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 |
---|---|---|---|---|---|---|---|---|
d65394d3791f0541253d5a6ecb9e9631c31cee7c | Test fix | Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnet5 | test/Microsoft.ApplicationInsights.AspNetCore.Tests/TelemetryInitializers/AspNetCoreEnvironmentTelemetryInitializerTests.cs | test/Microsoft.ApplicationInsights.AspNetCore.Tests/TelemetryInitializers/AspNetCoreEnvironmentTelemetryInitializerTests.cs | namespace Microsoft.ApplicationInsights.AspNetCore.Tests.TelemetryInitializers
{
using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Hosting.Internal;
using Xunit;
public class AspNetCoreEnvironmentTelemetryInitializerTests
{
[Fact]
public void InitializeDoesNotThrowIfHostingEnvironmentIsNull()
{
var initializer = new AspNetCoreEnvironmentTelemetryInitializer(null);
initializer.Initialize(new RequestTelemetry());
}
[Fact]
public void InitializeDoesNotOverrideExistingProperty()
{
var initializer = new AspNetCoreEnvironmentTelemetryInitializer(new HostingEnvironment() { EnvironmentName = "Production"});
var telemetry = new RequestTelemetry();
telemetry.Context.Properties.Add("AspNetCoreEnvironment", "Development");
initializer.Initialize(telemetry);
Assert.Equal("Development", telemetry.Context.GlobalProperties["AspNetCoreEnvironment"]);
}
[Fact]
public void InitializeSetsCurrentEnvironmentNameToProperty()
{
var initializer = new AspNetCoreEnvironmentTelemetryInitializer(new HostingEnvironment() { EnvironmentName = "Production"});
var telemetry = new RequestTelemetry();
initializer.Initialize(telemetry);
Assert.Equal("Production", telemetry.Context.GlobalProperties["AspNetCoreEnvironment"]);
}
}
}
| namespace Microsoft.ApplicationInsights.AspNetCore.Tests.TelemetryInitializers
{
using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Hosting.Internal;
using Xunit;
public class AspNetCoreEnvironmentTelemetryInitializerTests
{
[Fact]
public void InitializeDoesNotThrowIfHostingEnvironmentIsNull()
{
var initializer = new AspNetCoreEnvironmentTelemetryInitializer(null);
initializer.Initialize(new RequestTelemetry());
}
[Fact]
public void InitializeDoesNotOverrideExistingProperty()
{
var initializer = new AspNetCoreEnvironmentTelemetryInitializer(new HostingEnvironment() { EnvironmentName = "Production"});
var telemetry = new RequestTelemetry();
telemetry.Context.Properties.Add("AspNetCoreEnvironment", "Development");
initializer.Initialize(telemetry);
Assert.Equal("Development", telemetry.Context.Properties["AspNetCoreEnvironment"]);
}
[Fact]
public void InitializeSetsCurrentEnvironmentNameToProperty()
{
var initializer = new AspNetCoreEnvironmentTelemetryInitializer(new HostingEnvironment() { EnvironmentName = "Production"});
var telemetry = new RequestTelemetry();
initializer.Initialize(telemetry);
Assert.Equal("Production", telemetry.Context.Properties["AspNetCoreEnvironment"]);
}
}
}
| mit | C# |
e2316bb6343edc1f381009c7d3c4413dc29510a7 | remove some problems | olebg/Movie-Theater-Project | MovieTheater/MovieTheater.Framework/Core/Providers/JsonReader.cs | MovieTheater/MovieTheater.Framework/Core/Providers/JsonReader.cs | using MovieTheater.Framework.Core.Providers.Contracts;
using System.IO;
namespace MovieTheater.Framework.Core.Providers
{
public class JsonReader : IReader
{
public JsonReader(IReader reader, IWriter writer)
{
this.Reader = reader;
this.Writer = writer;
}
public IReader Reader { get; private set; }
public IWriter Writer { get; private set; }
public string Read()
{
this.Writer.Write("Enter path of JSON file:");
string path = this.Reader.Read();
StreamReader readJson = new StreamReader(path);
string jsonString = readJson.ReadToEnd();
return jsonString;
}
}
} | using MovieTheater.Framework.Core.Contracts;
using System.IO;
namespace MovieTheater.Framework.Core.Providers
{
public class JsonReader : IReader
{
public JsonReader(IReader reader, IWriter writer)
{
this.Reader = reader;
this.Writer = writer;
}
public IReader Reader { get; private set; }
public IWriter Writer { get; private set; }
public string Read()
{
this.Writer.Write("Enter path of JSON file:");
string path = this.Reader.Read();
StreamReader readJson = new StreamReader(path);
string jsonString = readJson.ReadToEnd();
return jsonString;
}
}
} | mit | C# |
8ec78688b80e8d1c92cc71a61a442e5c5c17c974 | Add empty actionParameters check (#148) | qianlifeng/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox,Wox-launcher/Wox | Wox.Core/Plugin/QueryBuilder.cs | Wox.Core/Plugin/QueryBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Wox.Plugin;
namespace Wox.Core.Plugin
{
public static class QueryBuilder
{
public static Query Build(string text, Dictionary<string, PluginPair> nonGlobalPlugins)
{
// replace multiple white spaces with one white space
var terms = text.Split(new[] { Query.TermSeperater }, StringSplitOptions.RemoveEmptyEntries);
if (terms.Length == 0)
{ // nothing was typed
return null;
}
var rawQuery = string.Join(Query.TermSeperater, terms);
string actionKeyword, search;
string possibleActionKeyword = terms[0];
List<string> actionParameters;
if (nonGlobalPlugins.TryGetValue(possibleActionKeyword, out var pluginPair) && !pluginPair.Metadata.Disabled)
{ // use non global plugin for query
actionKeyword = possibleActionKeyword;
actionParameters = terms.Skip(1).ToList();
search = actionParameters.Count > 0 ? rawQuery.Substring(actionKeyword.Length + 1) : string.Empty;
}
else
{ // non action keyword
actionKeyword = string.Empty;
actionParameters = terms.ToList();
search = rawQuery;
}
var query = new Query
{
Terms = terms,
RawQuery = rawQuery,
ActionKeyword = actionKeyword,
Search = search,
// Obsolete value initialisation
ActionName = actionKeyword,
ActionParameters = actionParameters
};
return query;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Wox.Plugin;
namespace Wox.Core.Plugin
{
public static class QueryBuilder
{
public static Query Build(string text, Dictionary<string, PluginPair> nonGlobalPlugins)
{
// replace multiple white spaces with one white space
var terms = text.Split(new[] { Query.TermSeperater }, StringSplitOptions.RemoveEmptyEntries);
if (terms.Length == 0)
{ // nothing was typed
return null;
}
var rawQuery = string.Join(Query.TermSeperater, terms);
string actionKeyword, search;
string possibleActionKeyword = terms[0];
List<string> actionParameters;
if (nonGlobalPlugins.TryGetValue(possibleActionKeyword, out var pluginPair) && !pluginPair.Metadata.Disabled)
{ // use non global plugin for query
actionKeyword = possibleActionKeyword;
actionParameters = terms.Skip(1).ToList();
search = rawQuery.Substring(actionKeyword.Length + 1);
}
else
{ // non action keyword
actionKeyword = string.Empty;
actionParameters = terms.ToList();
search = rawQuery;
}
var query = new Query
{
Terms = terms,
RawQuery = rawQuery,
ActionKeyword = actionKeyword,
Search = search,
// Obsolete value initialisation
ActionName = actionKeyword,
ActionParameters = actionParameters
};
return query;
}
}
} | mit | C# |
719b2424e0f90e1cd5f2a5c5a936d34f6b347d35 | Add json serialization for runtime configuration. | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver.DotNet/Config/Json/RuntimeConfiguration.cs | src/AsmResolver.DotNet/Config/Json/RuntimeConfiguration.cs | using System.IO;
using System.Text.Json;
namespace AsmResolver.DotNet.Config.Json
{
/// <summary>
/// Represents the root object of a runtime configuration, stored in a *.runtimeconfig.json file.
/// </summary>
public class RuntimeConfiguration
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>
/// Parses runtime configuration from a JSON file.
/// </summary>
/// <param name="path">The path to the runtime configuration file.</param>
/// <returns>The parsed runtime configuration.</returns>
public static RuntimeConfiguration FromFile(string path)
{
return FromJson(File.ReadAllText(path));
}
/// <summary>
/// Parses runtime configuration from a JSON string.
/// </summary>
/// <param name="json">The raw json string configuration file.</param>
/// <returns>The parsed runtime configuration.</returns>
public static RuntimeConfiguration FromJson(string json)
{
return JsonSerializer.Deserialize<RuntimeConfiguration>(json, JsonSerializerOptions);
}
/// <summary>
/// Gets or sets the runtime options.
/// </summary>
public RuntimeOptions RuntimeOptions
{
get;
set;
}
/// <summary>
/// Serializes the configuration to a JSON string.
/// </summary>
/// <returns>The JSON string.</returns>
public string ToJson()
{
return JsonSerializer.Serialize(this, JsonSerializerOptions);
}
/// <summary>
/// Writes the configuration to a file.
/// </summary>
/// <param name="path">The path to the JSON output file.</param>
public void Write(string path)
{
File.WriteAllText(path, ToJson());
}
}
}
| using System.IO;
using System.Text.Json;
namespace AsmResolver.DotNet.Config.Json
{
/// <summary>
/// Represents the root object of a runtime configuration, stored in a *.runtimeconfig.json file.
/// </summary>
public class RuntimeConfiguration
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>
/// Parses runtime configuration from a JSON file.
/// </summary>
/// <param name="path">The path to the runtime configuration file.</param>
/// <returns>The parsed runtime configuration.</returns>
public static RuntimeConfiguration FromFile(string path)
{
return FromJson(File.ReadAllText(path));
}
/// <summary>
/// Parses runtime configuration from a JSON string.
/// </summary>
/// <param name="json">The raw json string configuration file.</param>
/// <returns>The parsed runtime configuration.</returns>
public static RuntimeConfiguration FromJson(string json)
{
return JsonSerializer.Deserialize<RuntimeConfiguration>(json, JsonSerializerOptions);
}
/// <summary>
/// Gets or sets the runtime options.
/// </summary>
public RuntimeOptions RuntimeOptions
{
get;
set;
}
}
}
| mit | C# |
7531411597ebdeca92ccc67e7964c5c134acf862 | Fix syntax error | coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore | src/MiningCore/Persistence/Model/Projections/MinerStats.cs | src/MiningCore/Persistence/Model/Projections/MinerStats.cs | /*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace MiningCore.Persistence.Model.Projections
{
public class WorkerPerformanceStats
{
public double Hashrate { get; set; }
public double SharesPerSecond { get; set; }
}
public class WorkerPerformanceStatsContainer
{
public DateTime Created { get; set; }
public Dictionary<string, WorkerPerformanceStats> Workers { get; set; }
}
public class MinerStats
{
public ulong PendingShares { get; set; }
public decimal PendingBalance { get; set; }
public decimal TotalPaid { get; set; }
public Payment LastPayment { get; set; }
public WorkerPerformanceStatsContainer Performance { get; set; }
public MinerWorkerPerformanceStats[] PerformanceStats { get; set; }
}
}
| /*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace MiningCore.Persistence.Model.Projections
{
public class WorkerPerformanceStats
{
public double Hashrate { get; set; }
public double SharesPerSecond { get; set; }
}
public class WorkerPerformanceStatsContainer
{
public DateTime Created { get; set; }
public Dictionary<string, WorkerPerformanceStats> Workers { get; set; }
}
namespace MiningCore.Persistence.Model.Projections
{
public class MinerStats
{
public ulong PendingShares { get; set; }
public decimal PendingBalance { get; set; }
public decimal TotalPaid { get; set; }
public Payment LastPayment { get; set; }
public WorkerPerformanceStatsContainer Performance { get; set; }
public MinerWorkerPerformanceStats[] PerformanceStats { get; set; }
}
}
| mit | C# |
dd9a142e899030c6a53d0fd0275af6a57efd34f6 | Fix `TestSceneEditorSummaryTimeline` not displaying actual beatmap content | ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu | osu.Game.Tests/Visual/Editing/TestSceneEditorSummaryTimeline.cs | osu.Game.Tests/Visual/Editing/TestSceneEditorSummaryTimeline.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSummaryTimeline : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneEditorSummaryTimeline()
{
editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
}
protected override void LoadComplete()
{
base.LoadComplete();
AddStep("create timeline", () =>
{
// required for track
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Add(new SummaryTimeline
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 50)
});
});
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSummaryTimeline : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
private readonly EditorBeatmap editorBeatmap = new EditorBeatmap(new OsuBeatmap());
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Add(new SummaryTimeline
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 50)
});
}
}
}
| mit | C# |
ae1933db62507025b9fd09b8f1b824a6fcbb3fd7 | refactor GetBusyStatus | joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net | src/JoinRpg.WebPortal.Models/Characters/BusyStatusExtensions.cs | src/JoinRpg.WebPortal.Models/Characters/BusyStatusExtensions.cs | using System.Linq;
using JoinRpg.Data.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.PrimitiveTypes;
namespace JoinRpg.Web.Models.Characters
{
public static class BusyStatusExtensions
{
public static CharacterBusyStatusView GetBusyStatus(this Character character)
{
var characterType = character.IsAcceptingClaims ? CharacterType.Player : CharacterType.NonPlayer;
return (CharacterType: characterType, character) switch
{
{ CharacterType: CharacterType.NonPlayer } => CharacterBusyStatusView.Npc,
{ CharacterType: CharacterType.Player, character: { ApprovedClaim: not null } } => CharacterBusyStatusView.HasPlayer,
{ CharacterType: CharacterType.Player } when character.Claims.Any(c => c.ClaimStatus.IsActive()) => CharacterBusyStatusView.Discussed,
{ CharacterType: CharacterType.Player } => CharacterBusyStatusView.NoClaims,
_ => CharacterBusyStatusView.Unknown,
};
}
public static CharacterBusyStatusView GetBusyStatus(this CharacterView character)
{
return character switch
{
{ CharacterTypeInfo: { CharacterType: CharacterType.NonPlayer } } => CharacterBusyStatusView.Npc,
{ CharacterTypeInfo: { CharacterType: CharacterType.Player }, ApprovedClaim: not null } => CharacterBusyStatusView.HasPlayer,
{ CharacterTypeInfo: { CharacterType: CharacterType.Player }, } when character.Claims.Any(c => c.IsActive) => CharacterBusyStatusView.Discussed,
{ CharacterTypeInfo: { CharacterType: CharacterType.Player } } => CharacterBusyStatusView.NoClaims,
_ => CharacterBusyStatusView.Unknown,
};
}
}
}
| using System.Linq;
using JoinRpg.Data.Interfaces;
using JoinRpg.DataModel;
namespace JoinRpg.Web.Models.Characters
{
public static class BusyStatusExtensions
{
public static CharacterBusyStatusView GetBusyStatus(this Character character)
{
if (character.ApprovedClaim != null)
{
return CharacterBusyStatusView.HasPlayer;
}
if (character.Claims.Any(c => c.ClaimStatus.IsActive()))
{
return CharacterBusyStatusView.Discussed;
}
if (character.IsAcceptingClaims)
{
return CharacterBusyStatusView.NoClaims;
}
return CharacterBusyStatusView.Npc;
}
public static CharacterBusyStatusView GetBusyStatus(this CharacterView character)
{
if (character.ApprovedClaim != null)
{
return CharacterBusyStatusView.HasPlayer;
}
if (character.Claims.Any(c => c.IsActive))
{
return CharacterBusyStatusView.Discussed;
}
if (character.CharacterTypeInfo.IsAcceptingClaims)
{
return CharacterBusyStatusView.NoClaims;
}
return CharacterBusyStatusView.Npc;
}
}
}
| mit | C# |
97863cba3731e5eeebbe7ecdb650228dc52968be | fix minor introduced issue w/ admin landing | ucdavis/Badges,ucdavis/Badges | Badges/Areas/Admin/Controllers/LandingController.cs | Badges/Areas/Admin/Controllers/LandingController.cs | using System.Web.Mvc;
using Badges.Core.Domain;
using Badges.Controllers;
using Badges.Core.Repositories;
namespace Badges.Areas.Admin.Controllers
{
[Authorize(Roles=RoleNames.Administrator)]
public class LandingController : ApplicationController
{
//Admin/Landing
public LandingController(IRepositoryFactory repositoryFactory) : base(repositoryFactory)
{
}
public ActionResult Index()
{
return View();
}
}
}
| using System.Web.Mvc;
using Badges.Core.Domain;
namespace Badges.Areas.Admin.Controllers
{
[Authorize(Roles=RoleNames.Administrator)]
public class LandingController : Controller
{
//Admin/Landing
public ActionResult Index()
{
return View();
}
}
}
| mpl-2.0 | C# |
c1c83cd20a216bfb9501b4baea655f2af95f7b86 | Update version file with version number. | PaulTrampert/PTrampert.MongoDb.Configuration | Version.cs | Version.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyVersion("1.0.0.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyVersion("1.0.0.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0-build8")]
| mit | C# |
48c9f0d646fe66fef49a011a28a27d3952a52bb1 | Fix server lobby music exception. Audio resources aren't shipped with the server, so the check is essentially useless. | 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/GameTicking/GameTicker.LobbyMusic.cs | Content.Server/GameTicking/GameTicker.LobbyMusic.cs | using Content.Shared.Audio;
using Robust.Shared.Random;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameTicking
{
public partial class GameTicker
{
private const string LobbyMusicCollection = "LobbyMusic";
[ViewVariables]
private bool _lobbyMusicInitialized = false;
[ViewVariables]
private SoundCollectionPrototype _lobbyMusicCollection = default!;
[ViewVariables]
public string? LobbySong { get; private set; }
private void InitializeLobbyMusic()
{
DebugTools.Assert(!_lobbyMusicInitialized);
_lobbyMusicCollection = _prototypeManager.Index<SoundCollectionPrototype>(LobbyMusicCollection);
// Now that the collection is set, the lobby music has been initialized and we can choose a random song.
_lobbyMusicInitialized = true;
ChooseRandomLobbySong();
}
/// <summary>
/// Sets the current lobby song, or stops it if null.
/// </summary>
/// <param name="song">The lobby song to play, or null to stop any lobby songs.</param>
public void SetLobbySong(string? song)
{
DebugTools.Assert(_lobbyMusicInitialized);
if (song == null)
{
LobbySong = null;
return;
// TODO GAMETICKER send song stop event
}
LobbySong = song;
// TODO GAMETICKER send song change event
}
/// <summary>
/// Plays a random song from the LobbyMusic sound collection.
/// </summary>
public void ChooseRandomLobbySong()
{
DebugTools.Assert(_lobbyMusicInitialized);
SetLobbySong(_robustRandom.Pick(_lobbyMusicCollection.PickFiles).ToString());
}
/// <summary>
/// Stops the current lobby song being played.
/// </summary>
public void StopLobbySong()
{
SetLobbySong(null);
}
}
}
| using Content.Shared.Audio;
using Robust.Shared.ContentPack;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Random;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameTicking
{
public partial class GameTicker
{
[Dependency] private readonly IResourceManager _resourceManager = default!;
private const string LobbyMusicCollection = "LobbyMusic";
[ViewVariables]
private bool _lobbyMusicInitialized = false;
[ViewVariables]
private SoundCollectionPrototype _lobbyMusicCollection = default!;
[ViewVariables]
public string? LobbySong { get; private set; }
private void InitializeLobbyMusic()
{
DebugTools.Assert(!_lobbyMusicInitialized);
_lobbyMusicCollection = _prototypeManager.Index<SoundCollectionPrototype>(LobbyMusicCollection);
// Now that the collection is set, the lobby music has been initialized and we can choose a random song.
_lobbyMusicInitialized = true;
ChooseRandomLobbySong();
}
/// <summary>
/// Sets the current lobby song, or stops it if null.
/// </summary>
/// <param name="song">The lobby song to play, or null to stop any lobby songs.</param>
public void SetLobbySong(string? song)
{
DebugTools.Assert(_lobbyMusicInitialized);
if (song == null)
{
LobbySong = null;
return;
// TODO GAMETICKER send song stop event
}
if (!_resourceManager.ContentFileExists(song))
{
Logger.ErrorS("ticker", $"Tried to set lobby song to \"{song}\", which doesn't exist!");
return;
}
LobbySong = song;
// TODO GAMETICKER send song change event
}
/// <summary>
/// Plays a random song from the LobbyMusic sound collection.
/// </summary>
public void ChooseRandomLobbySong()
{
DebugTools.Assert(_lobbyMusicInitialized);
SetLobbySong(_robustRandom.Pick(_lobbyMusicCollection.PickFiles).ToString());
}
/// <summary>
/// Stops the current lobby song being played.
/// </summary>
public void StopLobbySong()
{
SetLobbySong(null);
}
}
}
| mit | C# |
bbbeed8dd30bd3ed2dfd091b51ecf33a49b0a760 | Delete unused static field (#21965) | zhenlan/corefx,Jiayili1/corefx,the-dwyer/corefx,mmitche/corefx,Jiayili1/corefx,tijoytom/corefx,tijoytom/corefx,ViktorHofer/corefx,twsouthwick/corefx,nchikanov/corefx,jlin177/corefx,fgreinacher/corefx,shimingsg/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,mmitche/corefx,mazong1123/corefx,DnlHarvey/corefx,the-dwyer/corefx,axelheer/corefx,ViktorHofer/corefx,rubo/corefx,richlander/corefx,stone-li/corefx,seanshpark/corefx,twsouthwick/corefx,cydhaselton/corefx,Ermiar/corefx,parjong/corefx,mazong1123/corefx,zhenlan/corefx,DnlHarvey/corefx,the-dwyer/corefx,yizhang82/corefx,tijoytom/corefx,cydhaselton/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,stone-li/corefx,mazong1123/corefx,parjong/corefx,twsouthwick/corefx,Ermiar/corefx,rubo/corefx,ViktorHofer/corefx,ViktorHofer/corefx,Ermiar/corefx,fgreinacher/corefx,cydhaselton/corefx,nchikanov/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,ptoonen/corefx,seanshpark/corefx,wtgodbe/corefx,ViktorHofer/corefx,DnlHarvey/corefx,seanshpark/corefx,zhenlan/corefx,the-dwyer/corefx,fgreinacher/corefx,the-dwyer/corefx,richlander/corefx,tijoytom/corefx,shimingsg/corefx,seanshpark/corefx,shimingsg/corefx,Jiayili1/corefx,tijoytom/corefx,ptoonen/corefx,jlin177/corefx,wtgodbe/corefx,ravimeda/corefx,wtgodbe/corefx,Jiayili1/corefx,rubo/corefx,richlander/corefx,jlin177/corefx,twsouthwick/corefx,yizhang82/corefx,MaggieTsang/corefx,jlin177/corefx,nchikanov/corefx,wtgodbe/corefx,ViktorHofer/corefx,MaggieTsang/corefx,ravimeda/corefx,shimingsg/corefx,nchikanov/corefx,krk/corefx,zhenlan/corefx,mazong1123/corefx,nchikanov/corefx,fgreinacher/corefx,MaggieTsang/corefx,ericstj/corefx,JosephTremoulet/corefx,nbarbettini/corefx,Ermiar/corefx,axelheer/corefx,tijoytom/corefx,krk/corefx,shimingsg/corefx,BrennanConroy/corefx,krk/corefx,axelheer/corefx,ptoonen/corefx,mazong1123/corefx,rubo/corefx,richlander/corefx,mazong1123/corefx,Ermiar/corefx,zhenlan/corefx,ravimeda/corefx,krk/corefx,ericstj/corefx,nbarbettini/corefx,cydhaselton/corefx,ravimeda/corefx,nchikanov/corefx,parjong/corefx,ericstj/corefx,jlin177/corefx,Ermiar/corefx,Jiayili1/corefx,DnlHarvey/corefx,DnlHarvey/corefx,mmitche/corefx,zhenlan/corefx,krk/corefx,JosephTremoulet/corefx,axelheer/corefx,wtgodbe/corefx,JosephTremoulet/corefx,tijoytom/corefx,twsouthwick/corefx,ericstj/corefx,richlander/corefx,yizhang82/corefx,Jiayili1/corefx,axelheer/corefx,ravimeda/corefx,nbarbettini/corefx,shimingsg/corefx,stone-li/corefx,jlin177/corefx,the-dwyer/corefx,yizhang82/corefx,krk/corefx,stone-li/corefx,parjong/corefx,seanshpark/corefx,wtgodbe/corefx,DnlHarvey/corefx,ptoonen/corefx,MaggieTsang/corefx,mmitche/corefx,Jiayili1/corefx,ravimeda/corefx,yizhang82/corefx,ptoonen/corefx,richlander/corefx,parjong/corefx,parjong/corefx,nbarbettini/corefx,JosephTremoulet/corefx,ericstj/corefx,mazong1123/corefx,ericstj/corefx,twsouthwick/corefx,krk/corefx,the-dwyer/corefx,BrennanConroy/corefx,rubo/corefx,richlander/corefx,nchikanov/corefx,cydhaselton/corefx,nbarbettini/corefx,wtgodbe/corefx,zhenlan/corefx,axelheer/corefx,mmitche/corefx,DnlHarvey/corefx,ravimeda/corefx,parjong/corefx,yizhang82/corefx,ericstj/corefx,nbarbettini/corefx,yizhang82/corefx,stone-li/corefx,JosephTremoulet/corefx,stone-li/corefx,MaggieTsang/corefx,mmitche/corefx,cydhaselton/corefx,jlin177/corefx,seanshpark/corefx,BrennanConroy/corefx,twsouthwick/corefx,ptoonen/corefx,shimingsg/corefx,stone-li/corefx,nbarbettini/corefx,seanshpark/corefx,cydhaselton/corefx,Ermiar/corefx | src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs | src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
internal partial class Interop
{
internal partial class Kernel32
{
/// <summary>
/// Does not allow access to non-file devices. This disallows DOS devices like "con:", "com1:",
/// "lpt1:", etc. Use this to avoid security problems, like allowing a web client asking a server
/// for "http://server/com1.aspx" and then causing a worker process to hang.
/// </summary>
[System.Security.SecurityCritical] // auto-generated
internal static SafeFileHandle SafeCreateFile(
string lpFileName,
int dwDesiredAccess,
System.IO.FileShare dwShareMode,
ref SECURITY_ATTRIBUTES securityAttrs,
FileMode dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile)
{
SafeFileHandle handle = UnsafeCreateFile(lpFileName, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if (!handle.IsInvalid)
{
int fileType = GetFileType(handle);
if (fileType != FileTypes.FILE_TYPE_DISK)
{
handle.Dispose();
throw new NotSupportedException(SR.NotSupported_FileStreamOnNonFiles);
}
}
return handle;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
internal partial class Interop
{
internal partial class Kernel32
{
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
/// <summary>
/// Does not allow access to non-file devices. This disallows DOS devices like "con:", "com1:",
/// "lpt1:", etc. Use this to avoid security problems, like allowing a web client asking a server
/// for "http://server/com1.aspx" and then causing a worker process to hang.
/// </summary>
[System.Security.SecurityCritical] // auto-generated
internal static SafeFileHandle SafeCreateFile(
string lpFileName,
int dwDesiredAccess,
System.IO.FileShare dwShareMode,
ref SECURITY_ATTRIBUTES securityAttrs,
FileMode dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile)
{
SafeFileHandle handle = UnsafeCreateFile(lpFileName, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if (!handle.IsInvalid)
{
int fileType = GetFileType(handle);
if (fileType != FileTypes.FILE_TYPE_DISK)
{
handle.Dispose();
throw new NotSupportedException(SR.NotSupported_FileStreamOnNonFiles);
}
}
return handle;
}
}
}
| mit | C# |
2a609dba85dcf3d8583b845589b1c9239580155a | Use InvariantCulture: | SuperJMN/Avalonia,susloparovdenis/Perspex,danwalmsley/Perspex,jkoritzinsky/Avalonia,tshcherban/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,kekekeks/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,punker76/Perspex,AvaloniaUI/Avalonia,jazzay/Perspex,wieslawsoltes/Perspex,akrisiun/Perspex,susloparovdenis/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,MrDaedra/Avalonia,grokys/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,OronDF343/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,OronDF343/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,kekekeks/Perspex,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia | src/Markup/Perspex.Markup.Xaml/Converters/TimeSpanTypeConverter.cs | src/Markup/Perspex.Markup.Xaml/Converters/TimeSpanTypeConverter.cs | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media;
namespace Perspex.Markup.Xaml.Converters
{
public class TimeSpanTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
{
var valueStr = (string)value;
if (!valueStr.Contains(":"))
{
// shorthand seconds format (ie. "0.25")
var secs = double.Parse(valueStr, CultureInfo.InvariantCulture);
return TimeSpan.FromSeconds(secs);
}
return TimeSpan.Parse(valueStr);
}
public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
} | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media;
namespace Perspex.Markup.Xaml.Converters
{
public class TimeSpanTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
{
var valueStr = (string)value;
if (!valueStr.Contains(":"))
{
// shorthand seconds format (ie. "0.25")
var secs = double.Parse(valueStr);
return TimeSpan.FromSeconds(secs);
}
return TimeSpan.Parse(valueStr);
}
public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
} | mit | C# |
9d53460315a044d82e5ba94c3a614a81b60d9b9b | Fix regression & enable ClearInitLocals in System.Text.RegularExpressions (#27146) | ruben-ayrapetyan/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,wtgodbe/coreclr,krk/coreclr,wtgodbe/coreclr,cshung/coreclr,krk/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,mmitche/coreclr,cshung/coreclr,poizan42/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,ruben-ayrapetyan/coreclr,mmitche/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,poizan42/coreclr,mmitche/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,krk/coreclr,poizan42/coreclr,krk/coreclr,wtgodbe/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr | src/mscorlib/shared/System/Collections/Generic/ValueListBuilder.cs | src/mscorlib/shared/System/Collections/Generic/ValueListBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
internal ref partial struct ValueListBuilder<T>
{
private Span<T> _span;
private T[] _arrayFromPool;
private int _pos;
public ValueListBuilder(Span<T> initialSpan)
{
_span = initialSpan;
_arrayFromPool = null;
_pos = 0;
}
public int Length => _pos;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(T item)
{
int pos = _pos;
if (pos >= _span.Length)
Grow();
_span[pos] = item;
_pos = pos + 1;
}
public ReadOnlySpan<T> AsReadOnlySpan()
{
return _span.Slice(0, _pos);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
if (_arrayFromPool != null)
{
ArrayPool<T>.Shared.Return(_arrayFromPool);
_arrayFromPool = null;
}
}
private void Grow()
{
T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2);
bool success = _span.TryCopyTo(array);
Debug.Assert(success);
T[] toReturn = _arrayFromPool;
_span = _arrayFromPool = array;
if (toReturn != null)
{
ArrayPool<T>.Shared.Return(toReturn);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
internal ref struct ValueListBuilder<T>
{
private Span<T> _span;
private T[] _arrayFromPool;
private int _pos;
public ValueListBuilder(Span<T> initialSpan)
{
_span = initialSpan;
_arrayFromPool = null;
_pos = 0;
}
public int Length => _pos;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(T item)
{
int pos = _pos;
if (pos >= _span.Length)
Grow();
_span[pos] = item;
_pos = pos + 1;
}
public ReadOnlySpan<T> AsReadOnlySpan()
{
return _span.Slice(0, _pos);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
if (_arrayFromPool != null)
{
ArrayPool<T>.Shared.Return(_arrayFromPool);
_arrayFromPool = null;
}
}
private void Grow()
{
T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2);
bool success = _span.TryCopyTo(array);
Debug.Assert(success);
T[] toReturn = _arrayFromPool;
_span = _arrayFromPool = array;
if (toReturn != null)
{
ArrayPool<T>.Shared.Return(toReturn);
}
}
}
}
| mit | C# |
f75038e51e7083f12fb0f64684f90ae406186e99 | Teste Alteração | kaiosilveira/CashFlow,kaiosilveira/CashFlow,kaiosilveira/CashFlow | CashFlow/CashFlow.DataAccess/Factories/ConnectionFactory.cs | CashFlow/CashFlow.DataAccess/Factories/ConnectionFactory.cs | using CashFlow.Domain.Model.Enumerators;
using CashFlow.NetFramework.Providers;
using System.Data;
using System.Data.SqlClient;
namespace CashFlow.DataAccess.Factories
{
public class ConnectionFactory
{
public IDbConnection GetConnection(ConnectionStrings connectionString)
{
var con = new SqlConnection(ConfigurationProvider.GetConnectionString(connectionString));
con.Open();
return con;
}
}
}
| using CashFlow.Domain.Model.Enumerators;
using CashFlow.NetFramework.Providers;
using System.Data;
using System.Data.SqlClient;
namespace CashFlow.DataAccess.Factories
{
public class ConnectionFactory
{
public IDbConnection GetConnection(ConnectionStrings connectionString)
{
var con = new SqlConnection(ConfigurationProvider.GetConnectionString(connectionString));
con.Open();
return con;
}
}
}
| mit | C# |
6a50831311e1ae8746534b7f990189a4e837af9f | remove exception | charlenni/Mapsui,charlenni/Mapsui | Mapsui.Nts/Extensions/CoordinateExtensions.cs | Mapsui.Nts/Extensions/CoordinateExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NetTopologySuite.Geometries;
namespace Mapsui.Nts.Extensions
{
public static class CoordinateExtensions
{
public static MPoint ToMPoint(this Coordinate coordinate)
{
return new MPoint(coordinate.X, coordinate.Y);
}
public static Point ToPoint(this Coordinate coordinate)
{
return new Point(coordinate.X, coordinate.Y);
}
public static LineString ToLineString(this IEnumerable<Coordinate> coordinates)
{
var list = coordinates.ToList();
if (list.Count == 1)
list.Add(list[0].Copy());
return new LineString(list.ToArray());
}
public static LinearRing ToLinearRing(this IEnumerable<Coordinate> coordinates)
{
if (coordinates.Count() == 0)
throw new Exception("coordinates can not be length 0");
var list = coordinates.ToList(); // Not using ToList could be more performant
if (list.Count == 1)
list.Add(list[0].Copy()); // LineString needs at least two coordinates
if (list.Count == 2)
list.Add(list[0].Copy()); // LinearRing needs at least three coordinates
if (!list.First().Equals2D(list.Last()))
list.Add(list[0].Copy()); // LinearRing needs to be 'closed' (first should equal last)
return new LinearRing(list.ToArray());
}
public static Polygon ToPolygon(this IEnumerable<Coordinate> coordinates, IEnumerable<IEnumerable<Coordinate>>? holes = null)
{
if (holes == null || holes.Count() == 0)
return new Polygon(coordinates.ToLinearRing());
return new Polygon(coordinates.ToLinearRing(), holes.Select(h => h.ToLinearRing()).ToArray());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using NetTopologySuite.Geometries;
namespace Mapsui.Nts.Extensions
{
public static class CoordinateExtensions
{
public static MPoint ToMPoint(this Coordinate coordinate)
{
return new MPoint(coordinate.X, coordinate.Y);
}
public static Point ToPoint(this Coordinate coordinate)
{
return new Point(coordinate.X, coordinate.Y);
}
public static LineString ToLineString(this IEnumerable<Coordinate> coordinates)
{
if (coordinates.Count() == 0)
throw new Exception("coordinates can not be length 0");
var list = coordinates.ToList();
if (list.Count == 1)
list.Add(list[0].Copy());
return new LineString(list.ToArray());
}
public static LinearRing ToLinearRing(this IEnumerable<Coordinate> coordinates)
{
if (coordinates.Count() == 0)
throw new Exception("coordinates can not be length 0");
var list = coordinates.ToList(); // Not using ToList could be more performant
if (list.Count == 1)
list.Add(list[0].Copy()); // LineString needs at least two coordinates
if (list.Count == 2)
list.Add(list[0].Copy()); // LinearRing needs at least three coordinates
if (!list.First().Equals2D(list.Last()))
list.Add(list[0].Copy()); // LinearRing needs to be 'closed' (first should equal last)
return new LinearRing(list.ToArray());
}
public static Polygon ToPolygon(this IEnumerable<Coordinate> coordinates, IEnumerable<IEnumerable<Coordinate>>? holes = null)
{
if (holes == null || holes.Count() == 0)
return new Polygon(coordinates.ToLinearRing());
return new Polygon(coordinates.ToLinearRing(), holes.Select(h => h.ToLinearRing()).ToArray());
}
}
}
| mit | C# |
2edc818fca3c676c9bb209c315272981db98b14b | add jsonp | zhouyongtao/webapi-learning,zhouyongtao/webapi-learning,zhouyongtao/webapi-learning | webapi-learning/Global.asax.cs | webapi-learning/Global.asax.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApiContrib.Formatting.Jsonp;
namespace webapi_learning
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//add jsonp
GlobalConfiguration.Configuration.AddJsonpFormatter();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace webapi_learning
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| mit | C# |
e3ff25a3eebeb5de0f7c1d852e0636a1e7014aee | Fix Stackoverflow. | bchavez/SharpFlame,bchavez/SharpFlame | source/Eto.Gl.Gtk/GtkGlSurfaceHandler.cs | source/Eto.Gl.Gtk/GtkGlSurfaceHandler.cs | using Eto.Drawing;
using Eto.Platform.GtkSharp;
namespace Eto.Gl.Gtk
{
public class GtkGlSurfaceHandler : GtkControl<GLDrawingArea, GLSurface>, IGLSurfacePlatformHandler
{
public override GLDrawingArea CreateControl()
{
var c = new GLDrawingArea();
c.Initialized += (sender, args) => Widget.OnInitialized(sender, args);
c.Resize += (sender, args) => Widget.OnResize(sender, args);
c.ShuttingDown += (sender, args) => Widget.OnShuttingDown(sender, args);
return c;
}
public Size GLSize
{
get { return this.Control.GLSize; }
set { this.Control.GLSize = value; }
}
public bool IsInitialized
{
get { return this.Control.IsInitialized; }
}
public void MakeCurrent()
{
this.Control.MakeCurrent();
}
public void SwapBuffers()
{
this.Control.SwapBuffers();
}
}
}
| using Eto.Drawing;
using Eto.Platform.GtkSharp;
namespace Eto.Gl.Gtk
{
public class GtkGlSurfaceHandler : GtkControl<GLDrawingArea, GLSurface>, IGLSurfacePlatformHandler
{
public override GLDrawingArea CreateControl()
{
var c = new GLDrawingArea();
c.Initialized += (sender, args) => Widget.OnInitialized(sender, args);
c.Resize += (sender, args) => Widget.OnResize(sender, args);
c.ShuttingDown += (sender, args) => Widget.OnShuttingDown(sender, args);
return c;
}
public Size GLSize
{
get { return this.Control.GLSize; }
set { this.GLSize = value; }
}
public bool IsInitialized
{
get { return this.Control.IsInitialized; }
}
public void MakeCurrent()
{
this.Control.MakeCurrent();
}
public void SwapBuffers()
{
this.Control.SwapBuffers();
}
}
}
| mit | C# |
1451b2743ebf3fd77a42ce93d498e4915eecf075 | Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | autofac/Autofac.SignalR | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.SignalR")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.SignalR")]
[assembly: AssemblyDescription("Autofac ASP.NET SignalR Integration")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)] | mit | C# |
c8fbbd37b3ff1023478d9f989ffbdf4d16ae7d64 | adjust assembly version to follow the module version | sachatrauwaen/openform,sachatrauwaen/openform,sachatrauwaen/openform | Properties/AssemblyInfo.cs | 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("OpenForm")]
[assembly: AssemblyDescription("OpenForm Module for DNN")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Satrabel")]
[assembly: AssemblyProduct("OpenForm")]
[assembly: AssemblyCopyright("Copyright © 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ef01dd5-84a1-49f3-9232-067440288455")]
// 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("03.00.01.00")]
[assembly: AssemblyFileVersion("03.00.01.00")]
| 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("OpenForm")]
[assembly: AssemblyDescription("OpenForm Module for DNN")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Satrabel")]
[assembly: AssemblyProduct("OpenForm")]
[assembly: AssemblyCopyright("Copyright © 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ef01dd5-84a1-49f3-9232-067440288455")]
// 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("02.01.03.00")]
[assembly: AssemblyFileVersion("02.01.03.00")]
| mit | C# |
34d8e200a453c5019372670a52cb09dcd1a7bf53 | Adjust osu!mania scroll speed defaults to be more sane (#6062) | smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,peppy/osu,EVAST9919/osu,smoogipoo/osu,ppy/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,NeoAdonis/osu,2yangk23/osu | osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs | osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.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.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaRulesetSetting.ScrollTime, 1500.0, 50.0, 5000.0, 50.0);
Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection
}
}
| // 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.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(ManiaRulesetSetting.ScrollTime, 2250.0, 50.0, 10000.0, 50.0);
Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection
}
}
| mit | C# |
fcd5c736d91b78c830f69d8a162d7d353787bd78 | send using the fake mailtrap smtp | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Core/Services/MailService.cs | Anlab.Core/Services/MailService.cs | using System.Threading.Tasks;
using Anlab.Core.Data;
using Anlab.Core.Domain;
using MailKit.Net.Smtp;
using MimeKit;
namespace Anlab.Core.Services {
public interface IMailService
{
Task EnqueueMessageAsync(MailMessage message);
void SendMessage(MailMessage mailMessage);
}
public class MailService : IMailService
{
private readonly ApplicationDbContext _dbContext;
public MailService(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task EnqueueMessageAsync(MailMessage message)
{
_dbContext.Add(message);
await _dbContext.SaveChangesAsync();
}
public void SendMessage(MailMessage mailMessage) {
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Anlab", "[email protected]"));
message.To.Add (new MailboxAddress(mailMessage.SendTo));
message.Subject = mailMessage.Subject;
message.Body = new TextPart("html") { Text = mailMessage.Body };
using (var client = new SmtpClient ()) {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
// TODO: use authenticated STMP
client.Connect("smtp.mailtrap.io", 2525);
// client.Connect ("smtp.ucdavis.edu", 587, false);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("b8a905cbb77fa1", "64d1a775a037f2");
client.Send (message);
client.Disconnect (true);
}
}
}
} | using System.Threading.Tasks;
using Anlab.Core.Data;
using Anlab.Core.Domain;
using MailKit.Net.Smtp;
using MimeKit;
namespace Anlab.Core.Services {
public interface IMailService
{
Task EnqueueMessageAsync(MailMessage message);
void SendMessage(MailMessage mailMessage);
}
public class MailService : IMailService
{
private readonly ApplicationDbContext _dbContext;
public MailService(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task EnqueueMessageAsync(MailMessage message)
{
_dbContext.Add(message);
await _dbContext.SaveChangesAsync();
}
public void SendMessage(MailMessage mailMessage) {
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Anlab", "[email protected]"));
message.To.Add (new MailboxAddress(mailMessage.SendTo));
message.Subject = mailMessage.Subject;
message.Body = new TextPart("html") { Text = mailMessage.Body };
using (var client = new SmtpClient ()) {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
// TODO: use authenticated STMP
client.Connect("smtp.ucdavis.edu", 25, false);
// client.Connect ("smtp.ucdavis.edu", 587, false);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
// client.Authenticate ("joey", "password");
client.Send (message);
client.Disconnect (true);
}
}
}
} | mit | C# |
4464a36daf79031ba27123b5044a96134191f8a3 | Update Cláudio Silva | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/ClaudioSilva.cs | src/Firehose.Web/Authors/ClaudioSilva.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 ClaudioSilva : IAmAMicrosoftMVP
{
public string FirstName => "Cláudio";
public string LastName => "Silva";
public string ShortBioOrTagLine => "SQL Server DBA and PowerShell MVP who loves to automate any process that needs to be done more than a couple of times.";
public string StateOrRegion => "Sintra, Portugal";
public string EmailAddress => string.Empty;
public string TwitterHandle => "claudioessilva";
public string GravatarHash => "c01100dc9b797cc424e48ca9c5ecb76f";
public string GitHubHandle => "claudioessilva";
public GeoPosition Position => new GeoPosition(38.754074938, -9.2808723);
public Uri WebSite => new Uri("https://claudioessilva.eu");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://claudioessilva.eu/category/powershell/feed/"); }
}
}
}
| 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 ClaudioSilva : IAmAMicrosoftMVP
{
public string FirstName => "Cláudio";
public string LastName => "Silva";
public string ShortBioOrTagLine => "SQL Server DBA who loves to automate any process that needs to be done more than a couple of times.";
public string StateOrRegion => "Sintra, Portugal";
public string EmailAddress => string.Empty;
public string TwitterHandle => "claudioessilva";
public string GravatarHash => "c01100dc9b797cc424e48ca9c5ecb76f";
public string GitHubHandle => "claudioessilva";
public GeoPosition Position => new GeoPosition(38.754074938, -9.2808723);
public Uri WebSite => new Uri("https://claudioessilva.eu");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://claudioessilva.eu/category/powershell/feed/"); }
}
}
}
| mit | C# |
842e060d883e27ffb115b5923689bb7e10ac5f55 | Update assembly version. | LogosBible/LogosGit | src/Logos.Git/Properties/AssemblyInfo.cs | src/Logos.Git/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Logos.Git")]
[assembly: AssemblyDescription("Utility code for working with local git repos and the GitHub web API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Logos Bible Software")]
[assembly: AssemblyProduct("Logos.Git")]
[assembly: AssemblyCopyright("Copyright 2013 Logos Bible Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("0.4.0")]
[assembly: AssemblyFileVersion("0.4.0")]
[assembly: AssemblyInformationalVersion("0.4.0")]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Logos.Git")]
[assembly: AssemblyDescription("Utility code for working with local git repos and the GitHub web API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Logos Bible Software")]
[assembly: AssemblyProduct("Logos.Git")]
[assembly: AssemblyCopyright("Copyright 2013 Logos Bible Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("0.3.0")]
[assembly: AssemblyFileVersion("0.3.0")]
[assembly: AssemblyInformationalVersion("0.3.0")]
| mit | C# |
23da1cbd1f519d4f57251958f7a8dd270656ad04 | Correct proxy type in `InterfaceProxy.Invocation` | Moq/moq4 | src/Moq/ProxyFactories/InterfaceProxy.cs | src/Moq/ProxyFactories/InterfaceProxy.cs | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
namespace Moq.Internals
{
/// <summary>Do not use. (Moq requires this class so that <see langword="object"/> methods can be set up on interface mocks.)</summary>
// NOTE: This type is actually specific to our DynamicProxy implementation of `ProxyFactory`.
// This type needs to be accessible to the generated interface proxy types because they will inherit from it. If user code
// is not strong-named, then DynamicProxy will put at least some generated types inside a weak-named assembly. Strong-named
// assemblies such as Moq's cannot reference weak-named assemblies, so we cannot use `[assembly: InternalsVisibleTo]`
// to make this type accessible. Therefore we need to declare it as public.
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class InterfaceProxy
{
private static MethodInfo equalsMethod = typeof(object).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);
private static MethodInfo getHashCodeMethod = typeof(object).GetMethod("GetHashCode", BindingFlags.Public | BindingFlags.Instance);
private static MethodInfo toStringMethod = typeof(object).GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance);
/// <summary/>
[DebuggerHidden]
public sealed override bool Equals(object obj)
{
// Forward this call to the interceptor, so that `object.Equals` can be set up.
var interceptor = (IInterceptor)((IProxy)this).Interceptor;
var invocation = new Invocation(this.GetType(), equalsMethod, obj);
interceptor.Intercept(invocation);
return (bool)invocation.ReturnValue;
}
/// <summary/>
[DebuggerHidden]
public sealed override int GetHashCode()
{
// Forward this call to the interceptor, so that `object.GetHashCode` can be set up.
var interceptor = (IInterceptor)((IProxy)this).Interceptor;
var invocation = new Invocation(this.GetType(), getHashCodeMethod);
interceptor.Intercept(invocation);
return (int)invocation.ReturnValue;
}
/// <summary/>
[DebuggerHidden]
public sealed override string ToString()
{
// Forward this call to the interceptor, so that `object.ToString` can be set up.
var interceptor = (IInterceptor)((IProxy)this).Interceptor;
var invocation = new Invocation(this.GetType(), toStringMethod);
interceptor.Intercept(invocation);
return (string)invocation.ReturnValue;
}
private sealed class Invocation : Moq.Invocation
{
private static object[] noArguments = new object[0];
public Invocation(Type proxyType, MethodInfo method, params object[] arguments)
: base(proxyType, method, arguments)
{
}
public Invocation(Type proxyType, MethodInfo method)
: base(proxyType, method, noArguments)
{
}
public override void Return() { }
public override void Return(object value)
{
this.SetReturnValue(value);
}
public override void ReturnBase() { }
}
}
}
| // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
namespace Moq.Internals
{
/// <summary>Do not use. (Moq requires this class so that <see langword="object"/> methods can be set up on interface mocks.)</summary>
// NOTE: This type is actually specific to our DynamicProxy implementation of `ProxyFactory`.
// This type needs to be accessible to the generated interface proxy types because they will inherit from it. If user code
// is not strong-named, then DynamicProxy will put at least some generated types inside a weak-named assembly. Strong-named
// assemblies such as Moq's cannot reference weak-named assemblies, so we cannot use `[assembly: InternalsVisibleTo]`
// to make this type accessible. Therefore we need to declare it as public.
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class InterfaceProxy
{
private static MethodInfo equalsMethod = typeof(object).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);
private static MethodInfo getHashCodeMethod = typeof(object).GetMethod("GetHashCode", BindingFlags.Public | BindingFlags.Instance);
private static MethodInfo toStringMethod = typeof(object).GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance);
/// <summary/>
[DebuggerHidden]
public sealed override bool Equals(object obj)
{
// Forward this call to the interceptor, so that `object.Equals` can be set up.
var interceptor = (IInterceptor)((IProxy)this).Interceptor;
var invocation = new Invocation(interceptor.GetType(), equalsMethod, obj);
interceptor.Intercept(invocation);
return (bool)invocation.ReturnValue;
}
/// <summary/>
[DebuggerHidden]
public sealed override int GetHashCode()
{
// Forward this call to the interceptor, so that `object.GetHashCode` can be set up.
var interceptor = (IInterceptor)((IProxy)this).Interceptor;
var invocation = new Invocation(interceptor.GetType(), getHashCodeMethod);
interceptor.Intercept(invocation);
return (int)invocation.ReturnValue;
}
/// <summary/>
[DebuggerHidden]
public sealed override string ToString()
{
// Forward this call to the interceptor, so that `object.ToString` can be set up.
var interceptor = (IInterceptor)((IProxy)this).Interceptor;
var invocation = new Invocation(interceptor.GetType(), toStringMethod);
interceptor.Intercept(invocation);
return (string)invocation.ReturnValue;
}
private sealed class Invocation : Moq.Invocation
{
private static object[] noArguments = new object[0];
public Invocation(Type proxyType, MethodInfo method, params object[] arguments)
: base(proxyType, method, arguments)
{
}
public Invocation(Type proxyType, MethodInfo method)
: base(proxyType, method, noArguments)
{
}
public override void Return() { }
public override void Return(object value)
{
this.SetReturnValue(value);
}
public override void ReturnBase() { }
}
}
}
| bsd-3-clause | C# |
a2e4891ee658ce8148e6554918a133e857acfb44 | Fix test brittleness. | lnu/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core | src/NHibernate.Test/Linq/LoggingTests.cs | src/NHibernate.Test/Linq/LoggingTests.cs | using System.Linq;
using NHibernate.Cfg;
using NHibernate.DomainModel.Northwind.Entities;
using NUnit.Framework;
namespace NHibernate.Test.Linq
{
[TestFixture]
public class LoggingTests : LinqTestCase
{
[Test]
public void PageBetweenProjections()
{
using (var spy = new LogSpy("NHibernate.Linq"))
{
var subquery = db.Products.Where(p => p.ProductId > 5);
var list = db.Products.Where(p => subquery.Contains(p))
.Skip(5).Take(10)
.ToList();
var logtext = spy.GetWholeLog();
const string expected =
"Expression (partially evaluated): value(NHibernate.Linq.NhQueryable`1[NHibernate.DomainModel.Northwind.Entities.Product]).Where(p => value(NHibernate.Linq.NhQueryable`1[NHibernate.DomainModel.Northwind.Entities.Product]).Where(p => (p.ProductId > 5)).Contains(p)).Skip(5).Take(10)";
Assert.That(logtext, Is.StringContaining(expected));
}
}
[Test]
public void CanLogLinqExpressionWithoutInitializingContainedProxy()
{
var productId = db.Products.Select(p => p.ProductId).First();
using (var logspy = new LogSpy("NHibernate.Linq"))
{
var productProxy = session.Load<Product>(productId);
Assert.That(NHibernateUtil.IsInitialized(productProxy), Is.False);
var result = from product in db.Products
where product == productProxy
select product;
Assert.That(result.Count(), Is.EqualTo(1));
// Verify that the expected logging did happen.
var actualLog = logspy.GetWholeLog();
string expectedLog =
"Expression (partially evaluated): value(NHibernate.Linq.NhQueryable`1[NHibernate.DomainModel.Northwind.Entities.Product])" +
".Where(product => (product == Product#" + productId + ")).Count()";
Assert.That(actualLog, Is.StringContaining(expectedLog));
// And verify that the proxy in the expression wasn't initialized.
Assert.That(NHibernateUtil.IsInitialized(productProxy), Is.False,
"ERROR: We expected the proxy to NOT be initialized.");
}
}
}
}
| using System.Linq;
using NHibernate.Cfg;
using NHibernate.DomainModel.Northwind.Entities;
using NUnit.Framework;
namespace NHibernate.Test.Linq
{
[TestFixture]
public class LoggingTests : LinqTestCase
{
[Test]
public void PageBetweenProjections()
{
using (var spy = new LogSpy("NHibernate.Linq"))
{
var subquery = db.Products.Where(p => p.ProductId > 5);
var list = db.Products.Where(p => subquery.Contains(p))
.Skip(5).Take(10)
.ToList();
var logtext = spy.GetWholeLog();
const string expected =
"Expression (partially evaluated): value(NHibernate.Linq.NhQueryable`1[NHibernate.DomainModel.Northwind.Entities.Product]).Where(p => value(NHibernate.Linq.NhQueryable`1[NHibernate.DomainModel.Northwind.Entities.Product]).Where(p => (p.ProductId > 5)).Contains(p)).Skip(5).Take(10)";
Assert.That(logtext, Is.StringContaining(expected));
}
}
[Test]
public void CanLogLinqExpressionWithoutInitializingContainedProxy()
{
var productId = db.Products.Select(p => p.ProductId).First();
using (var logspy = new LogSpy("NHibernate.Linq"))
{
var productProxy = session.Load<Product>(productId);
Assert.That(NHibernateUtil.IsInitialized(productProxy), Is.False);
var result = from product in db.Products
where product == productProxy
select product;
Assert.That(result.Count(), Is.EqualTo(1));
// Verify that the expected logging did happen.
var actualLog = logspy.GetWholeLog();
const string expectedLog =
"Expression (partially evaluated): value(NHibernate.Linq.NhQueryable`1[NHibernate.DomainModel.Northwind.Entities.Product])" +
".Where(product => (product == Product#1)).Count()";
Assert.That(actualLog, Is.StringContaining(expectedLog));
// And verify that the proxy in the expression wasn't initialized.
Assert.That(NHibernateUtil.IsInitialized(productProxy), Is.False,
"ERROR: We expected the proxy to NOT be initialized.");
}
}
}
}
| lgpl-2.1 | C# |
0e7b62b1a0e35b06b5b658d3b80db14cd392f83f | add repo | mzrimsek/scheduler,mzrimsek/scheduler,mzrimsek/scheduler | Controllers/SchedulerController.cs | Controllers/SchedulerController.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using scheduler.Interfaces;
using scheduler.Mappers;
using scheduler.Models;
using scheduler.Models.SchedulerViewModels;
namespace scheduler.Controllers
{
public class SchedulerController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger _logger;
private readonly IEventRepository _eventRepo;
private readonly IInviteeRepository _inviteeRepo;
public SchedulerController(UserManager<ApplicationUser> userManager, ILoggerFactory loggerFactory, IEventRepository eventRepo, IInviteeRepository inviteeRepo)
{
_userManager = userManager;
_logger = loggerFactory.CreateLogger<SchedulerController>();
_eventRepo = eventRepo;
_inviteeRepo = inviteeRepo;
}
[HttpGet]
public async Task<IActionResult> Index()
{
var user = await GetCurrentUserAsync();
if (user != null) {
return View();
}
return RedirectToAction("Login", "Account");
}
[HttpPost]
public async Task<IActionResult> CreateEvent(EventViewModel model)
{
var currentUser = await GetCurrentUserAsync();
var eventDbModel = EventModelMapper.MapFrom(currentUser, model);
var newEvent = _eventRepo.Create(eventDbModel);
foreach(var email in model.InviteeEmails)
{
var userId = "id-found-searching-for-user-in-db-by-email";
var inviteeDbModel = InviteeModelMapper.MapFrom(newEvent, userId);
_inviteeRepo.Create(inviteeDbModel);
}
return View(model);
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using scheduler.Interfaces;
using scheduler.Mappers;
using scheduler.Models;
using scheduler.Models.SchedulerViewModels;
namespace scheduler.Controllers
{
public class SchedulerController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger _logger;
private readonly IEventRepository _eventRepo;
public SchedulerController(UserManager<ApplicationUser> userManager, ILoggerFactory loggerFactory, IEventRepository eventRepo)
{
_userManager = userManager;
_logger = loggerFactory.CreateLogger<SchedulerController>();
_eventRepo = eventRepo;
}
[HttpGet]
public async Task<IActionResult> Index()
{
var user = await GetCurrentUserAsync();
if (user != null) {
return View();
}
return RedirectToAction("Login", "Account");
}
[HttpPost]
public async Task<IActionResult> CreateEvent(EventViewModel model)
{
var currentUser = await GetCurrentUserAsync();
var eventDbModel = EventModelMapper.MapFrom(currentUser, model);
var newEvent = _eventRepo.Create(eventDbModel);
//need to add invitees
return View(model);
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
}
} | mit | C# |
a8b804aaaa3e8bff74b5f3f7f06cdf4b77862874 | Update VehicleType.cs | ikkentim/SampSharp,ikkentim/SampSharp,ikkentim/SampSharp | src/SampSharp.GameMode/SAMP/Commands/ParameterTypes/VehicleType.cs | src/SampSharp.GameMode/SAMP/Commands/ParameterTypes/VehicleType.cs | // SampSharp
// Copyright 2017 Tim Potze
//
// 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.Globalization;
using System.Linq;
using SampSharp.GameMode.World;
namespace SampSharp.GameMode.SAMP.Commands.ParameterTypes
{
/// <summary>
/// Represents a vehicle command parameter.
/// </summary>
public class VehicleType : ICommandParameterType
{
#region Implementation of ICommandParameterType
/// <summary>
/// Gets the value for the occurance of this parameter type at the start of the commandText. The processed text will be
/// removed from the commandText.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <param name="output">The output.</param>
/// <returns>
/// true if parsed successfully; false otherwise.
/// </returns>
public bool Parse(ref string commandText, out object output)
{
var text = commandText.TrimStart();
output = null;
if (string.IsNullOrEmpty(text))
return false;
var word = text.Split(' ').First();
// find a vehicle with a matching id.
int id;
if (int.TryParse(word, NumberStyles.Integer, CultureInfo.InvariantCulture, out id))
{
var vehicle = BaseVehicle.Find(id);
if (vehicle != null)
{
output = vehicle;
commandText = commandText.Substring(word.Length).TrimStart(' ');
return true;
}
}
return false;
}
#endregion
}
}
| // SampSharp
// Copyright 2017 Tim Potze
//
// 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.Globalization;
using System.Linq;
using SampSharp.GameMode.World;
namespace SampSharp.GameMode.SAMP.Commands.ParameterTypes
{
/// <summary>
/// Represents a player command parameter.
/// </summary>
public class VehicleType : ICommandParameterType
{
#region Implementation of ICommandParameterType
/// <summary>
/// Gets the value for the occurance of this parameter type at the start of the commandText. The processed text will be
/// removed from the commandText.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <param name="output">The output.</param>
/// <returns>
/// true if parsed successfully; false otherwise.
/// </returns>
public bool Parse(ref string commandText, out object output)
{
var text = commandText.TrimStart();
output = null;
if (string.IsNullOrEmpty(text))
return false;
var word = text.Split(' ').First();
// find a vehicle with a matching id.
int id;
if (int.TryParse(word, NumberStyles.Integer, CultureInfo.InvariantCulture, out id))
{
var vehicle = BaseVehicle.Find(id);
if (vehicle != null)
{
output = vehicle;
commandText = commandText.Substring(word.Length).TrimStart(' ');
return true;
}
}
return false;
}
#endregion
}
} | apache-2.0 | C# |
0fd333d92af4f596d96f11db453c6c95b7117850 | Use steamcmd script instead of command line arguments to allow for spaces in install path | Limmek/Factorio-Server-Launcher | FactorioServerLuancher/Download.cs | FactorioServerLuancher/Download.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Permissions;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Diagnostics;
namespace FactorioServerLauncher
{
class Download
{
public static Process DownloadFactorio = new Process();
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Start(string Path, string Username = "", string Password = "")
{
string tempPath = System.IO.Path.GetTempPath();
string AnonumysLogin = "";
if (Username != "" && Password != "")
AnonumysLogin = "login " + Username + " " + Password;
CreateSteamCmdScript(AnonumysLogin);
var StartArguments = "+runscript " + tempPath + "steamcmd.txt";
ProcessStartInfo startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Normal,
Verb = "runas",
FileName = Path + @"\steamcmd.exe",
Arguments = StartArguments,
WorkingDirectory = Path,
CreateNoWindow = false,
RedirectStandardInput = false,
RedirectStandardOutput = false,
UseShellExecute = true
};
DownloadFactorio = Process.Start(startInfo);
DownloadFactorio.WaitForExit();
if (File.Exists(tempPath + "steamcmd.txt"))
{
File.Delete(tempPath + "steamcmd.txt");
}
}
private static void CreateSteamCmdScript(string login)
{
string[] scriptLines = {
login,
"force_install_dir \"" + Settings.factorioInstallPath + "\"",
"app_update "+ Settings.appId.ToString(),
"quit"
};
string tempPath = Path.GetTempPath();
System.IO.File.WriteAllLines(tempPath + "steamcmd.txt", scriptLines);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Permissions;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Diagnostics;
namespace FactorioServerLauncher
{
class Download
{
public static Process DownloadFactorio = new Process();
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Start(string Path, string Username="", string Password="")
{
string AnonumysLogin = "";
if (Username != "" && Password != "")
AnonumysLogin = "+login " + Username + " " + Password;
var StartArguments = AnonumysLogin + " +force_install_dir " + Settings.factorioInstallPath + " +app_update "+ Settings.appId.ToString() +" validate +quit";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.Verb = "runas";
startInfo.FileName = Path + @"\steamcmd.exe";
startInfo.Arguments = StartArguments;
startInfo.WorkingDirectory = Path;
startInfo.CreateNoWindow = false;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = false;
startInfo.UseShellExecute = true;
DownloadFactorio = Process.Start(startInfo);
}
}
}
| mit | C# |
d9ca293da6801bb896b1dcabc99d5be314169b0f | Use dotnet-bot instead of vslsnap GitHub account for GithubMergeTool | CyrusNajmabadi/roslyn,amcasey/roslyn,diryboy/roslyn,heejaechang/roslyn,aelij/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,srivatsn/roslyn,robinsedlaczek/roslyn,lorcanmooney/roslyn,genlu/roslyn,CaptainHayashi/roslyn,mmitche/roslyn,AmadeusW/roslyn,pdelvo/roslyn,mattwar/roslyn,panopticoncentral/roslyn,pdelvo/roslyn,brettfo/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,cston/roslyn,Giftednewt/roslyn,tvand7093/roslyn,wvdd007/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,VSadov/roslyn,mattscheffer/roslyn,Hosch250/roslyn,MattWindsor91/roslyn,drognanar/roslyn,gafter/roslyn,aelij/roslyn,zooba/roslyn,paulvanbrenk/roslyn,davkean/roslyn,drognanar/roslyn,mavasani/roslyn,physhi/roslyn,akrisiun/roslyn,zooba/roslyn,weltkante/roslyn,tmat/roslyn,brettfo/roslyn,physhi/roslyn,dotnet/roslyn,orthoxerox/roslyn,eriawan/roslyn,khyperia/roslyn,jeffanders/roslyn,jkotas/roslyn,OmarTawfik/roslyn,Hosch250/roslyn,pdelvo/roslyn,dpoeschl/roslyn,yeaicc/roslyn,kelltrick/roslyn,kelltrick/roslyn,reaction1989/roslyn,orthoxerox/roslyn,diryboy/roslyn,diryboy/roslyn,akrisiun/roslyn,jeffanders/roslyn,bkoelman/roslyn,reaction1989/roslyn,CaptainHayashi/roslyn,lorcanmooney/roslyn,sharwell/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,reaction1989/roslyn,nguerrera/roslyn,jmarolf/roslyn,stephentoub/roslyn,agocke/roslyn,stephentoub/roslyn,genlu/roslyn,mattscheffer/roslyn,abock/roslyn,bartdesmet/roslyn,yeaicc/roslyn,khyperia/roslyn,khyperia/roslyn,xasx/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,robinsedlaczek/roslyn,jamesqo/roslyn,DustinCampbell/roslyn,TyOverby/roslyn,mgoertz-msft/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,Hosch250/roslyn,dotnet/roslyn,bkoelman/roslyn,swaroop-sridhar/roslyn,abock/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,mmitche/roslyn,stephentoub/roslyn,amcasey/roslyn,paulvanbrenk/roslyn,mattwar/roslyn,srivatsn/roslyn,tvand7093/roslyn,davkean/roslyn,mattscheffer/roslyn,tmeschter/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,tmat/roslyn,amcasey/roslyn,jamesqo/roslyn,genlu/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,AnthonyDGreen/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,TyOverby/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,yeaicc/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,brettfo/roslyn,cston/roslyn,VSadov/roslyn,dotnet/roslyn,jkotas/roslyn,AnthonyDGreen/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,bkoelman/roslyn,VSadov/roslyn,tvand7093/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,jamesqo/roslyn,paulvanbrenk/roslyn,jeffanders/roslyn,abock/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,mgoertz-msft/roslyn,OmarTawfik/roslyn,davkean/roslyn,eriawan/roslyn,AlekseyTs/roslyn,gafter/roslyn,AlekseyTs/roslyn,sharwell/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,mavasani/roslyn,mmitche/roslyn,mavasani/roslyn,drognanar/roslyn,MattWindsor91/roslyn,xasx/roslyn,KevinRansom/roslyn,agocke/roslyn,jmarolf/roslyn,MattWindsor91/roslyn,AnthonyDGreen/roslyn,shyamnamboodiripad/roslyn,Giftednewt/roslyn,ErikSchierboom/roslyn,dpoeschl/roslyn,weltkante/roslyn,AlekseyTs/roslyn,Giftednewt/roslyn,zooba/roslyn,KevinRansom/roslyn,gafter/roslyn,aelij/roslyn,jkotas/roslyn,heejaechang/roslyn,jcouv/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,orthoxerox/roslyn,dpoeschl/roslyn,cston/roslyn,TyOverby/roslyn,lorcanmooney/roslyn,kelltrick/roslyn,shyamnamboodiripad/roslyn,jcouv/roslyn,srivatsn/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,robinsedlaczek/roslyn,tmat/roslyn,KirillOsenkov/roslyn,mattwar/roslyn,ErikSchierboom/roslyn,xasx/roslyn,eriawan/roslyn,tannergooding/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,akrisiun/roslyn,tannergooding/roslyn,agocke/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,jcouv/roslyn,CaptainHayashi/roslyn,jmarolf/roslyn | src/Tools/Github/GithubMergeTool/run.csx | src/Tools/Github/GithubMergeTool/run.csx | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#r "GithubMergeTool.dll"
#load "auth.csx"
using System;
using System.Net;
using System.Threading.Tasks;
private static string DotnetBotGithubAuthToken = null;
private static TraceWriter Log = null;
private static async Task MakeGithubPr(string repoOwner, string repoName, string srcBranch, string destBranch)
{
var gh = new GithubMergeTool.GithubMergeTool("[email protected]", DotnetBotGithubAuthToken);
Log.Info($"Merging from {srcBranch} to {destBranch}");
var result = await gh.CreateMergePr(repoOwner, repoName, srcBranch, destBranch);
if (result != null)
{
if (result.StatusCode == (HttpStatusCode)422)
{
Log.Info("PR not created -- all commits are present in base branch");
}
else
{
Log.Error($"Error creating PR. GH response code: {result.StatusCode}");
}
}
else
{
Log.Info("PR created successfully");
}
}
private static Task MakeRoslynPr(string srcBranch, string destBranch)
=> MakeGithubPr("dotnet", "roslyn", srcBranch, destBranch);
private static async Task RunAsync()
{
DotnetBotGithubAuthToken = await GetSecret("dotnet-bot-github-auth-token");
// Roslyn branches
await MakeRoslynPr("dev15.0.x", "dev15.1.x");
await MakeRoslynPr("dev15.1.x", "master");
await MakeRoslynPr("master", "dev16");
}
public static void Run(TimerInfo myTimer, TraceWriter log)
{
Log = log;
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
RunAsync().GetAwaiter().GetResult();
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#r "GithubMergeTool.dll"
#load "auth.csx"
using System;
using System.Net;
using System.Threading.Tasks;
private static string VslsnapGithubAuthToken = null;
private static TraceWriter Log = null;
private static async Task MakeGithubPr(string repoOwner, string repoName, string srcBranch, string destBranch)
{
var gh = new GithubMergeTool.GithubMergeTool("[email protected]", VslsnapGithubAuthToken);
Log.Info($"Merging from {srcBranch} to {destBranch}");
var result = await gh.CreateMergePr(repoOwner, repoName, srcBranch, destBranch);
if (result != null)
{
if (result.StatusCode == (HttpStatusCode)422)
{
Log.Info("PR not created -- all commits are present in base branch");
}
else
{
Log.Error($"Error creating PR. GH response code: {result.StatusCode}");
}
}
else
{
Log.Info("PR created successfully");
}
}
private static Task MakeRoslynPr(string srcBranch, string destBranch)
=> MakeGithubPr("dotnet", "roslyn", srcBranch, destBranch);
private static async Task RunAsync()
{
VslsnapGithubAuthToken = await GetSecret("vslsnap-github-auth-token");
// Roslyn branches
await MakeRoslynPr("dev15.0.x", "dev15.1.x");
await MakeRoslynPr("dev15.1.x", "master");
await MakeRoslynPr("master", "dev16");
}
public static void Run(TimerInfo myTimer, TraceWriter log)
{
Log = log;
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
RunAsync().GetAwaiter().GetResult();
}
| mit | C# |
236124496d208c9bcf554ee36ead97170f5705ce | add missing accent colour in control tab item | NeoAdonis/osu,peppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,ppy/osu | osu.Game/Overlays/BreadcrumbControlOverlayHeader.cs | osu.Game/Overlays/BreadcrumbControlOverlayHeader.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.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string>
{
protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl();
public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string>
{
public OverlayHeaderBreadcrumbControl()
{
RelativeSizeAxes = Axes.X;
Height = 47;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
AccentColour = colourProvider.Light2;
}
protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value)
{
AccentColour = AccentColour,
};
private class ControlTabItem : BreadcrumbTabItem
{
protected override float ChevronSize => 8;
public ControlTabItem(string value)
: base(value)
{
RelativeSizeAxes = Axes.Y;
Text.Font = Text.Font.With(size: 14);
Text.Anchor = Anchor.CentreLeft;
Text.Origin = Anchor.CentreLeft;
Chevron.Y = 1;
Bar.Height = 0;
}
// base OsuTabItem makes font bold on activation, we don't want that here
protected override void OnActivated() => FadeHovered();
protected override void OnDeactivated() => FadeUnhovered();
}
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public abstract class BreadcrumbControlOverlayHeader : TabControlOverlayHeader<string>
{
protected override OsuTabControl<string> CreateTabControl() => new OverlayHeaderBreadcrumbControl();
public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string>
{
public OverlayHeaderBreadcrumbControl()
{
RelativeSizeAxes = Axes.X;
Height = 47;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
AccentColour = colourProvider.Light2;
}
protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value);
private class ControlTabItem : BreadcrumbTabItem
{
protected override float ChevronSize => 8;
public ControlTabItem(string value)
: base(value)
{
RelativeSizeAxes = Axes.Y;
Text.Font = Text.Font.With(size: 14);
Text.Anchor = Anchor.CentreLeft;
Text.Origin = Anchor.CentreLeft;
Chevron.Y = 1;
Bar.Height = 0;
}
// base OsuTabItem makes font bold on activation, we don't want that here
protected override void OnActivated() => FadeHovered();
protected override void OnDeactivated() => FadeUnhovered();
}
}
}
}
| mit | C# |
f415d227eaae38e1bdd6a694916ec8784d98623b | Add sub execution tasks | defrancea/Fadm | Core/Fadm/Core/ExecutionResult.cs | Core/Fadm/Core/ExecutionResult.cs | /*
* Copyright (c) 2015, Fadm. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
namespace Fadm.Core
{
/// <summary>
/// Represents an execution result providing more context to the calling code.
/// </summary>
public class ExecutionResult
{
/// <summary>
/// The status specifying whether it worked.
/// </summary>
public ExecutionResultStatus Status { get; private set; }
/// <summary>
/// The message containing a description of what happened.
/// </summary>
public string Message { get; private set; }
/// <summary>
/// The sub execution results.
/// </summary>
public ExecutionResult[] SubExecutionResults { get; private set; }
/// <summary>
/// Initializes a new instance of <see cref="ExecutionResult"/>.
/// </summary>
/// <param name="status">The execution result status.</param>
/// <param name="message">The execution result message</param>
public ExecutionResult(ExecutionResultStatus status, string message)
{
this.Status = status;
this.Message = message;
this.SubExecutionResults = new ExecutionResult[0];
}
/// <summary>
/// Initializes a new instance of <see cref="ExecutionResult"/> containing sub task.
/// </summary>
/// <param name="status">The execution result status.</param>
/// <param name="message">The execution result message.</param>
/// <param name="subExecutionResults">The sub execution results.</param>
public ExecutionResult(ExecutionResultStatus status, string message, ExecutionResult[] subExecutionResults)
{
this.Status = status;
this.Message = message;
this.SubExecutionResults = subExecutionResults;
}
}
} | /*
* Copyright (c) 2015, Fadm. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
namespace Fadm.Core
{
/// <summary>
/// Represents an execution result providing more context to the calling code.
/// </summary>
public class ExecutionResult
{
/// <summary>
/// The status specifying whether it worked.
/// </summary>
public ExecutionResultStatus Status { get; private set; }
/// <summary>
/// The message containing a description of what happened.
/// </summary>
public string Message { get; private set; }
/// <summary>
/// Initializes a new instance of <see cref="ExecutionResult"/>.
/// </summary>
/// <param name="status">The execution result status.</param>
/// <param name="message">The execution result message</param>
public ExecutionResult(ExecutionResultStatus status, string message)
{
this.Status = status;
this.Message = message;
}
}
}
| lgpl-2.1 | C# |
eb3b266372b37f9a60fda8f8216cba6bff7e4447 | Fix test event ordering to correctly test fail case | ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework | osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs | osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new TestAudioCollectionManager();
var threadExecutionFinished = new ManualResetEventSlim();
var updateLoopStarted = new ManualResetEventSlim();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++)
manager.AddItem(new TestingAdjustableAudioComponent());
// in a separate thread start processing the queue
var thread = new Thread(() =>
{
while (!manager.IsDisposed)
{
updateLoopStarted.Set();
manager.Update();
}
threadExecutionFinished.Set();
});
thread.Start();
Assert.IsTrue(updateLoopStarted.Wait(10000));
Assert.DoesNotThrow(() => manager.Dispose());
Assert.IsTrue(threadExecutionFinished.Wait(10000));
}
private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
{
public new bool IsDisposed => base.IsDisposed;
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioCollectionManagerTest
{
[Test]
public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException()
{
var manager = new TestAudioCollectionManager();
var threadExecutionFinished = new ManualResetEventSlim();
var updateLoopStarted = new ManualResetEventSlim();
// add a huge amount of items to the queue
for (int i = 0; i < 10000; i++)
manager.AddItem(new TestingAdjustableAudioComponent());
// in a separate thread start processing the queue
var thread = new Thread(() =>
{
while (!manager.IsDisposed)
{
manager.Update();
updateLoopStarted.Set();
}
threadExecutionFinished.Set();
});
thread.Start();
Assert.IsTrue(updateLoopStarted.Wait(10000));
Assert.DoesNotThrow(() => manager.Dispose());
Assert.IsTrue(threadExecutionFinished.Wait(10000));
}
private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent>
{
public new bool IsDisposed => base.IsDisposed;
}
private class TestingAdjustableAudioComponent : AdjustableAudioComponent
{
}
}
}
| mit | C# |
90fecbc9c7435ff5c2f3077b8fdebb96ff3d6c52 | Add test showing all mod icons for reference | ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu | osu.Game.Tests/Visual/UserInterface/TestSceneModIcon.cs | osu.Game.Tests/Visual/UserInterface/TestSceneModIcon.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.UI;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneModIcon : OsuTestScene
{
[Test]
public void TestShowAllMods()
{
AddStep("create mod icons", () =>
{
Child = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Full,
ChildrenEnumerable = Ruleset.Value.CreateInstance().CreateAllMods().Select(m => new ModIcon(m)),
};
});
}
[Test]
public void TestChangeModType()
{
ModIcon icon = null!;
AddStep("create mod icon", () => Child = icon = new ModIcon(new OsuModDoubleTime()));
AddStep("change mod", () => icon.Mod = new OsuModEasy());
}
[Test]
public void TestInterfaceModType()
{
ModIcon icon = null!;
var ruleset = new OsuRuleset();
AddStep("create mod icon", () => Child = icon = new ModIcon(ruleset.AllMods.First(m => m.Acronym == "DT")));
AddStep("change mod", () => icon.Mod = ruleset.AllMods.First(m => m.Acronym == "EZ"));
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Linq;
using NUnit.Framework;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.UI;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneModIcon : OsuTestScene
{
[Test]
public void TestChangeModType()
{
ModIcon icon = null;
AddStep("create mod icon", () => Child = icon = new ModIcon(new OsuModDoubleTime()));
AddStep("change mod", () => icon.Mod = new OsuModEasy());
}
[Test]
public void TestInterfaceModType()
{
ModIcon icon = null;
var ruleset = new OsuRuleset();
AddStep("create mod icon", () => Child = icon = new ModIcon(ruleset.AllMods.First(m => m.Acronym == "DT")));
AddStep("change mod", () => icon.Mod = ruleset.AllMods.First(m => m.Acronym == "EZ"));
}
}
}
| mit | C# |
f77ad8cf3907327834db7d12c129511f70c5b819 | Remove unused using | UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,smoogipooo/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu | osu.Game/Screens/Ranking/ScorePanelTrackingContainer.cs | osu.Game/Screens/Ranking/ScorePanelTrackingContainer.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 osu.Framework.Graphics.Containers;
namespace osu.Game.Screens.Ranking
{
/// <summary>
/// A <see cref="CompositeDrawable"/> which tracks the size of a <see cref="ScorePanel"/>, to which the <see cref="ScorePanel"/> can be added or removed.
/// </summary>
public class ScorePanelTrackingContainer : CompositeDrawable
{
/// <summary>
/// The <see cref="ScorePanel"/> that created this <see cref="ScorePanelTrackingContainer"/>.
/// </summary>
public readonly ScorePanel Panel;
internal ScorePanelTrackingContainer(ScorePanel panel)
{
Panel = panel;
Attach();
}
/// <summary>
/// Detaches the <see cref="ScorePanel"/> from this <see cref="ScorePanelTrackingContainer"/>, removing it as a child.
/// This <see cref="ScorePanelTrackingContainer"/> will continue tracking any size changes.
/// </summary>
/// <exception cref="InvalidOperationException">If the <see cref="ScorePanel"/> is already detached.</exception>
public void Detach()
{
if (InternalChildren.Count == 0)
throw new InvalidOperationException("Score panel container is not attached.");
RemoveInternal(Panel);
}
/// <summary>
/// Attaches the <see cref="ScorePanel"/> to this <see cref="ScorePanelTrackingContainer"/>, adding it as a child.
/// </summary>
/// <exception cref="InvalidOperationException">If the <see cref="ScorePanel"/> is already attached.</exception>
public void Attach()
{
if (InternalChildren.Count > 0)
throw new InvalidOperationException("Score panel container is already attached.");
AddInternal(Panel);
}
}
}
| // 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 osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Screens.Ranking
{
/// <summary>
/// A <see cref="CompositeDrawable"/> which tracks the size of a <see cref="ScorePanel"/>, to which the <see cref="ScorePanel"/> can be added or removed.
/// </summary>
public class ScorePanelTrackingContainer : CompositeDrawable
{
/// <summary>
/// The <see cref="ScorePanel"/> that created this <see cref="ScorePanelTrackingContainer"/>.
/// </summary>
public readonly ScorePanel Panel;
internal ScorePanelTrackingContainer(ScorePanel panel)
{
Panel = panel;
Attach();
}
/// <summary>
/// Detaches the <see cref="ScorePanel"/> from this <see cref="ScorePanelTrackingContainer"/>, removing it as a child.
/// This <see cref="ScorePanelTrackingContainer"/> will continue tracking any size changes.
/// </summary>
/// <exception cref="InvalidOperationException">If the <see cref="ScorePanel"/> is already detached.</exception>
public void Detach()
{
if (InternalChildren.Count == 0)
throw new InvalidOperationException("Score panel container is not attached.");
RemoveInternal(Panel);
}
/// <summary>
/// Attaches the <see cref="ScorePanel"/> to this <see cref="ScorePanelTrackingContainer"/>, adding it as a child.
/// </summary>
/// <exception cref="InvalidOperationException">If the <see cref="ScorePanel"/> is already attached.</exception>
public void Attach()
{
if (InternalChildren.Count > 0)
throw new InvalidOperationException("Score panel container is already attached.");
AddInternal(Panel);
}
}
}
| mit | C# |
e17f8750aeff93dfcf1fe39fc926512a49435cca | Bump nuget version to 1.3.0. | FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| using System.Reflection;
[assembly: AssemblyVersion("1.2.1.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| mit | C# |
1a610d34868fa8db6b2e78f046bf71289ce9f3f1 | Enable dynamically adding and removing navigation list items at runtime. | grantcolley/wpfcontrols | DevelopmentInProgress.WPFControls/NavigationPanel/NavigationList.cs | DevelopmentInProgress.WPFControls/NavigationPanel/NavigationList.cs | //-----------------------------------------------------------------------
// <copyright file="NavigationList.cs" company="Development In Progress Ltd">
// Copyright © 2012. All rights reserved.
// </copyright>
// <author>Grant Colley</author>
//-----------------------------------------------------------------------
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
namespace DevelopmentInProgress.WPFControls.NavigationPanel
{
/// <summary>
/// The NavigationList class.
/// </summary>
public class NavigationList : Control
{
private readonly static DependencyProperty NavigationListNameProperty;
private readonly static DependencyProperty NavigationListItemsProperty;
/// <summary>
/// Static constructor for the <see cref="NavigationList"/> class for registering dependency properties and events.
/// </summary>
static NavigationList()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NavigationList), new FrameworkPropertyMetadata(typeof(NavigationList)));
NavigationListNameProperty = DependencyProperty.Register("NavigationListName", typeof(string), typeof(NavigationList));
NavigationListItemsProperty = DependencyProperty.Register("NavigationListItems", typeof(ObservableCollection<NavigationListItem>),
typeof(NavigationList), new FrameworkPropertyMetadata(new ObservableCollection<NavigationListItem>()));
}
/// <summary>
/// Initializes a new instance of the NavigationList class.
/// </summary>
public NavigationList()
{
NavigationListItems = new ObservableCollection<NavigationListItem>();
}
/// <summary>
/// Gets or sets the navigation list name.
/// </summary>
public string NavigationListName
{
get { return GetValue(NavigationListNameProperty).ToString(); }
set { SetValue(NavigationListNameProperty, value); }
}
/// <summary>
/// Gets or sets the list of <see cref="NavigationListItem"/>'s.
/// </summary>
public ObservableCollection<NavigationListItem> NavigationListItems
{
get { return (ObservableCollection<NavigationListItem>)GetValue(NavigationListItemsProperty); }
set { SetValue(NavigationListItemsProperty, value); }
}
}
} | //-----------------------------------------------------------------------
// <copyright file="NavigationList.cs" company="Development In Progress Ltd">
// Copyright © 2012. All rights reserved.
// </copyright>
// <author>Grant Colley</author>
//-----------------------------------------------------------------------
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace DevelopmentInProgress.WPFControls.NavigationPanel
{
/// <summary>
/// The NavigationList class.
/// </summary>
public class NavigationList : Control
{
private readonly static DependencyProperty NavigationListNameProperty;
private readonly static DependencyProperty NavigationListItemsProperty;
/// <summary>
/// Static constructor for the <see cref="NavigationList"/> class for registering dependency properties and events.
/// </summary>
static NavigationList()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NavigationList), new FrameworkPropertyMetadata(typeof(NavigationList)));
NavigationListNameProperty = DependencyProperty.Register("NavigationListName", typeof(string), typeof(NavigationList));
NavigationListItemsProperty = DependencyProperty.Register("NavigationListItems", typeof(List<NavigationListItem>),
typeof(NavigationList), new FrameworkPropertyMetadata(new List<NavigationListItem>()));
}
/// <summary>
/// Initializes a new instance of the NavigationList class.
/// </summary>
public NavigationList()
{
NavigationListItems = new List<NavigationListItem>();
}
/// <summary>
/// Gets or sets the navigation list name.
/// </summary>
public string NavigationListName
{
get { return GetValue(NavigationListNameProperty).ToString(); }
set { SetValue(NavigationListNameProperty, value); }
}
/// <summary>
/// Gets or sets the list of <see cref="NavigationListItem"/>'s.
/// </summary>
public List<NavigationListItem> NavigationListItems
{
get { return (List<NavigationListItem>)GetValue(NavigationListItemsProperty); }
set { SetValue(NavigationListItemsProperty, value); }
}
}
} | apache-2.0 | C# |
46354f2880415b40c04eef44b537a2b3f7ecc450 | Update Zip.cs | tsubaki/UnityZip,tsubaki/UnityZip,tsubaki/UnityZip | Assets/Plugins/Zip.cs | Assets/Plugins/Zip.cs | using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
using Ionic.Zip;
using System.Text;
using System.IO;
public class ZipUtil
{
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern void unzip (string zipFilePath, string location);
[DllImport("__Internal")]
private static extern void zip (string zipFilePath);
[DllImport("__Internal")]
private static extern void addZipFile (string addFile);
#endif
public static void Unzip (string zipFilePath, string location)
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX
Directory.CreateDirectory (location);
using (ZipFile zip = ZipFile.Read (zipFilePath)) {
zip.ExtractAll (location, ExtractExistingFileAction.OverwriteSilently);
}
#elif UNITY_ANDROID
using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
zipper.CallStatic ("unzip", zipFilePath, location);
}
#elif UNITY_IPHONE
unzip (zipFilePath, location);
#endif
}
public static void Zip (string zipFileName, params string[] files)
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX
string path = Path.GetDirectoryName(zipFileName);
Directory.CreateDirectory (path);
using (ZipFile zip = new ZipFile()) {
foreach (string file in files) {
zip.AddFile(file, "");
}
zip.Save (zipFileName);
}
#elif UNITY_ANDROID
using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
{
zipper.CallStatic ("zip", zipFileName, files);
}
}
#elif UNITY_IPHONE
foreach (string file in files) {
addZipFile (file);
}
zip (zipFileName);
#endif
}
}
| using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
using Ionic.Zip;
using System.Text;
using System.IO;
public class ZipUtil
{
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern void unzip (string zipFilePath, string location);
[DllImport("__Internal")]
private static extern void zip (string zipFilePath);
[DllImport("__Internal")]
private static extern void addZipFile (string addFile);
#endif
public static void Unzip (string zipFilePath, string location)
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
Directory.CreateDirectory (location);
using (ZipFile zip = ZipFile.Read (zipFilePath)) {
zip.ExtractAll (location, ExtractExistingFileAction.OverwriteSilently);
}
#elif UNITY_ANDROID
using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
zipper.CallStatic ("unzip", zipFilePath, location);
}
#elif UNITY_IPHONE
unzip (zipFilePath, location);
#endif
}
public static void Zip (string zipFileName, params string[] files)
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
string path = Path.GetDirectoryName(zipFileName);
Directory.CreateDirectory (path);
using (ZipFile zip = new ZipFile()) {
foreach (string file in files) {
zip.AddFile(file, "");
}
zip.Save (zipFileName);
}
#elif UNITY_ANDROID
using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
{
zipper.CallStatic ("zip", zipFileName, files);
}
}
#elif UNITY_IPHONE
foreach (string file in files) {
addZipFile (file);
}
zip (zipFileName);
#endif
}
}
| mit | C# |
c7a43cc3c45d81c6852e6a84b3dfadd76fba1598 | Fix build.cake | Redth/Cake.Android.Adb | build.cake | build.cake | var sln = "./Cake.Android.Adb.sln";
var nuspec = "./Cake.Android.Adb.nuspec";
var target = Argument ("target", "libs");
var NUGET_VERSION = Argument("nugetversion", "0.9999");
var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip";
var SDK_VERSION = "25.2.3";
Task ("externals")
.WithCriteria (!FileExists ("./android-sdk/android-sdk.zip"))
.Does (() =>
{
var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx");
if (IsRunningOnWindows ())
url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows");
EnsureDirectoryExists ("./android-sdk/");
DownloadFile (url, "./android-sdk/android-sdk.zip");
Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/");
// Install platform-tools so we get adb
StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" });
});
Task ("libs").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = "Release");
});
Task ("nuget").IsDependentOn ("libs").Does (() =>
{
CreateDirectory ("./nupkg/");
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./nupkg/",
Version = NUGET_VERSION,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
DeleteFiles ("./**/*.apk");
});
RunTarget (target); | var sln = "./Cake.Android.SdkManager.sln";
var nuspec = "./Cake.Android.SdkManager.nuspec";
var target = Argument ("target", "libs");
var NUGET_VERSION = Argument("nugetversion", "0.9999");
var SDK_URL_BASE = "https://dl.google.com/android/repository/tools_r{0}-{1}.zip";
var SDK_VERSION = "25.2.3";
Task ("externals")
.WithCriteria (!FileExists ("./android-sdk/android-sdk.zip"))
.Does (() =>
{
var url = string.Format (SDK_URL_BASE, SDK_VERSION, "macosx");
if (IsRunningOnWindows ())
url = string.Format (SDK_URL_BASE, SDK_VERSION, "windows");
EnsureDirectoryExists ("./android-sdk/");
DownloadFile (url, "./android-sdk/android-sdk.zip");
Unzip ("./android-sdk/android-sdk.zip", "./android-sdk/");
// Install platform-tools so we get adb
StartProcess ("./android-sdk/tools/bin/sdkmanager", new ProcessSettings { Arguments = "platform-tools" });
});
Task ("libs").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = "Release");
});
Task ("nuget").IsDependentOn ("libs").Does (() =>
{
CreateDirectory ("./nupkg/");
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./nupkg/",
Version = NUGET_VERSION,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
DeleteFiles ("./**/*.apk");
});
RunTarget (target); | mit | C# |
654e6e3349a6bc6b0accec98147875c13ddd7c81 | Bump version to 0.15 | whampson/cascara,whampson/bft-spec | Src/WHampson.Cascara/Properties/AssemblyInfo.cs | Src/WHampson.Cascara/Properties/AssemblyInfo.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.Cascara")]
[assembly: AssemblyProduct("WHampson.Cascara")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.15.0.0")]
[assembly: AssemblyVersion("0.15.0.0")]
[assembly: AssemblyInformationalVersion("0.15")]
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.Cascara")]
[assembly: AssemblyProduct("WHampson.Cascara")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.14.0.0")]
[assembly: AssemblyVersion("0.14.0.0")]
[assembly: AssemblyInformationalVersion("0.14")]
| mit | C# |
9db9caec7f1a7cb2007ca66aea3e79e8ffdd1508 | Add Metafield.Type, deprecate Metafield.ValueType | nozzlegear/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Entities/MetaField.cs | ShopifySharp/Entities/MetaField.cs | using Newtonsoft.Json;
using System;
namespace ShopifySharp
{
public class MetaField : ShopifyObject
{
/// <summary>
/// The date and time when the metafield was created.
/// </summary>
[JsonProperty("created_at")]
public DateTimeOffset? CreatedAt { get; set; }
/// <summary>
/// The date and time when the metafield was last updated.
/// </summary>
[JsonProperty("updated_at")]
public DateTimeOffset? UpdatedAt { get; set; }
/// <summary>
/// Identifier for the metafield (maximum of 30 characters).
/// </summary>
[JsonProperty("key")]
public string Key { get; set; }
/// <summary>
/// Information to be stored as metadata. Must be either a string or an int.
/// </summary>
[JsonProperty("value")]
public object Value { get; set; }
/// <summary>
/// The metafield's information type. See https://shopify.dev/apps/metafields/definitions/types for a full list of types.
/// </summary>
public string Type { get; set; }
/// <summary>
/// States whether the information in the value is stored as a 'string' or 'integer.'
/// </summary>
[JsonProperty("value_type")]
[Obsolete("ValueType is deprecated and replaced by Type.")]
public string ValueType { get; set; }
/// <summary>
/// Container for a set of metadata. Namespaces help distinguish between metadata you created and metadata created by another individual with a similar namespace (maximum of 20 characters).
/// </summary>
[JsonProperty("namespace")]
public string Namespace { get; set; }
/// <summary>
/// Additional information about the metafield.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// The Id of the Shopify Resource that the metafield is associated with. This value could be the id of things like product, order, variant, collection.
/// </summary>
[JsonProperty("owner_id")]
public long? OwnerId { get; set; }
/// <summary>
/// The name of the Shopify Resource that the metafield is associated with. This could be things like product, order, variant, collection.
/// </summary>
[JsonProperty("owner_resource")]
public string OwnerResource { get; set; }
}
}
| using Newtonsoft.Json;
using System;
namespace ShopifySharp
{
public class MetaField : ShopifyObject
{
/// <summary>
/// The date and time when the metafield was created.
/// </summary>
[JsonProperty("created_at")]
public DateTimeOffset? CreatedAt { get; set; }
/// <summary>
/// The date and time when the metafield was last updated.
/// </summary>
[JsonProperty("updated_at")]
public DateTimeOffset? UpdatedAt { get; set; }
/// <summary>
/// Identifier for the metafield (maximum of 30 characters).
/// </summary>
[JsonProperty("key")]
public string Key { get; set; }
/// <summary>
/// Information to be stored as metadata. Must be either a string or an int.
/// </summary>
[JsonProperty("value")]
public object Value { get; set; }
/// <summary>
/// States whether the information in the value is stored as a 'string' or 'integer.'
/// </summary>
[JsonProperty("value_type")]
public string ValueType { get; set; }
/// <summary>
/// Container for a set of metadata. Namespaces help distinguish between metadata you created and metadata created by another individual with a similar namespace (maximum of 20 characters).
/// </summary>
[JsonProperty("namespace")]
public string Namespace { get; set; }
/// <summary>
/// Additional information about the metafield.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// The Id of the Shopify Resource that the metafield is associated with. This value could be the id of things like product, order, variant, collection.
/// </summary>
[JsonProperty("owner_id")]
public long? OwnerId { get; set; }
/// <summary>
/// The name of the Shopify Resource that the metafield is associated with. This could be things like product, order, variant, collection.
/// </summary>
[JsonProperty("owner_resource")]
public string OwnerResource { get; set; }
}
}
| mit | C# |
e8b5ecd3ee63dd4932a9ac049e967becf3ea12cc | Add constructor to CatalogAttributeDefinitionDto | ZEISS-PiWeb/PiWeb-Api | src/Api.Rest.Dtos/Data/CatalogAttributeDefinitionDto.cs | src/Api.Rest.Dtos/Data/CatalogAttributeDefinitionDto.cs | #region copyright
/* * * * * * * * * * * * * * * * * * * * * * * * * */
/* Carl Zeiss IMT (IZfM Dresden) */
/* Softwaresystem PiWeb */
/* (c) Carl Zeiss 2015 */
/* * * * * * * * * * * * * * * * * * * * * * * * * */
#endregion
namespace Zeiss.PiWeb.Api.Rest.Dtos.Data
{
#region usings
using System;
using Newtonsoft.Json;
using Zeiss.PiWeb.Api.Rest.Dtos.Converter;
#endregion
/// <summary>
/// Defines an entity's attribute which is based on a <see cref="Catalog"/>.
/// </summary>
[JsonConverter( typeof( AttributeDefinitionConverter ) )]
public class CatalogAttributeDefinitionDto : AbstractAttributeDefinitionDto
{
#region constructors
/// <summary>
/// Initializes a new instance of the <see cref="CatalogAttributeDefinitionDto"/> class.
/// </summary>
public CatalogAttributeDefinitionDto()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="CatalogAttributeDefinitionDto"/> class.
/// </summary>
/// <param name="key">The unique key for this attribute</param>
/// <param name="description">The attribute description</param>
/// <param name="catalogUuid">The uuid of the catalog this attribute definition points to.</param>
/// <param name="queryEfficient"><code>true</code> if this attribute is efficient for filtering operations</param>
public CatalogAttributeDefinitionDto( ushort key, string description, Guid catalogUuid, bool queryEfficient = false )
: base( key, description, queryEfficient )
{
Catalog = catalogUuid;
}
#endregion
#region properties
/// <summary>
/// Gets or sets the uuid of the catalog this attribute definition points to.
/// </summary>
public Guid Catalog { get; set; }
#endregion
}
} | #region copyright
/* * * * * * * * * * * * * * * * * * * * * * * * * */
/* Carl Zeiss IMT (IZfM Dresden) */
/* Softwaresystem PiWeb */
/* (c) Carl Zeiss 2015 */
/* * * * * * * * * * * * * * * * * * * * * * * * * */
#endregion
namespace Zeiss.PiWeb.Api.Rest.Dtos.Data
{
#region usings
using System;
using Newtonsoft.Json;
using Zeiss.PiWeb.Api.Rest.Dtos.Converter;
#endregion
/// <summary>
/// Defines an entity's attribute which is based on a <see cref="Catalog"/>.
/// </summary>
[JsonConverter( typeof( AttributeDefinitionConverter ) )]
public class CatalogAttributeDefinitionDto : AbstractAttributeDefinitionDto
{
#region properties
/// <summary>
/// Gets or sets the uuid of the catalog this attribute definition points to.
/// </summary>
public Guid Catalog { get; set; }
#endregion
}
} | bsd-3-clause | C# |
7df865ec87704855d268d1e305fdb36fa665e6bb | Fix condition | mdsol/mauth-client-dotnet | src/Medidata.MAuth.Core/HttpRequestMessageExtensions.cs | src/Medidata.MAuth.Core/HttpRequestMessageExtensions.cs | using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Medidata.MAuth.Core
{
internal static class HttpRequestMessageExtensions
{
public async static Task<byte[]> GetRequestContentAsBytesAsync(this HttpRequestMessage request)
{
return request.Content is null
? Array.Empty<byte>()
: await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
#if NET5_0
public static byte[] GetRequestContentAsBytes(this HttpRequestMessage request)
{
using (var memoryStream = new MemoryStream())
{
if (request.Content != null)
{
request.Content.ReadAsStream().CopyTo(memoryStream);
}
return memoryStream.ToArray();
}
}
#endif
}
}
| using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Medidata.MAuth.Core
{
internal static class HttpRequestMessageExtensions
{
public async static Task<byte[]> GetRequestContentAsBytesAsync(this HttpRequestMessage request)
{
return request.Content is null
? Array.Empty<byte>()
: await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
#if NET5_0
public static byte[] GetRequestContentAsBytes(this HttpRequestMessage request)
{
using (var memoryStream = new MemoryStream())
{
if (request.Content is null)
{
request.Content.ReadAsStream().CopyTo(memoryStream);
}
return memoryStream.ToArray();
}
}
#endif
}
}
| mit | C# |
d51b29b77abf7725b36909a8a38bed215ce5b22d | bump version | Fody/Caseless | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Caseless")]
[assembly: AssemblyProduct("Caseless")]
[assembly: AssemblyVersion("1.7.1")]
[assembly: AssemblyFileVersion("1.7.1")] | using System.Reflection;
[assembly: AssemblyTitle("Caseless")]
[assembly: AssemblyProduct("Caseless")]
[assembly: AssemblyVersion("1.7.0")]
[assembly: AssemblyFileVersion("1.7.0")] | mit | C# |
b24a0a434221adc3e5a67a095a698a4955e720d7 | Verify that an ApplicationConfigurationException is thrown if no configuration file exists | appharbor/appharbor-cli | src/AppHarbor.Tests/ApplicationConfigurationTest.cs | src/AppHarbor.Tests/ApplicationConfigurationTest.cs | using System.IO;
using System.Text;
using Moq;
using Xunit;
namespace AppHarbor.Tests
{
public class ApplicationConfigurationTest
{
public static string ConfigurationFile = Path.GetFullPath(".appharbor");
[Fact]
public void ShouldReturnApplicationIdIfConfigurationFileExists()
{
var fileSystem = new Mock<IFileSystem>();
var applicationName = "bar";
var configurationFile = ConfigurationFile;
var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName));
fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream);
var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object);
Assert.Equal(applicationName, applicationConfiguration.GetApplicationId());
}
[Fact]
public void ShouldThrowIfApplicationFileDoesNotExist()
{
var fileSystem = new InMemoryFileSystem();
var applicationConfiguration = new ApplicationConfiguration(fileSystem);
Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId());
}
}
}
| using System.IO;
using System.Text;
using Moq;
using Xunit;
namespace AppHarbor.Tests
{
public class ApplicationConfigurationTest
{
[Fact]
public void ShouldReturnApplicationIdIfConfigurationFileExists()
{
var fileSystem = new Mock<IFileSystem>();
var applicationName = "bar";
var configurationFile = Path.GetFullPath(".appharbor");
var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName));
fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream);
var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object);
Assert.Equal(applicationName, applicationConfiguration.GetApplicationId());
}
}
}
| mit | C# |
231a3cac5a8b8670bceacb7a1afb1a13327e74e1 | move HancContext to new app layer | thewizster/hanc,thewizster/hanc | AspNetAPI/Data/DbInitializer.cs | AspNetAPI/Data/DbInitializer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Hanc.Common.Data;
namespace Hanc.AspNetAPI.Models
{
public class DbInitializer
{
/// <summary>
/// Ensures the database is created and seeded
/// </summary>
/// <param name="context"></param>
public static void Initialize(HancContext context)
{
context.Database.EnsureCreated();
var titles = context.Set<Title>();
if (titles.Any())
{
return; // DB has already been seeded
}
var seedTitles = new Title[] {
new Title { Name="Contact", ForEntityName="Person" },
new Title { Name="Employee", ForEntityName="Person" },
new Title { Name="Manager", ForEntityName="Person"},
new Title { Name="Salesperson", ForEntityName="Person"},
new Title { Name="Lead", ForEntityName="Person"},
new Title { Name="User", ForEntityName="Person"},
new Title { Name="Customer", ForEntityName="Organization"},
new Title { Name="Client", ForEntityName="Organization"},
new Title { Name="Lead", ForEntityName="Organization"},
new Title { Name="Business", ForEntityName="Organization"}
};
titles.AddRange(seedTitles);
context.SaveChanges();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Hanc.AspNetAPI.Data;
namespace Hanc.AspNetAPI.Models
{
public class DbInitializer
{
/// <summary>
/// Ensures the database is created and seeded
/// </summary>
/// <param name="context"></param>
public static void Initialize(HancContext context)
{
context.Database.EnsureCreated();
if (context.Titles.Any())
{
return; // DB has already been seeded
}
var titles = new Title[] {
new Title { Name="Contact", ForEntityName="Person" },
new Title { Name="Employee", ForEntityName="Person" },
new Title { Name="Manager", ForEntityName="Person"},
new Title { Name="Salesperson", ForEntityName="Person"},
new Title { Name="Lead", ForEntityName="Person"},
new Title { Name="User", ForEntityName="Person"},
new Title { Name="Customer", ForEntityName="Organization"},
new Title { Name="Client", ForEntityName="Organization"},
new Title { Name="Lead", ForEntityName="Organization"},
new Title { Name="Business", ForEntityName="Organization"}
};
context.Titles.AddRange(titles);
context.SaveChanges();
}
}
}
| mit | C# |
9865f3387f647abb61e89e5893169fea2ce189e7 | Update namespace of AuthorizeAgent | zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server.Web/Framework/IAuthorizeAgent.cs | src/Glimpse.Server.Web/Framework/IAuthorizeAgent.cs | using Microsoft.AspNet.Http;
namespace Glimpse.Server.Web
{
public interface IAuthorizeAgent
{
bool AllowAgent(HttpContext context);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
namespace Glimpse.Server.Web.Framework
{
public interface IAuthorizeAgent
{
bool AllowAgent(HttpContext context);
}
}
| mit | C# |
51cb32b23f4007037b11a2222009b56fdfbaf423 | Exclude string from data fields | AndMu/Wikiled.Arff | src/Wikiled.Arff/Extensions/ArffDataSetExtension.cs | src/Wikiled.Arff/Extensions/ArffDataSetExtension.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Wikiled.Arff.Logic;
using Wikiled.Arff.Logic.Headers;
namespace Wikiled.Arff.Extensions
{
public static class ArffDataSetExtension
{
public static IEnumerable<(int? Y, double[] X)> GetData(this IArffDataSet dataSet)
{
var table = GetFeatureTable(dataSet);
foreach (var dataRow in dataSet.Documents)
{
var y = dataSet.Header.Class?.ReadClassIdValue(dataRow.Class);
yield return (y, dataRow.GetX(table));
}
}
public static Dictionary<IHeader, int> GetFeatureTable(this IArffDataSet dataSet)
{
var headers = dataSet.Header
.Where(item => dataSet.Header.Class != item && !(item is DateHeader) && !(item is StringHeader))
.OrderBy(item => dataSet.Header.GetIndex(item));
var table = new Dictionary<IHeader, int>();
int index = 0;
foreach (var header in headers)
{
table[header] = index;
index++;
}
return table;
}
private static double[] GetX(this IArffDataRow row, Dictionary<IHeader, int> headers)
{
double[] x = new double[headers.Count];
for (int i = 0; i < x.Length; i++)
{
x[i] = 0;
}
foreach (var wordsData in row.GetRecords())
{
if (!headers.TryGetValue(wordsData.Header, out var index))
{
continue;
}
double value = 1;
if (wordsData.Value != null)
{
value = Convert.ToDouble(wordsData.Value);
}
x[index] = value;
}
return x;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Wikiled.Arff.Logic;
using Wikiled.Arff.Logic.Headers;
namespace Wikiled.Arff.Extensions
{
public static class ArffDataSetExtension
{
public static IEnumerable<(int? Y, double[] X)> GetData(this IArffDataSet dataSet)
{
var table = GetFeatureTable(dataSet);
foreach (var dataRow in dataSet.Documents)
{
var y = dataSet.Header.Class?.ReadClassIdValue(dataRow.Class);
yield return (y, dataRow.GetX(table));
}
}
public static Dictionary<IHeader, int> GetFeatureTable(this IArffDataSet dataSet)
{
var headers = dataSet.Header.Where(item => dataSet.Header.Class != item && !(item is DateHeader)).OrderBy(item => dataSet.Header.GetIndex(item));
var table = new Dictionary<IHeader, int>();
int index = 0;
foreach (var header in headers)
{
table[header] = index;
index++;
}
return table;
}
private static double[] GetX(this IArffDataRow row, Dictionary<IHeader, int> headers)
{
double[] x = new double[headers.Count];
for (int i = 0; i < x.Length; i++)
{
x[i] = 0;
}
foreach (var wordsData in row.GetRecords())
{
if (!headers.TryGetValue(wordsData.Header, out var index))
{
continue;
}
double value = 1;
if (wordsData.Value != null)
{
value = Convert.ToDouble(wordsData.Value);
}
x[index] = value;
}
return x;
}
}
}
| mit | C# |
67b19b12a65337dd92f633a68f74744bcef41b0c | Update ServiceModel class template | mlruzic/visual-studio-scaffolding | Scaffolder/Resources/Templates/Models/_ServiceModelName_.cs | Scaffolder/Resources/Templates/Models/_ServiceModelName_.cs | namespace $ModuleNamespace$.Models
{
using Se.Core.Models;
using ShoutEm.Common.Cloning;
public class $ServiceModelName$ : ModelBase<long>, IShallowCloneable<$ServiceModelName$>
{
$rest(TableColumns): {col
| public $col.DotNetType$ $col.Name$ { get; set; \}}; separator="\n\n"$
public $ServiceModelName$ ShallowClone()
{
return MemberwiseClone() as $ServiceModelName$;
}
}
}
| namespace $ModuleNamespace$.Models
{
using Se.Core.Models;
using ShoutEm.Common.Cloning;
public class $ServiceModelName$ : ModelBase<long>, IShallowCloneable<$ServiceModelName$>
{
$TableColumns: {col
| public $col.DotNetType$ $col.Name$ { get; set; \}}; separator="\n\n"$
public $ServiceModelName$ ShallowClone()
{
return MemberwiseClone() as $ServiceModelName$;
}
}
}
| mit | C# |
efd5df46a0f5b973bd91debd153c0f7936ee31a7 | improve notification helper api | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Helpers/NotificationHelpers.cs | WalletWasabi.Gui/Helpers/NotificationHelpers.cs | using Avalonia.Controls.Notifications;
using Splat;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Helpers
{
public static class NotificationHelpers
{
public static INotificationManager GetNotificationManager()
{
return Locator.Current.GetService<INotificationManager>();
}
public static void Success (string message, string title = "Success!")
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Success));
}
public static void Information (string message, string title = "Info!")
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Warning));
}
public static void Warning (string message, string title = "Warning!")
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Warning));
}
public static void Error(string message, string title = "Error!")
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Error));
}
}
}
| using Avalonia.Controls.Notifications;
using Splat;
using System;
using System.Collections.Generic;
using System.Text;
namespace WalletWasabi.Gui.Helpers
{
public static class NotificationHelpers
{
public static INotificationManager GetNotificationManager()
{
return Locator.Current.GetService<INotificationManager>();
}
public static void Information (string title, string message)
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Information));
}
public static void Warning (string title, string message)
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Warning));
}
public static void Error(string title, string message)
{
GetNotificationManager().Show(new Notification(title, message, NotificationType.Error));
}
}
}
| mit | C# |
354804c3fc4c72636848af330374ca3ec17be26d | Add document representation code | peterblazejewicz/m101DotNet-vNext,peterblazejewicz/m101DotNet-vNext | M101DotNet/Program.cs | M101DotNet/Program.cs | using System;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
namespace M101DotNet
{
public class Program
{
public static void Main(string[] args)
{
MainAsync(args).Wait();
Console.WriteLine();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task MainAsync(string[] args)
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var db = client.GetDatabase("test");
var doc = new BsonDocument
{
{"name", "Jones"}
};
doc.Add("age", 30);
doc["profession"] = "hacker";
var nestedArray = new BsonArray();
nestedArray.Add(new BsonDocument("color", "red"));
doc.Add("array", nestedArray);
Console.WriteLine(doc);
}
}
} | using System;
using System.Threading.Tasks;
using MongoDB.Driver;
namespace M101DotNet
{
public class Program
{
public static void Main(string[] args)
{
MainAsync(args).Wait();
Console.WriteLine();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task MainAsync(string[] args)
{
var client = new MongoClient();
}
}
} | mit | C# |
8d0843b2d2cc0aeb5944ecf184600774fa598170 | Make published_at nullable | plangrid/plangrid-api-net | PlanGrid.Api/Sheet.cs | PlanGrid.Api/Sheet.cs | using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace PlanGrid.Api
{
public class Sheet
{
[JsonProperty("uid")]
public string Uid { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("version_name")]
public string VersionName { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("tags")]
public string[] Tags { get; set; }
[JsonProperty("published_by")]
public UserReference PublishedBy { get; set; }
[JsonProperty("published_at")]
public DateTime? PublishedAt { get; set; }
[JsonProperty("deleted")]
public bool IsDeleted { get; set; }
[JsonProperty("uploaded_file_name")]
public string UploadedFileName { get; set; }
public override string ToString()
{
return $"{Name} ({PublishedAt} by {PublishedBy.Email})";
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace PlanGrid.Api
{
public class Sheet
{
[JsonProperty("uid")]
public string Uid { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("version_name")]
public string VersionName { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("tags")]
public string[] Tags { get; set; }
[JsonProperty("published_by")]
public UserReference PublishedBy { get; set; }
[JsonProperty("published_at")]
public DateTime PublishedAt { get; set; }
[JsonProperty("deleted")]
public bool IsDeleted { get; set; }
[JsonProperty("uploaded_file_name")]
public string UploadedFileName { get; set; }
public override string ToString()
{
return $"{Name} ({PublishedAt} by {PublishedBy.Email})";
}
}
}
| mit | C# |
a7dcabfb282c3ba51d1994c70e9e20985fb5288f | Update version | DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Resources;
// WARNING this file is shared accross multiple projects
[assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")]
[assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2017")]
[assembly: AssemblyCompany("CodePlex Foundation")]
[assembly: AssemblyVersion("17.1.0.0")]
[assembly: AssemblyFileVersion("17.1.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| using System.Reflection;
using System.Resources;
// WARNING this file is shared accross multiple projects
[assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")]
[assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2017")]
[assembly: AssemblyCompany("CodePlex Foundation")]
[assembly: AssemblyVersion("17.0.0.0")]
[assembly: AssemblyFileVersion("17.0.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| bsd-3-clause | C# |
9f6f0ae289660c8f3658237114b6de1efb5206d3 | Refactor and improve the if-statement. | BerniceChua/Unity-Procedural-Cave-Generation-Tutorial | Assets/_Scripts/Detect2DOr3D.cs | Assets/_Scripts/Detect2DOr3D.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class ToggleEvent : UnityEvent<bool> { }
public class Detect2DOr3D : MonoBehaviour {
public GameObject m_caveMesh;
public GameObject m_mainCamera;
public GameObject m_fpsCamera;
//public CustomSimplePlayer script3D;
//public Custom2DSimplePlayer script2D;
public GameObject m_meshGenerator;
public GameObject m_playerController;
// Use this for initialization
void Start () {
DetectOrientation();
}
void DetectOrientation () {
//if (m_caveMesh.transform.rotation.eulerAngles.x == 270 || m_caveMesh.transform.rotation.eulerAngles.x == -90) {
if (m_caveMesh.GetComponent<MeshGenerator>().is2D == true) {
m_fpsCamera.SetActive(false);
m_mainCamera.SetActive(true);
m_playerController.AddComponent<CapsuleCollider2D>();
m_playerController.AddComponent<Rigidbody2D>();
m_playerController.GetComponent<Rigidbody2D>().gravityScale = 0; // This prevents the player character from sliding down, since the map is tilted 270 degrees or -90 degrees.
m_playerController.AddComponent<Custom2DSimplePlayer>();
} else if (m_caveMesh.transform.rotation.eulerAngles.x == 0) {
m_fpsCamera.SetActive(true);
m_mainCamera.SetActive(false);
m_playerController.AddComponent<CapsuleCollider>();
m_playerController.AddComponent<Rigidbody>();
m_playerController.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
m_playerController.AddComponent<CustomSimplePlayer>();
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class ToggleEvent : UnityEvent<bool> { }
public class Detect2DOr3D : MonoBehaviour {
public GameObject m_caveMesh;
public GameObject m_mainCamera;
public GameObject m_fpsCamera;
//public CustomSimplePlayer script3D;
//public Custom2DSimplePlayer script2D;
//public GameObject m_mapGenerator;
public GameObject m_playerController;
// Use this for initialization
void Start () {
DetectOrientation();
}
void DetectOrientation () {
if (m_caveMesh.transform.rotation.eulerAngles.x == 270 || m_caveMesh.transform.rotation.eulerAngles.x == -90) {
m_fpsCamera.SetActive(false);
m_mainCamera.SetActive(true);
m_playerController.AddComponent<CapsuleCollider2D>();
m_playerController.AddComponent<Rigidbody2D>();
m_playerController.GetComponent<Rigidbody2D>().gravityScale = 0; // This prevents the player character from sliding down, since the map is tilted 270 degrees or -90 degrees.
m_playerController.AddComponent<Custom2DSimplePlayer>();
} else if (m_caveMesh.transform.rotation.eulerAngles.x == 0) {
m_fpsCamera.SetActive(true);
m_mainCamera.SetActive(false);
m_playerController.AddComponent<CapsuleCollider>();
m_playerController.AddComponent<Rigidbody>();
m_playerController.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
m_playerController.AddComponent<CustomSimplePlayer>();
}
}
}
| mit | C# |
a44ca61e831ef63d176d4b0fc85c7dba22fd9947 | remove base class from fields | Axosoft/AxosoftAPI.NET | AxosoftAPI.NET/Models/Fields.cs | AxosoftAPI.NET/Models/Fields.cs | using System;
using Newtonsoft.Json;
namespace AxosoftAPI.NET.Models
{
public class Fields
{
[JsonProperty("field")]
public string Field { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("info")]
public string Info { get; set; }
[JsonProperty("cols")]
public string Cols { get; set; }
[JsonProperty("editable")]
public Boolean Editable { get; set; }
}
}
| using System;
using Newtonsoft.Json;
namespace AxosoftAPI.NET.Models
{
public class Fields : BaseModel
{
[JsonProperty("field")]
public string Field { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("info")]
public string Info { get; set; }
[JsonProperty("cols")]
public string Cols { get; set; }
[JsonProperty("editable")]
public Boolean Editable { get; set; }
}
}
| mit | C# |
211232fabf9a94cdd41bc33cdd2624fcf5231d58 | Update Program.cs | ThomasKV/GitTest1 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// This remark was inserted using GitHub
// Another remark inserted using GitHub
// Code to call Feature1 class and some thing else
// Add code to call Feature3
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// This remark was inserted using GitHub
// Another remark inserted using GitHub
// Code to call Feature1 class and some thing else
}
}
}
| mit | C# |
6c82bce8cd9a1c58e518be8c90d04aff97965030 | fix null set | titanium007/Windows-User-Action-Hook,titanium007/EventHook,justcoding121/Windows-User-Action-Hook | EventHook/Helpers/AsyncQueue.cs | EventHook/Helpers/AsyncQueue.cs | using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace EventHook.Helpers
{
/// <summary>
/// A concurrent queue facilitating async dequeue with minimal locking
/// Assumes single/multi-threaded producer and a single-threaded consumer
/// </summary>
/// <typeparam name="T"></typeparam>
internal class AsyncQueue<T>
{
private CancellationToken taskCancellationToken;
internal AsyncQueue(CancellationToken taskCancellationToken)
{
this.taskCancellationToken = taskCancellationToken;
}
/// <summary>
/// Backing queue
/// </summary>
ConcurrentQueue<T> queue = new ConcurrentQueue<T>();
/// <summary>
/// Keeps any pending Dequeue task to wake up once data arrives
/// </summary>
TaskCompletionSource<bool> dequeueTask;
/// <summary>
/// Supports multi-threaded producers
/// </summary>
/// <param name="value"></param>
internal void Enqueue(T value)
{
queue.Enqueue(value);
//wake up the dequeue task with result
dequeueTask?.TrySetResult(true);
}
/// <summary>
/// Assumes a single-threaded consumer!
/// </summary>
/// <returns></returns>
internal async Task<T> DequeueAsync()
{
T result;
queue.TryDequeue(out result);
if (result != null)
{
return result;
}
dequeueTask = new TaskCompletionSource<bool>();
taskCancellationToken.Register(() => dequeueTask.TrySetCanceled());
await dequeueTask.Task;
queue.TryDequeue(out result);
return result;
}
}
}
| using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace EventHook.Helpers
{
/// <summary>
/// A concurrent queue facilitating async dequeue with minimal locking
/// Assumes single/multi-threaded producer and a single-threaded consumer
/// </summary>
/// <typeparam name="T"></typeparam>
internal class AsyncQueue<T>
{
private CancellationToken taskCancellationToken;
internal AsyncQueue(CancellationToken taskCancellationToken)
{
this.taskCancellationToken = taskCancellationToken;
}
/// <summary>
/// Backing queue
/// </summary>
ConcurrentQueue<T> queue = new ConcurrentQueue<T>();
/// <summary>
/// Keeps any pending Dequeue task to wake up once data arrives
/// </summary>
TaskCompletionSource<bool> dequeueTask;
/// <summary>
/// Supports multi-threaded producers
/// </summary>
/// <param name="value"></param>
internal void Enqueue(T value)
{
queue.Enqueue(value);
//wake up the dequeue task with result
dequeueTask?.TrySetResult(true);
}
/// <summary>
/// Assumes a single-threaded consumer!
/// </summary>
/// <returns></returns>
internal async Task<T> DequeueAsync()
{
T result;
queue.TryDequeue(out result);
if (result != null)
{
return result;
}
dequeueTask = new TaskCompletionSource<bool>();
taskCancellationToken.Register(() => dequeueTask.TrySetCanceled());
await dequeueTask.Task;
dequeueTask = null;
queue.TryDequeue(out result);
return result;
}
}
}
| mit | C# |
e67fc8f8f3ae4e185402cc39157abf292afb39f7 | Print to BattleNet log | Goz3rr/UnityHook,synap5e/UnityHook | HookRegistry/BackendSwitcher.cs | HookRegistry/BackendSwitcher.cs | using System;
using System.Reflection;
namespace Hooks
{
[RuntimeHookAttribute]
public class BackendSwitcher
{
public BackendSwitcher()
{
HookRegistry.Register (OnCall);
}
object OnCall(string typeName, string methodName, object thisObj, params object[] args) {
if (typeName != "BattleNet" || methodName != ".cctor") {
return null;
}
string backend = Vars.Key("Aurora.Backend").GetStr("BattleNetDll");
IBattleNet impl;
if (backend == "BattleNetDll") {
impl = new BattleNetDll ();
} else if (backend == "BattleNetCSharp") {
impl = new BattleNetCSharp();
} else {
throw new NotImplementedException("Invalid Battle.net Backend (Aurora.Backend)");
}
typeof(BattleNet).GetField("s_impl", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, impl);
Log.BattleNet.Print("Forced BattleNet backend to {0}", backend);
return 1;
}
}
} | using System;
using System.Reflection;
namespace Hooks
{
[RuntimeHookAttribute]
public class BackendSwitcher
{
public BackendSwitcher()
{
HookRegistry.Register (OnCall);
}
object OnCall(string typeName, string methodName, object thisObj, params object[] args) {
if (typeName != "BattleNet" || methodName != ".cctor") {
return null;
}
string backend = Vars.Key("Aurora.Backend").GetStr("BattleNetDll");
IBattleNet impl;
if (backend == "BattleNetDll") {
impl = new BattleNetDll ();
} else if (backend == "BattleNetCSharp") {
impl = new BattleNetCSharp();
} else {
throw new NotImplementedException("Invalid Battle.net Backend (Aurora.Backend)");
}
typeof(BattleNet).GetField("s_impl", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, impl);
Log.Bob.Print("Forced BattleNet backend to {0}", backend);
return 1;
}
}
} | mit | C# |
1f7def97df318bcb3f4cfe8487b0c4227878cdee | Fix typo | gmich/Results | Gmich.Results.Tests/ResultTests.cs | Gmich.Results.Tests/ResultTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Gmich.Results.Tests
{
[TestClass]
public class ResultTests
{
private Result SuccessfulResult => Result.Ok();
private Result FailedResult => Result.FailWith(State.Error, "Failed Result");
[TestMethod]
public void SuccessfulResult_Test()
{
SuccessfulResult
.OnSuccess(res =>
Assert.IsTrue(res.Success))
.OnFailure(res =>
Assert.Fail("This should be successful"));
}
[TestMethod]
public void FailedResult_Test()
{
FailedResult
.OnSuccess(res =>
Assert.Fail("This should fail"))
.OnFailure(res =>
Assert.IsTrue(res.Failure));
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Gmich.Results.Tests
{
[TestClass]
public class ResultTests
{
private Result SuccessfulResult => Result.Ok();
private Result FailedResult => Result.FailWith(State.Error, "Failed Result");
[TestMethod]
public void SuccessfulResult_Test()
{
SuccessfulResult
.OnSuccess(res =>
Assert.IsTrue(res.Success))
.OnFailure(res =>
Assert.Fail("This should be successful"));
}
[TestMethod]
public void FailedResult_Test()
{
SuccessfulResult
.OnSuccess(res =>
Assert.Fail("This should fail"))
.OnFailure(res =>
Assert.IsTrue(res.Failure));
}
}
}
| mit | C# |
8bf207eb545a4b6ca29c955c2e9d6e50a99addff | Test IsNearExpiracy while converted ToLocalTime | createitpt/Create.CSP.GitHub.Reporting,createitpt/Create.CSP.GitHub.Reporting,createitpt/Create.CSP.GitHub.Reporting | Job/Entities/AuthorizationToken.cs | Job/Entities/AuthorizationToken.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Create.CSP.GitHub.Reporting.Entities
{
public class AuthorizationToken
{
/// <summary>
/// Captures when the token expires
/// </summary>
public DateTime ExpiresOn { get; set; }
/// <summary>
/// Access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Constructor for getting an authorization token
/// </summary>
/// <param name="access_Token">access token</param>
/// <param name="expires_in">number of seconds the token is valid for</param>
public AuthorizationToken(string access_Token, long expires_in)
{
this.AccessToken = access_Token;
this.ExpiresOn = DateTime.UtcNow.AddSeconds(expires_in);
}
public AuthorizationToken(string accessToken, DateTime expiresOn)
{
this.AccessToken = accessToken;
this.ExpiresOn = expiresOn.ToLocalTime();
}
/// <summary>
/// Returns true if the authorization token is near expiracy.
/// </summary>
/// <returnsTtrue if the authorization token is near expiracy. False otherwise.</returns>
public bool IsNearExpiracy()
{
//// if token is expiring in the next minute or expired, return true
return DateTime.UtcNow.ToLocalTime() > this.ExpiresOn.AddMinutes(-1);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Create.CSP.GitHub.Reporting.Entities
{
public class AuthorizationToken
{
/// <summary>
/// Captures when the token expires
/// </summary>
public DateTime ExpiresOn { get; set; }
/// <summary>
/// Access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Constructor for getting an authorization token
/// </summary>
/// <param name="access_Token">access token</param>
/// <param name="expires_in">number of seconds the token is valid for</param>
public AuthorizationToken(string access_Token, long expires_in)
{
this.AccessToken = access_Token;
this.ExpiresOn = DateTime.UtcNow.AddSeconds(expires_in);
}
public AuthorizationToken(string accessToken, DateTime expiresOn)
{
this.AccessToken = accessToken;
this.ExpiresOn = expiresOn.ToLocalTime();
}
/// <summary>
/// Returns true if the authorization token is near expiracy.
/// </summary>
/// <returnsTtrue if the authorization token is near expiracy. False otherwise.</returns>
public bool IsNearExpiracy()
{
//// if token is expiring in the next minute or expired, return true
return DateTime.UtcNow > this.ExpiresOn.AddMinutes(-1);
}
}
}
| mit | C# |
e11fc783b6f12666f6a05689f7975071def336d5 | Update SpaceHolder.cs | NikIvRu/NectarineProject | Mall/SpaceHolder/SpaceHolder.cs | Mall/SpaceHolder/SpaceHolder.cs | namespace Mall.Staff
{
using System;
using System.Collections.Generic;
public class SpaceHolder
{
//Fields
private decimal bankBalance;
private string owner;
private string companyName;
//Constructors
public SpaceHolder(string companyName, string owner, decimal bankBalance, Booth Booth)
{
this.CompanyName = companyName;
this.Owner = owner;
this.BankBalance = bankBalance;
this.Boot = Booth;
this.Personal = Personal;
this.Sellable = Sellable;
}
//Properties
public Booth Boot { get; private set; }
public IList<Employee> Personal { get; private set; }
public IList<ISellable> Sellable { get; private set; }
public decimal BankBalance
{
get { return this.bankBalance; }
private set { this.bankBalance = value; }
}
public string Owner
{
get { return this.owner; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Please enter owner of the company, using this space");
}
this.owner = value;
}
}
public string CompanyName
{
get { return this.companyName; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Please enter correct name for the company, using this space");
}
this.companyName = value;
}
}
//Enums
//Interfaces
//Methods // TO DO - May be some method - if bankBalance is less than zero - company should leave the mall
}
}
| namespace Mall.Staff
{
using System;
public class SpaceHolder
{
//Fields
//Constructors
//Enums
//Interfaces
//Properties
//Methods
}
} | mit | C# |
10be4fc4b02194024f0b21b901b20a2fed149f16 | Update RuleUpdater.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | ProcessBlockUtil/RuleUpdater.cs | ProcessBlockUtil/RuleUpdater.cs | /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
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.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung)");
Console.WriteLine(" ");
Console.WriteLine("Process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
Console.WriteLine("Obtaining Paths...");
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete and copy Exist file.
*/
Console.WriteLine("Deleting old file...");
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt");
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
Console.WriteLine("Downloading new rules...");
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Restarting Service....");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
/*
Ending message.
*/
Console.WriteLine("Process Ended, you can close window.");
Console.ReadLine();
}
}
}
| /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
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.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung");
Console.WriteLine(" ");
Console.WriteLine("Process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
Console.WriteLine("Obtaining Paths...");
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete and copy Exist file.
*/
Console.WriteLine("Deleting old file...");
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt");
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
Console.WriteLine("Downloading new rules...");
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Restarting Service....");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
Console.WriteLine("Process Ended, you can close window.");
Console.ReadLine();
}
}
}
| apache-2.0 | C# |
135854049ac037d9d16bd23cbf2946058ef02c6e | Update RuleUpdater.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | ProcessBlockUtil/RuleUpdater.cs | ProcessBlockUtil/RuleUpdater.cs | /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
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.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung");
Console.WriteLine(" ");
Console.WriteLine("The process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete and copy Exist file.
*/
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Restarting Service....");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
}
}
}
| /*
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
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.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NetUtil;
namespace ACProcessBlockUtil
{
class RuleUpdater
{
public static void Main(String[] a){
/*
Version message.
*/
Console.WriteLine("AC PBU RuleUpdater V1.0.1");
Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung");
Console.WriteLine(" ");
Console.WriteLine("The process is starting, please make sure the program running.");
/*
Stop The Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Stop();
pbuSC.WaitForStatus(ServiceControllerStatus.Stopped);
/*
Obtain some path.
*/
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
/*
Delete Exist file.
*/
if(File.Exists(userProfile + "\\ACRules.txt")){
File.Delete(userProfile + "\\ACRules.txt");
}
/*
Download File.
*/
NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt");
/*
Restart the Service.
*/
Console.WriteLine("Stopping Service....");
ServiceController pbuSC = new ServiceController("pbuService");
pbuSC.Start();
pbuSC.WaitForStatus(ServiceControllerStatus.Running);
}
}
}
| apache-2.0 | C# |
33994eb032fae9c630ff07ac03d2d40f57b726d6 | Fix for not using the Instance commandline argument. If the argument is specified then this will be used before the command is dispatched. | Particular/Topshelf,Particular/Topshelf,Particular/Topshelf,Particular/Topshelf | src/Topshelf/TopshelfDispatcher.cs | src/Topshelf/TopshelfDispatcher.cs | // Copyright 2007-2010 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf
{
using System.Collections.Generic;
using System.Linq;
using Commands;
using Configuration;
using log4net;
public static class TopshelfDispatcher
{
static readonly ILog _log = LogManager.GetLogger("Topshelf.TopshelfDispatcher");
public static void Dispatch(RunConfiguration config, TopshelfArguments args)
{
//find the command by the args 'Command'
var run = new RunCommand(config.Coordinator, config.WinServiceSettings.ServiceName);
if(!string.IsNullOrEmpty(args.Instance))
{
_log.Info("Using instance name from commandline.");
config.WinServiceSettings.ServiceName = new ServiceName(
config.WinServiceSettings.ServiceName.Name,
args.Instance);
}
var command = new List<Command>
{
run,
new InstallService(config.WinServiceSettings),
new UninstallService(config.WinServiceSettings)
}
.Where(x => x.Name == args.ActionName)
.DefaultIfEmpty(run)
.SingleOrDefault();
_log.DebugFormat("Running command: '{0}'", command.Name);
command.Execute();
}
}
} | // Copyright 2007-2010 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf
{
using System.Collections.Generic;
using System.Linq;
using Commands;
using Configuration;
using log4net;
public static class TopshelfDispatcher
{
static readonly ILog _log = LogManager.GetLogger("Topshelf.TopshelfDispatcher");
public static void Dispatch(RunConfiguration config, TopshelfArguments args)
{
//find the command by the args 'Command'
var run = new RunCommand(config.Coordinator, config.WinServiceSettings.ServiceName);
var command = new List<Command>
{
run,
new InstallService(config.WinServiceSettings),
new UninstallService(config.WinServiceSettings)
}
.Where(x => x.Name == args.ActionName)
.DefaultIfEmpty(run)
.SingleOrDefault();
_log.DebugFormat("Running command: '{0}'", command.Name);
command.Execute();
}
}
} | apache-2.0 | C# |
fd0e4c5bb74fd9b3fec1ddd95ec276d91d34b2a4 | remove unneeded method. | bordoley/RxApp | RxApp.Android/AndroidInterfaces.cs | RxApp.Android/AndroidInterfaces.cs | using Android.App;
using Android.Content;
using Android.Views;
namespace RxApp.Android
{
public interface IAndroidApplication
{
Context ApplicationContext { get; }
void OnCreate();
void OnTerminate();
}
public interface IActivity
{
Application Application { get; }
FragmentManager FragmentManager { get; }
void Finish();
}
} | using Android.App;
using Android.Content;
using Android.Views;
namespace RxApp.Android
{
public interface IAndroidApplication
{
Context ApplicationContext { get; }
void OnCreate();
void OnTerminate();
}
public interface IActivity
{
Application Application { get; }
FragmentManager FragmentManager { get; }
void Finish();
bool OnOptionsItemSelected(IMenuItem item);
}
} | apache-2.0 | C# |
43b1ac3c08de8acb0cedac8eaf06bba1a613d3cf | set enum key for CustomFieldType | rolembergfilho/Serenity,TukekeSoft/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,linpiero/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,linpiero/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,linpiero/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,TukekeSoft/Serenity,volkanceylan/Serenity,linpiero/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,TukekeSoft/Serenity,dfaruque/Serenity,volkanceylan/Serenity,linpiero/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity | Serenity.Data.Entity/CustomFields/CustomFieldType.cs | Serenity.Data.Entity/CustomFields/CustomFieldType.cs | using Serenity.ComponentModel;
using System.ComponentModel;
namespace Serenity.Data
{
[EnumKey("CustomFieldType")]
public enum CustomFieldType
{
[Description("Metin (String)")]
String = 1,
[Description("Tamsayı (Int32)")]
Int32 = 2,
[Description("Tamsayı (Int64)")]
Int64 = 3,
[Description("Ondalıklı Sayı (Decimal)")]
Decimal = 4,
[Description("Tarih (Date)")]
Date = 5,
[Description("Tarih / Zaman (DateTime)")]
DateTime = 6,
[Description("Mantıksal (Boolean)")]
Boolean = 7
}
} | using System.ComponentModel;
namespace Serenity.Data
{
public enum CustomFieldType
{
[Description("Metin (String)")]
String = 1,
[Description("Tamsayı (Int32)")]
Int32 = 2,
[Description("Tamsayı (Int64)")]
Int64 = 3,
[Description("Ondalıklı Sayı (Decimal)")]
Decimal = 4,
[Description("Tarih (Date)")]
Date = 5,
[Description("Tarih / Zaman (DateTime)")]
DateTime = 6,
[Description("Mantıksal (Boolean)")]
Boolean = 7
}
} | mit | C# |
81d8a6a8948c6879d8225334f3a3c12d320cd5e6 | Remove unneeded test case, | adamchester/AutoFixture,hackle/AutoFixture,adamchester/AutoFixture,AutoFixture/AutoFixture,hackle/AutoFixture,zvirja/AutoFixture,dcastro/AutoFixture,sbrockway/AutoFixture,sergeyshushlyapin/AutoFixture,sbrockway/AutoFixture,Pvlerick/AutoFixture,sean-gilliam/AutoFixture,sergeyshushlyapin/AutoFixture,dcastro/AutoFixture | Src/AutoFixtureUnitTest/Utf8EncodingGeneratorTest.cs | Src/AutoFixtureUnitTest/Utf8EncodingGeneratorTest.cs | using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Kernel;
using Ploeh.AutoFixtureUnitTest.Kernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace Ploeh.AutoFixtureUnitTest
{
public class Utf8EncodingGeneratorTest
{
[Fact]
public void SutIsSpecimenBuilder()
{
var sut = new Utf8EncodingGenerator();
Assert.IsAssignableFrom<ISpecimenBuilder>(sut);
}
[Fact]
public void CreateWithEncodingRequestWillReturnUtf8Encoding()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
var result = sut.Create(typeof(Encoding), new DelegatingSpecimenContext());
// Assert
Assert.Equal(Encoding.UTF8, result);
}
[Fact]
public void CreateWithNullRequestWillReturnNoSpecimen()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
var result = sut.Create(null, new DelegatingSpecimenContext());
// Assert
Assert.Equal(new NoSpecimen(), result);
}
[Fact]
public void CreateWithNonTypeRequestWillReturnNoSpecimen()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
var result = sut.Create(new object(), new DelegatingSpecimenContext());
// Assert
Assert.Equal(new NoSpecimen(), result);
}
}
}
| using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Kernel;
using Ploeh.AutoFixtureUnitTest.Kernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace Ploeh.AutoFixtureUnitTest
{
public class Utf8EncodingGeneratorTest
{
[Fact]
public void SutIsSpecimenBuilder()
{
var sut = new Utf8EncodingGenerator();
Assert.IsAssignableFrom<ISpecimenBuilder>(sut);
}
[Fact]
public void CreateWithEncodingRequestWillReturnUtf8Encoding()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
var result = sut.Create(typeof(Encoding), new DelegatingSpecimenContext());
// Assert
Assert.Equal(Encoding.UTF8, result);
}
[Fact]
public void CreateWithNullRequestWillReturnNoSpecimen()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
var result = sut.Create(null, new DelegatingSpecimenContext());
// Assert
Assert.Equal(new NoSpecimen(), result);
}
[Fact]
public void CreateWithNullContextDoesNotThrow()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
Assert.DoesNotThrow(() => sut.Create(typeof(object), null));
}
[Fact]
public void CreateWithNonTypeRequestWillReturnNoSpecimen()
{
// Arrange
var sut = new Utf8EncodingGenerator();
// Act
var result = sut.Create(new object(), new DelegatingSpecimenContext());
// Assert
Assert.Equal(new NoSpecimen(), result);
}
}
}
| mit | C# |
8eb03beb80cf3859a52d763fcb6a486ae46cfd87 | Fix whitespace linting issue. | RehanSaeed/Schema.NET | Source/Schema.NET/Thing.Partial.cs | Source/Schema.NET/Thing.Partial.cs | namespace Schema.NET
{
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Thing : JsonLdObject
{
private const string ContextPropertyJson = "\"@context\":\"http://schema.org\",";
/// <summary>
/// Serializer settings used.
/// Note: Escapes HTML to avoid XSS vulnerabilities where user-supplied data is used.
/// </summary>
private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings()
{
Converters = new List<JsonConverter>()
{
new StringEnumConverter()
},
NullValueHandling = NullValueHandling.Ignore,
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
/// <summary>
/// Returns the JSON-LD representation of this instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents the JSON-LD representation of this instance.
/// </returns>
public override string ToString() =>
RemoveAllButFirstContext(JsonConvert.SerializeObject(this, SerializerSettings));
private static string RemoveAllButFirstContext(string json)
{
var stringBuilder = new StringBuilder(json);
var startIndex = ContextPropertyJson.Length + 1; // We add the one to represent the opening curly brace.
stringBuilder.Replace(ContextPropertyJson, string.Empty, startIndex, stringBuilder.Length - startIndex);
return stringBuilder.ToString();
}
}
}
| namespace Schema.NET
{
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Thing : JsonLdObject
{
private const string ContextPropertyJson = "\"@context\":\"http://schema.org\",";
/// <summary>
/// Serializer settings used.
/// Note: Escapes HTML to avoid XSS vulnerabilities where user-supplied data is used.
/// </summary>
private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings()
{
Converters = new List<JsonConverter>()
{
new StringEnumConverter()
},
NullValueHandling = NullValueHandling.Ignore,
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
/// <summary>
/// Returns the JSON-LD representation of this instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents the JSON-LD representation of this instance.
/// </returns>
public override string ToString() =>
RemoveAllButFirstContext(JsonConvert.SerializeObject(this, SerializerSettings));
private static string RemoveAllButFirstContext(string json)
{
var stringBuilder = new StringBuilder(json);
var startIndex = ContextPropertyJson.Length + 1; // We add the one to represent the opening curly brace.
stringBuilder.Replace(ContextPropertyJson, string.Empty, startIndex, stringBuilder.Length - startIndex);
return stringBuilder.ToString();
}
}
}
| mit | C# |
408defff7d685494271bd1dfae87fe7b86792aed | Add shared project for models for client-server communication. | robinsedlaczek/ModelR | WaveDev.ModelR.Server/ModelRHub.cs | WaveDev.ModelR.Server/ModelRHub.cs | using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
using System;
using System.Globalization;
using WaveDev.ModelR.Shared.Models;
namespace WaveDev.ModelR.Server
{
public class ModelRHub : Hub
{
#region Private Fields
private IList<SceneInfoModel> _scenes;
#endregion
#region Constructor
public ModelRHub()
{
_scenes = new List<SceneInfoModel>
{
new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 1", Description = "The first default scene at the server." },
new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 2", Description = "Just another scene." }
};
}
#endregion
#region Public Overrides
public override Task OnConnected()
{
Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' connected.", Context.ConnectionId));
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' disconnected.", Context.ConnectionId));
return base.OnDisconnected(stopCalled);
}
#endregion
#region Public Hub Methods
public IEnumerable<SceneInfoModel> GetAvailableScenes()
{
return _scenes;
}
[Authorize]
public void JoinSceneGroup(Guid sceneId)
{
}
[Authorize]
public void CreateSceneObject()
{
}
#endregion
}
}
| using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
using WaveDev.ModelR.Models;
using System;
using System.Globalization;
namespace WaveDev.ModelR.Server
{
public class ModelRHub : Hub
{
#region Private Fields
private IList<SceneInfoModel> _scenes;
#endregion
#region Constructor
public ModelRHub()
{
_scenes = new List<SceneInfoModel>
{
new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 1", Description = "The first default scene at the server." },
new SceneInfoModel { Id = Guid.NewGuid(), Name = "Scene 2", Description = "Just another scene." }
};
}
#endregion
#region Public Overrides
public override Task OnConnected()
{
Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' connected.", Context.ConnectionId));
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Console.WriteLine(string.Format(CultureInfo.CurrentUICulture, "Client '{0}' disconnected.", Context.ConnectionId));
return base.OnDisconnected(stopCalled);
}
#endregion
#region Public Hub Methods
public IEnumerable<SceneInfoModel> GetAvailableScenes()
{
return _scenes;
}
[Authorize]
public void JoinSceneGroup(Guid sceneId)
{
}
#endregion
}
}
| mit | C# |
2cda4ebd4a8522883cbdfb5856d1d4f49a6130ec | Increment assembly version | gibachan/XmlDict | XmlDict/Properties/AssemblyInfo.cs | XmlDict/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("XmlDict")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XmlDict")]
[assembly: AssemblyCopyright("Copyright © 2017 gibachan")]
[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("49919141-c1ed-4f8c-9af2-686102a6e994")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.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("XmlDict")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XmlDict")]
[assembly: AssemblyCopyright("Copyright © 2017 gibachan")]
[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("49919141-c1ed-4f8c-9af2-686102a6e994")]
// 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# |
331502558707bdb13c10e864c5f90e96633396e3 | Clear out UnixFD | tmds/Tmds.DBus | src/Tmds.DBus/UnixFd.cs | src/Tmds.DBus/UnixFd.cs | // Copyright 2016 Tom Deseyn <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
namespace Tmds.DBus
{
// This is a placeholder type for DBus UNIX_FD ('h') type.
// The UNIX_FD type is not supported by Tmds.DBus.
public struct UnixFd
{}
} | // Copyright 2016 Tom Deseyn <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
namespace Tmds.DBus
{
public struct UnixFd
{
public UnixFd(uint value)
{
Value = value;
}
public uint Value { get; set; }
}
} | mit | C# |
cad47368acf5d254629b96ec89e4b21fc85bd236 | Bump to 1.5 | JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm,i3at/ArchiSteamFarm,KlappPc/ArchiSteamFarm,KlappPc/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,JustArchi/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,i3at/ArchiSteamFarm | ArchiSteamFarm/Properties/AssemblyInfo.cs | ArchiSteamFarm/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("ArchiSteamFarm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArchiSteamFarm")]
[assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 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("35af7887-08b9-40e8-a5ea-797d8b60b30c")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.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("ArchiSteamFarm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArchiSteamFarm")]
[assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 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("35af7887-08b9-40e8-a5ea-797d8b60b30c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.1.0")]
[assembly: AssemblyFileVersion("1.4.1.0")]
| apache-2.0 | C# |
2550541d311c418bc3a635ccf1c223d29f21809c | Make vision and locomotion required on humanoids | mysticfall/Alensia | Assets/Alensia/Core/Character/Humanoid.cs | Assets/Alensia/Core/Character/Humanoid.cs | using Alensia.Core.Locomotion;
using Alensia.Core.Sensor;
using UnityEngine;
using UnityEngine.Assertions;
using Zenject;
namespace Alensia.Core.Character
{
public class Humanoid : Character<IBinocularVision, ILeggedLocomotion>, IHumanoid
{
public override Transform Head { get; }
public override IBinocularVision Vision { get; }
public override ILeggedLocomotion Locomotion { get; }
public Humanoid(
[InjectOptional] Race race,
[InjectOptional] Sex sex,
IBinocularVision vision,
ILeggedLocomotion locomotion,
Animator animator,
Transform transform) : base(race, sex, animator, transform)
{
Assert.IsNotNull(vision, "vision != null");
Assert.IsNotNull(locomotion, "locomotion != null");
Head = GetBodyPart(HumanBodyBones.Head);
Vision = vision;
Locomotion = locomotion;
}
public Transform GetBodyPart(HumanBodyBones bone) => Animator.GetBoneTransform(bone);
}
} | using Alensia.Core.Locomotion;
using Alensia.Core.Sensor;
using UnityEngine;
using UnityEngine.Assertions;
using Zenject;
namespace Alensia.Core.Character
{
public class Humanoid : Character<IBinocularVision, ILeggedLocomotion>, IHumanoid
{
public override Transform Head { get; }
public override IBinocularVision Vision { get; }
public override ILeggedLocomotion Locomotion { get; }
public Humanoid(
[InjectOptional] Race race,
[InjectOptional] Sex sex,
[InjectOptional] IBinocularVision vision,
[InjectOptional] ILeggedLocomotion locomotion,
Animator animator,
Transform transform) : base(race, sex, animator, transform)
{
Assert.IsNotNull(vision, "vision != null");
Assert.IsNotNull(locomotion, "locomotion != null");
Head = GetBodyPart(HumanBodyBones.Head);
Vision = vision;
Locomotion = locomotion;
}
public Transform GetBodyPart(HumanBodyBones bone) => Animator.GetBoneTransform(bone);
}
} | apache-2.0 | C# |
8361d40397fbc65e36e0163b47098391b514eea1 | Update version for package publish. | digibaraka/BotBuilder,yakumo/BotBuilder,jockorob/BotBuilder,jockorob/BotBuilder,Clairety/ConnectMe,msft-shahins/BotBuilder,jockorob/BotBuilder,Clairety/ConnectMe,stevengum97/BotBuilder,Clairety/ConnectMe,mmatkow/BotBuilder,navaei/BotBuilder,navaei/BotBuilder,xiangyan99/BotBuilder,mmatkow/BotBuilder,dr-em/BotBuilder,mmatkow/BotBuilder,xiangyan99/BotBuilder,msft-shahins/BotBuilder,digibaraka/BotBuilder,xiangyan99/BotBuilder,dr-em/BotBuilder,mmatkow/BotBuilder,stevengum97/BotBuilder,stevengum97/BotBuilder,dr-em/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,digibaraka/BotBuilder,dr-em/BotBuilder,xiangyan99/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,navaei/BotBuilder,jockorob/BotBuilder,digibaraka/BotBuilder,yakumo/BotBuilder,navaei/BotBuilder,Clairety/ConnectMe | CSharp/Library/Properties/AssemblyInfo.cs | CSharp/Library/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("Microsoft.Bot.Builder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Bot Builder")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.24")]
[assembly: AssemblyFileVersion("0.9.0.24")]
[assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")]
| 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("Microsoft.Bot.Builder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Bot Builder")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.23")]
[assembly: AssemblyFileVersion("0.9.0.23")]
[assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")]
| mit | C# |
458adf8cdbf5c9ec1e2edef916b05ca769a10f86 | Bump version to 1.1.0 | kidaa/DissDlcToolkit,adriangl/DissDlcToolkit | DissDlcToolkit/Properties/AssemblyInfo.cs | DissDlcToolkit/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("Dissidia Duodecim Final Fantasy DLC Toolkit")]
[assembly: AssemblyDescription("Generate & edit DLCs for Dissidia Duodecim Final Fantasy!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dissidia Duodecim Final Fantasy DLC Toolkit")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("fdf9236d-549f-4b30-b5c4-da9070cd87fc")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("Dissidia Duodecim Final Fantasy DLC Toolkit")]
[assembly: AssemblyDescription("Generate & edit DLCs for Dissidia Duodecim Final Fantasy!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dissidia Duodecim Final Fantasy DLC Toolkit")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible como true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
[assembly: Guid("fdf9236d-549f-4b30-b5c4-da9070cd87fc")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| apache-2.0 | C# |
e9ebc5b389930ab851bf573ee3e7aa7044a0ddcf | Handle Tcl errors | undees/irule,undees/irule | lib/irule.cs | lib/irule.cs | // The code is new, but the idea is from http://wiki.tcl.tk/9563
using System;
using System.Runtime.InteropServices;
namespace Irule
{
public class TclInterp : IDisposable
{
[DllImport("tcl8.4")]
protected static extern IntPtr Tcl_CreateInterp();
[DllImport("tcl8.4")]
protected static extern int Tcl_Init(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern int Tcl_Eval(IntPtr interp, string script);
[DllImport("tcl8.4")]
protected static extern IntPtr Tcl_GetStringResult(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern void Tcl_DeleteInterp(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern void Tcl_Finalize();
protected const int TCL_ERROR = 1;
private IntPtr interp;
private bool disposed;
public TclInterp()
{
interp = Tcl_CreateInterp();
Tcl_Init(interp);
disposed = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing && interp != IntPtr.Zero)
{
Tcl_DeleteInterp(interp);
Tcl_Finalize();
}
interp = IntPtr.Zero;
disposed = true;
}
}
public string Eval(string text)
{
if (disposed)
{
throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter");
}
var status = Tcl_Eval(interp, text);
var raw = Tcl_GetStringResult(interp);
var result = Marshal.PtrToStringAnsi(raw);
if (TCL_ERROR == status)
{
throw new Exception("Tcl interpreter returned an error: " + result);
}
return result;
}
}
}
| // The code is new, but the idea is from http://wiki.tcl.tk/9563
using System;
using System.Runtime.InteropServices;
namespace Irule
{
public class TclInterp : IDisposable
{
[DllImport("tcl8.4")]
protected static extern IntPtr Tcl_CreateInterp();
[DllImport("tcl8.4")]
protected static extern int Tcl_Init(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern int Tcl_Eval(IntPtr interp, string script);
[DllImport("tcl8.4")]
protected static extern IntPtr Tcl_GetStringResult(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern void Tcl_DeleteInterp(IntPtr interp);
[DllImport("tcl8.4")]
protected static extern void Tcl_Finalize();
private IntPtr interp;
private bool disposed;
public TclInterp()
{
interp = Tcl_CreateInterp();
Tcl_Init(interp);
disposed = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing && interp != IntPtr.Zero)
{
Tcl_DeleteInterp(interp);
Tcl_Finalize();
}
interp = IntPtr.Zero;
disposed = true;
}
}
public string Eval(string text)
{
if (disposed)
{
throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter");
}
Tcl_Eval(interp, text);
var result = Tcl_GetStringResult(interp);
return Marshal.PtrToStringAnsi(result);
}
}
}
| mit | C# |
f2138905be445b06c06f335ac1c145ea120a76d5 | Add code task | roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon | R7.Epsilon/Components/EpsilonUrlHelper.cs | R7.Epsilon/Components/EpsilonUrlHelper.cs | //
// EpsilonUrlHelper.cs
//
// Author:
// Roman M. Yagodin <[email protected]>
//
// Copyright (c) 2017 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Web;
namespace R7.Epsilon.Components
{
public static class EpsilonUrlHelper
{
// TODO: Move to the base library
/// <summary>
/// Checks if browser is InternetExplorer
/// </summary>
/// <returns><c>true</c>, if browser is InternetExplorer, <c>false</c> otherwise.</returns>
/// <param name="request">Request.</param>
public static bool IsIeBrowser (HttpRequest request)
{
var browserName = request.Browser.Browser.ToUpperInvariant ();
if (browserName.StartsWith ("IE", StringComparison.Ordinal)
|| browserName.Contains ("MSIE")
|| browserName == "INTERNETEXPLORER") {
return true;
}
return false;
}
/// <summary>
/// Checks if browser is Edge
/// </summary>
/// <returns><c>true</c>, if browser is Edge, <c>false</c> otherwise.</returns>
/// <param name="request">Request.</param>
public static bool IsEdgeBrowser (HttpRequest request)
{
return request.UserAgent.Contains ("Edge");
}
}
}
| //
// EpsilonUrlHelper.cs
//
// Author:
// Roman M. Yagodin <[email protected]>
//
// Copyright (c) 2017 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Web;
namespace R7.Epsilon.Components
{
public static class EpsilonUrlHelper
{
/// <summary>
/// Checks if browser is InternetExplorer
/// </summary>
/// <returns><c>true</c>, if browser is InternetExplorer, <c>false</c> otherwise.</returns>
/// <param name="request">Request.</param>
public static bool IsIeBrowser (HttpRequest request)
{
var browserName = request.Browser.Browser.ToUpperInvariant ();
if (browserName.StartsWith ("IE", StringComparison.Ordinal)
|| browserName.Contains ("MSIE")
|| browserName == "INTERNETEXPLORER") {
return true;
}
return false;
}
/// <summary>
/// Checks if browser is Edge
/// </summary>
/// <returns><c>true</c>, if browser is Edge, <c>false</c> otherwise.</returns>
/// <param name="request">Request.</param>
public static bool IsEdgeBrowser (HttpRequest request)
{
return request.UserAgent.Contains ("Edge");
}
}
}
| agpl-3.0 | C# |
e1d206a05b1ee74688bfe8d4ec1dc78add4d7b97 | Use one based numbering for Material label | unlimitedbacon/MatterControl,tellingmachine/MatterControl,MatterHackers/MatterControl,larsbrubaker/MatterControl,rytz/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,MatterHackers/MatterControl,MatterHackers/MatterControl,jlewin/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,tellingmachine/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,rytz/MatterControl,rytz/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl | SlicerConfiguration/SettingsControlBar.cs | SlicerConfiguration/SettingsControlBar.cs | /*
Copyright (c) 2014, Kevin Pope
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using System;
using System.Collections.Generic;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class SettingsControlBar : FlowLayoutWidget
{
public SettingsControlBar()
{
this.HAnchor = HAnchor.ParentLeftRight;
int numberOfHeatedExtruders = ActiveSliceSettings.Instance.ExtruderCount();
this.AddChild(new PresetSelectorWidget("Quality".Localize(), RGBA_Bytes.Yellow, "quality", 0));
this.AddChild(new GuiWidget(8, 0));
if (numberOfHeatedExtruders > 1)
{
List<RGBA_Bytes> colorList = new List<RGBA_Bytes>() { RGBA_Bytes.Orange, RGBA_Bytes.Violet, RGBA_Bytes.YellowGreen };
for (int i = 0; i < numberOfHeatedExtruders; i++)
{
if (i > 0)
{
this.AddChild(new GuiWidget(8, 0));
}
int colorIndex = i % colorList.Count;
RGBA_Bytes color = colorList[colorIndex];
this.AddChild(new PresetSelectorWidget(string.Format("{0} {1}", "Material".Localize(), i + 1), color, "material", i));
}
}
else
{
this.AddChild(new PresetSelectorWidget("Material".Localize(), RGBA_Bytes.Orange, "material", 0));
}
this.Height = 60 * TextWidget.GlobalPointSizeScaleRatio;
}
}
}
| /*
Copyright (c) 2014, Kevin Pope
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using System;
using System.Collections.Generic;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class SettingsControlBar : FlowLayoutWidget
{
public SettingsControlBar()
{
this.HAnchor = HAnchor.ParentLeftRight;
int numberOfHeatedExtruders = ActiveSliceSettings.Instance.ExtruderCount();
this.AddChild(new PresetSelectorWidget("Quality".Localize(), RGBA_Bytes.Yellow, "quality", 0));
this.AddChild(new GuiWidget(8, 0));
if (numberOfHeatedExtruders > 1)
{
List<RGBA_Bytes> colorList = new List<RGBA_Bytes>() { RGBA_Bytes.Orange, RGBA_Bytes.Violet, RGBA_Bytes.YellowGreen };
for (int i = 0; i < numberOfHeatedExtruders; i++)
{
if (i > 0)
{
this.AddChild(new GuiWidget(8, 0));
}
int colorIndex = i % colorList.Count;
RGBA_Bytes color = colorList[colorIndex];
this.AddChild(new PresetSelectorWidget(string.Format("{0} {1}", "Material".Localize(), i), color, "material", i));
}
}
else
{
this.AddChild(new PresetSelectorWidget("Material".Localize(), RGBA_Bytes.Orange, "material", 0));
}
this.Height = 60 * TextWidget.GlobalPointSizeScaleRatio;
}
}
}
| bsd-2-clause | C# |
fa8559dee7ff915b2caf3b1b7ced788cb18b4a8f | Change foreign key annotation. | dimitardanailov/TwitterBackupBackendAndAngularjs,dimitardanailov/TwitterBackupBackendAndAngularjs,dimitardanailov/TwitterBackupBackendAndAngularjs | TwitterWebApplicationEntities/Follower.cs | TwitterWebApplicationEntities/Follower.cs | using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TwitterWebApplicationEntities
{
public class Follower : BaseModel
{
[Key]
public int FollowerID { get; set; }
// Foreign Key
[Required]
[MaxLength(128, ErrorMessage = "Maximum length is {0} characters.")]
public string FollowedUserID { get; set; }
[Required]
[MaxLength(128, ErrorMessage = "Maximum length is {0} characters.")]
public string FollowerUserID { get; set; }
[ForeignKey("FollowedUserID")]
public virtual ApplicationUser FollowedUser { get; set; }
[ForeignKey("FollowerUserID")]
public virtual ApplicationUser FollowerUser { get; set; }
}
}
| using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TwitterWebApplicationEntities
{
public class Follower : BaseModel
{
[Key]
public int FollowerID { get; set; }
// Foreign Key
[Required]
[MaxLength(128, ErrorMessage = "Maximum length is {0} characters.")]
public string FollowedUserID { get; set; }
[Required]
[MaxLength(128, ErrorMessage = "Maximum length is {0} characters.")]
public string FollowerUserID { get; set; }
[ForeignKey("FollowedUserID")]
public virtual ApplicationUser FollowedUser { get; set; }
[ForeignKey("FollowerUser")]
public virtual ApplicationUser FollowerUser { get; set; }
}
}
| mit | C# |
29b4c750a0cd0d49f827380fd0256c9b83177b1c | set version to 0.1 | dimaaan/pgEdit | PgEdit/Properties/AssemblyInfo.cs | PgEdit/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("PgEdit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PgEdit")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8f5629c9-4c6e-4537-8b0d-3b3908f695d1")]
// 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.*")]
[assembly: AssemblyFileVersion("0.1.*")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PgEdit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PgEdit")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8f5629c9-4c6e-4537-8b0d-3b3908f695d1")]
// 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# |
f84b3369693ff9231ed48431b78d0f657ca9a81c | Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | autofac/Autofac.Web | Properties/VersionAssemblyInfo.cs | Properties/VersionAssemblyInfo.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
| mit | C# |
16fcf5d41a1353dcca8c2c74fd5f41ebcf350b8e | work on admin screens | Jetski5822/NGM.Forum | Views/Parts.Threads.Post.ListAdmin.cshtml | Views/Parts.Threads.Post.ListAdmin.cshtml | @using Orchard.Core.Contents.ViewModels;
@using Orchard.Utility.Extensions;
@if (Model.ContentItems.Items.Count > 0) {
using (Html.BeginFormAntiForgeryPost(Url.Action("List", "Admin", new { area = "Contents", id = "" }))) {
<fieldset class="bulk-actions">
<label for="publishActions">@T("Actions:")</label>
<select id="publishActions" name="Options.BulkAction">
@Html.SelectOption(ContentsBulkAction.None, ContentsBulkAction.None, T("Choose action...").ToString())
@Html.SelectOption(ContentsBulkAction.None, ContentsBulkAction.PublishNow, T("Publish Now").ToString())
@Html.SelectOption(ContentsBulkAction.None, ContentsBulkAction.Unpublish, T("Unpublish").ToString())
@Html.SelectOption(ContentsBulkAction.None, ContentsBulkAction.Remove, T("Delete").ToString())
</select>
@Html.Hidden("returnUrl", ViewContext.RequestContext.HttpContext.Request.ToUrlString())
<button type="submit" name="submit.BulkEdit" value="yes">@T("Apply")</button>
</fieldset>
<fieldset class="contentItems bulk-items">
@Display(Model.ContentItems)
</fieldset>
}
} else {
<div class="info message">@T("There are no posts for this thread.")</div>
} | @using Orchard.Core.Contents.ViewModels;
@using Orchard.Utility.Extensions;
@if (Model.ContentItems.Items.Count > 0) {
<fieldset class="contentItems bulk-items">
@Display(Model.ContentItems)
</fieldset>
} else {
<div class="info message">@T("There are no posts for this thread.")</div>
} | bsd-3-clause | C# |
efa2c1082d42831cfbd93958faba51eb37b1e09b | optimize assembly qualified name handling | rogeralsing/Wire,Horusiath/Hyperion,cpx/Wire,rogeralsing/Wire,akkadotnet/Hyperion,AsynkronIT/Wire,akkadotnet/Hyperion,Horusiath/Hyperion | Wire/ValueSerializers/ObjectSerializer.cs | Wire/ValueSerializers/ObjectSerializer.cs | using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
namespace Wire.ValueSerializers
{
public class ObjectSerializer : ValueSerializer
{
public Type Type { get; }
public Action<Stream, object, SerializerSession> Writer { get; }
public Func<Stream, SerializerSession, object> Reader { get; }
public byte[] AssemblyQualifiedName { get; }
public ObjectSerializer(Type type, Action<Stream, object, SerializerSession> writer,
Func<Stream, SerializerSession, object> reader)
{
Type = type;
Writer = writer;
Reader = reader;
AssemblyQualifiedName = Encoding.UTF8.GetBytes(type.AssemblyQualifiedName);
}
public override void WriteManifest(Stream stream, Type type, SerializerSession session)
{
stream.WriteByte(255); //write manifest identifier,
ByteArraySerializer.Instance.WriteValue(stream, AssemblyQualifiedName, session); //write the encoded name of the type
}
public override void WriteValue(Stream stream, object value, SerializerSession session)
{
Writer(stream, value, session);
}
public override object ReadValue(Stream stream, SerializerSession session)
{
return Reader(stream, session);
}
public override Type GetElementType()
{
return Type;
}
}
} | using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
namespace Wire.ValueSerializers
{
public class ObjectSerializer : ValueSerializer
{
private static readonly ConcurrentDictionary<Type, byte[]> AssemblyQualifiedNames =
new ConcurrentDictionary<Type, byte[]>();
public Type Type { get; }
public Action<Stream, object, SerializerSession> Writer { get; }
public Func<Stream, SerializerSession, object> Reader { get; }
public ObjectSerializer(Type type, Action<Stream, object, SerializerSession> writer,
Func<Stream, SerializerSession, object> reader)
{
Type = type;
Writer = writer;
Reader = reader;
}
public override void WriteManifest(Stream stream, Type type, SerializerSession session)
{
stream.WriteByte(255); //write manifest identifier,
var bytes = AssemblyQualifiedNames.GetOrAdd(type, t =>
{
var name = t.AssemblyQualifiedName;
var b = Encoding.UTF8.GetBytes(name);
return b;
});
ByteArraySerializer.Instance.WriteValue(stream, bytes, session); //write the encoded name of the type
}
public override void WriteValue(Stream stream, object value, SerializerSession session)
{
Writer(stream, value, session);
}
public override object ReadValue(Stream stream, SerializerSession session)
{
return Reader(stream, session);
}
public override Type GetElementType()
{
return Type;
}
}
} | apache-2.0 | C# |
8b6e4693a0a007b0b38a7a93f034e86c1445cfd8 | Add toggle play by keyboard input | setchi/NotesEditor,setchi/NoteEditor | Assets/Scripts/UI/TogglePlayPresenter.cs | Assets/Scripts/UI/TogglePlayPresenter.cs | using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UI;
public class TogglePlayPresenter : MonoBehaviour
{
[SerializeField]
Button togglePlayButton;
[SerializeField]
Sprite iconPlay;
[SerializeField]
Sprite iconPause;
NotesEditorModel model;
void Awake()
{
model = NotesEditorModel.Instance;
model.OnLoadedMusicObservable.First().Subscribe(_ => Init());
}
void Init()
{
this.UpdateAsObservable()
.Where(_ => Input.GetKeyDown(KeyCode.Space))
.Merge(togglePlayButton.OnClickAsObservable())
.Subscribe(_ => model.IsPlaying.Value = !model.IsPlaying.Value);
model.IsPlaying.DistinctUntilChanged().Subscribe(playing =>
{
var playButtonImage = togglePlayButton.GetComponent<Image>();
if (playing)
{
model.Audio.Play();
playButtonImage.sprite = iconPause;
}
else
{
model.Audio.Pause();
playButtonImage.sprite = iconPlay;
}
});
}
}
| using UniRx;
using UnityEngine;
using UnityEngine.UI;
public class TogglePlayPresenter : MonoBehaviour
{
[SerializeField]
Button togglePlayButton;
[SerializeField]
Sprite iconPlay;
[SerializeField]
Sprite iconPause;
NotesEditorModel model;
void Awake()
{
model = NotesEditorModel.Instance;
model.OnLoadedMusicObservable.First().Subscribe(_ => Init());
}
void Init()
{
togglePlayButton.OnClickAsObservable()
.Subscribe(_ => model.IsPlaying.Value = !model.IsPlaying.Value);
model.IsPlaying.DistinctUntilChanged().Subscribe(playing =>
{
var playButtonImage = togglePlayButton.GetComponent<Image>();
if (playing)
{
model.Audio.Play();
playButtonImage.sprite = iconPause;
}
else
{
model.Audio.Pause();
playButtonImage.sprite = iconPlay;
}
});
}
}
| mit | C# |
8eb7717ac80f8bcff3a2a6a87cd38584dccdca0e | Remove unsafe block | rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary | CSGL.Vulkan/Vulkan/ImageView.cs | CSGL.Vulkan/Vulkan/ImageView.cs | using System;
namespace CSGL.Vulkan {
public class ImageViewCreateInfo {
public Image image;
public VkImageViewType viewType;
public VkFormat format;
public VkComponentMapping components;
public VkImageSubresourceRange subresourceRange;
public ImageViewCreateInfo(Image image) {
this.image = image;
}
}
public class ImageView : IDisposable, INative<VkImageView> {
VkImageView imageView;
bool disposed = false;
public VkImageView Native {
get {
return imageView;
}
}
public Device Device { get; private set; }
public ImageView(Device device, ImageViewCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
if (info.image == null) throw new ArgumentNullException(nameof(info.image));
Device = device;
CreateImageView(info);
}
void CreateImageView(ImageViewCreateInfo mInfo) {
VkImageViewCreateInfo info = new VkImageViewCreateInfo();
info.sType = VkStructureType.ImageViewCreateInfo;
info.image = mInfo.image.Native;
info.viewType = mInfo.viewType;
info.format = mInfo.format;
info.components = mInfo.components;
info.subresourceRange = mInfo.subresourceRange;
var result = Device.Commands.createImageView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out imageView);
if (result != VkResult.Success) throw new ImageViewException(string.Format("Error creating image view: {0}", result));
}
public void Dispose() {
if (disposed) return;
Device.Commands.destroyImageView(Device.Native, imageView, Device.Instance.AllocationCallbacks);
disposed = true;
}
}
public class ImageViewException : Exception {
public ImageViewException(string message) : base(message) { }
}
}
| using System;
namespace CSGL.Vulkan {
public class ImageViewCreateInfo {
public Image image;
public VkImageViewType viewType;
public VkFormat format;
public VkComponentMapping components;
public VkImageSubresourceRange subresourceRange;
public ImageViewCreateInfo(Image image) {
this.image = image;
}
}
public class ImageView : IDisposable, INative<VkImageView> {
VkImageView imageView;
bool disposed = false;
public VkImageView Native {
get {
return imageView;
}
}
public Device Device { get; private set; }
public ImageView(Device device, ImageViewCreateInfo info) {
if (device == null) throw new ArgumentNullException(nameof(device));
if (info == null) throw new ArgumentNullException(nameof(info));
if (info.image == null) throw new ArgumentNullException(nameof(info.image));
Device = device;
CreateImageView(info);
}
void CreateImageView(ImageViewCreateInfo mInfo) {
VkImageViewCreateInfo info = new VkImageViewCreateInfo();
info.sType = VkStructureType.ImageViewCreateInfo;
info.image = mInfo.image.Native;
info.viewType = mInfo.viewType;
info.format = mInfo.format;
info.components = mInfo.components;
info.subresourceRange = mInfo.subresourceRange;
var result = Device.Commands.createImageView(Device.Native, ref info, Device.Instance.AllocationCallbacks, out imageView);
if (result != VkResult.Success) throw new ImageViewException(string.Format("Error creating image view: {0}", result));
}
public void Dispose() {
if (disposed) return;
unsafe
{
Device.Commands.destroyImageView(Device.Native, imageView, Device.Instance.AllocationCallbacks);
}
disposed = true;
}
}
public class ImageViewException : Exception {
public ImageViewException(string message) : base(message) { }
}
}
| mit | C# |
a32874236778eedd2c0556aad1d0cd0529900828 | Implement Dispose pattern | vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary | CSGL.Vulkan/Vulkan/Semaphore.cs | CSGL.Vulkan/Vulkan/Semaphore.cs | using System;
namespace CSGL.Vulkan {
public class Semaphore : IDisposable, INative<VkSemaphore> {
VkSemaphore semaphore;
bool disposed = false;
public Device Device { get; private set; }
public VkSemaphore Native {
get {
return semaphore;
}
}
public Semaphore(Device device) {
if (device == null) throw new ArgumentNullException(nameof(device));
Device = device;
CreateSemaphore();
}
void CreateSemaphore() {
VkSemaphoreCreateInfo info = new VkSemaphoreCreateInfo();
info.sType = VkStructureType.SemaphoreCreateInfo;
var result = Device.Commands.createSemaphore(Device.Native, ref info, Device.Instance.AllocationCallbacks, out semaphore);
if (result != VkResult.Success) throw new SemaphoreException(string.Format("Error creating semaphore: {0}", result));
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (disposed) return;
Device.Commands.destroySemaphore(Device.Native, semaphore, Device.Instance.AllocationCallbacks);
disposed = true;
}
~Semaphore() {
Dispose(false);
}
}
public class SemaphoreException : Exception {
public SemaphoreException(string message) : base(message) { }
}
}
| using System;
namespace CSGL.Vulkan {
public class Semaphore : IDisposable, INative<VkSemaphore> {
VkSemaphore semaphore;
bool disposed = false;
public Device Device { get; private set; }
public VkSemaphore Native {
get {
return semaphore;
}
}
public Semaphore(Device device) {
if (device == null) throw new ArgumentNullException(nameof(device));
Device = device;
CreateSemaphore();
}
void CreateSemaphore() {
VkSemaphoreCreateInfo info = new VkSemaphoreCreateInfo();
info.sType = VkStructureType.SemaphoreCreateInfo;
var result = Device.Commands.createSemaphore(Device.Native, ref info, Device.Instance.AllocationCallbacks, out semaphore);
if (result != VkResult.Success) throw new SemaphoreException(string.Format("Error creating semaphore: {0}", result));
}
public void Dispose() {
if (disposed) return;
Device.Commands.destroySemaphore(Device.Native, semaphore, Device.Instance.AllocationCallbacks);
disposed = true;
}
}
public class SemaphoreException : Exception {
public SemaphoreException(string message) : base(message) { }
}
}
| mit | C# |
a49ba744aa1a02d4e4987cecdbade7c12f8f7e9b | Reduce Revision check calls via interface | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Http.Features/FeatureReferences.cs | src/Microsoft.AspNetCore.Http.Features/FeatureReferences.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNetCore.Http.Features
{
public struct FeatureReferences<TCache>
{
public FeatureReferences(IFeatureCollection collection)
{
Collection = collection;
Cache = default(TCache);
Revision = collection.Revision;
}
public IFeatureCollection Collection { get; private set; }
public int Revision { get; private set; }
// cache is a public field because the code calling Fetch must
// be able to pass ref values that "dot through" the TCache struct memory,
// if it was a Property then that getter would return a copy of the memory
// preventing the use of "ref"
public TCache Cache;
public TFeature Fetch<TFeature, TState>(
ref TFeature cached,
TState state,
Func<TState, TFeature> factory) where TFeature : class
{
var revision = Collection.Revision;
if (Revision == revision)
{
// collection unchanged, use cached
return cached ?? UpdateCached(ref cached, state, factory);
}
// collection changed, clear cache
Cache = default(TCache);
// empty cache is current revision
Revision = revision;
return UpdateCached(ref cached, state, factory);
}
private TFeature UpdateCached<TFeature, TState>(ref TFeature cached, TState state, Func<TState, TFeature> factory) where TFeature : class
{
cached = Collection.Get<TFeature>();
if (cached == null)
{
// create if item not in collection
cached = factory(state);
Collection.Set(cached);
// Revision changed by .Set, update revision
Revision = Collection.Revision;
}
return cached;
}
public TFeature Fetch<TFeature>(ref TFeature cached, Func<IFeatureCollection, TFeature> factory)
where TFeature : class => Fetch(ref cached, Collection, factory);
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNetCore.Http.Features
{
public struct FeatureReferences<TCache>
{
public FeatureReferences(IFeatureCollection collection)
{
Collection = collection;
Cache = default(TCache);
Revision = collection.Revision;
}
public IFeatureCollection Collection { get; private set; }
public int Revision { get; private set; }
// cache is a public field because the code calling Fetch must
// be able to pass ref values that "dot through" the TCache struct memory,
// if it was a Property then that getter would return a copy of the memory
// preventing the use of "ref"
public TCache Cache;
public TFeature Fetch<TFeature, TState>(
ref TFeature cached,
TState state,
Func<TState, TFeature> factory)
{
var cleared = false;
if (Revision != Collection.Revision)
{
cleared = true;
Cache = default(TCache);
Revision = Collection.Revision;
}
var feature = cached;
if (feature == null || cleared)
{
feature = Collection.Get<TFeature>();
if (feature == null)
{
feature = factory(state);
Collection.Set(feature);
Revision = Collection.Revision;
}
cached = feature;
}
return feature;
}
public TFeature Fetch<TFeature>(ref TFeature cached, Func<IFeatureCollection, TFeature> factory) =>
Fetch(ref cached, Collection, factory);
}
} | apache-2.0 | C# |
fa59b894677ad8a733c4fe5da7c9e2e413b65789 | Include 'error#context' as the context in the MVC test | TheNeatCompany/RollbarSharp,mteinum/RollbarSharp2,TheNeatCompany/RollbarSharp,jmblab/RollbarSharp,mroach/RollbarSharp,mteinum/RollbarSharp2 | src/RollbarSharp.Mvc4Test/App_Start/FilterConfig.cs | src/RollbarSharp.Mvc4Test/App_Start/FilterConfig.cs | using System.IO;
using System.Web.Mvc;
namespace RollbarSharp.Mvc4Test
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new RollbarExceptionFilter());
filters.Add(new HandleErrorAttribute());
}
}
public class RollbarExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
return;
(new RollbarClient()).SendException(filterContext.Exception, modelAction: m => m.Context = "error#context");
}
}
} | using System.IO;
using System.Web.Mvc;
namespace RollbarSharp.Mvc4Test
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new RollbarExceptionFilter());
filters.Add(new HandleErrorAttribute());
}
}
public class RollbarExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
return;
(new RollbarClient()).SendException(filterContext.Exception);
}
}
} | apache-2.0 | C# |
1a83df7d6dbbc6e390c81b4fb0d0655f2d9e11d2 | Remove obsolete TS method | mavasani/roslyn,mavasani/roslyn,dotnet/roslyn,dotnet/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn | src/VisualStudio/Core/Def/ProjectSystem/DocumentProvider.cs | src/VisualStudio/Core/Def/ProjectSystem/DocumentProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal sealed class DocumentProvider
{
internal class ShimDocument : IVisualStudioHostDocument
{
public ShimDocument(AbstractProject hostProject, DocumentId id, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
Project = hostProject;
Id = id ?? DocumentId.CreateNewId(hostProject.Id, filePath);
FilePath = filePath;
SourceCodeKind = sourceCodeKind;
}
public AbstractProject Project { get; }
public DocumentId Id { get; }
public string FilePath { get; }
public SourceCodeKind SourceCodeKind { get; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal sealed class DocumentProvider
{
[Obsolete("This overload is a compatibility shim for TypeScript; please do not use it.")]
public IVisualStudioHostDocument TryGetDocumentForFile(
AbstractProject hostProject,
string filePath,
SourceCodeKind sourceCodeKind,
Func<ITextBuffer, bool> canUseTextBuffer,
Func<uint, IReadOnlyList<string>> getFolderNames,
EventHandler updatedOnDiskHandler = null,
EventHandler<bool> openedHandler = null,
EventHandler<bool> closingHandler = null)
{
return new ShimDocument(hostProject, DocumentId.CreateNewId(hostProject.Id), filePath, sourceCodeKind);
}
internal class ShimDocument : IVisualStudioHostDocument
{
public ShimDocument(AbstractProject hostProject, DocumentId id, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
{
Project = hostProject;
Id = id ?? DocumentId.CreateNewId(hostProject.Id, filePath);
FilePath = filePath;
SourceCodeKind = sourceCodeKind;
}
public AbstractProject Project { get; }
public DocumentId Id { get; }
public string FilePath { get; }
public SourceCodeKind SourceCodeKind { get; }
}
}
}
| mit | C# |
ef82cc68d8179cbcf4f30223cf12464b2ac179eb | fix selezione preaccoppiato | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Models/Classi/Composizione/PreAccoppiato.cs | src/backend/SO115App.Models/Classi/Composizione/PreAccoppiato.cs | //-----------------------------------------------------------------------
// <copyright file="PreAccoppiati.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Generic;
namespace SO115App.API.Models.Classi.Composizione
{
public class PreAccoppiato
{
public string Id => CodiceMezzo;
public string CodiceMezzo { get; set; }
public string GenereMezzo { get; set; }
public string StatoMezzo { get; set; }
public string DescrizioneMezzo { get; set; }
public string Distaccamento { get; set; }
public string Km { get; set; }
public string TempoPercorrenza { get; set; }
public List<Squadra> Squadre { get; set; }
}
/// <summary>
/// Squadra del preaccoppiato
/// </summary>
public class Squadra
{
public Squadra(string codice, string nome, string stato) =>
(Codice, Nome, Stato) = (codice, nome, stato);
public Squadra() { }
public string Codice { get; set; }
public string Stato { get; set; }
public string Nome { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="PreAccoppiati.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Generic;
namespace SO115App.API.Models.Classi.Composizione
{
public class PreAccoppiato
{
public string CodiceMezzo { get; set; }
public string GenereMezzo { get; set; }
public string StatoMezzo { get; set; }
public string DescrizioneMezzo { get; set; }
public string Distaccamento { get; set; }
public string Km { get; set; }
public string TempoPercorrenza { get; set; }
public List<Squadra> Squadre { get; set; }
}
/// <summary>
/// Squadra del preaccoppiato
/// </summary>
public class Squadra
{
public Squadra(string codice, string nome, string stato) =>
(Codice, Nome, Stato) = (codice, nome, stato);
public Squadra() { }
public string Codice { get; set; }
public string Stato { get; set; }
public string Nome { get; set; }
}
}
| agpl-3.0 | C# |
a51bc056dba89f72361522cc1aa608838ddec1e1 | Fix incorrect [AssemblyTitle] | martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode | 2015/day-04/AdventOfCode.Day4/Properties/AssemblyInfo.cs | 2015/day-04/AdventOfCode.Day4/Properties/AssemblyInfo.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="https://github.com/martincostello/adventofcode">
// Martin Costello (c) 2015
// </copyright>
// <license>
// See license.txt in the project root for license information.
// </license>
// <summary>
// AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AdventOfCode.Day4")]
[assembly: AssemblyDescription("Solution to day 4 of http://adventofcode.com/day/4.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Martin Costello")]
[assembly: AssemblyProduct("AdventOfCode.Day4")]
[assembly: AssemblyCopyright("Copyright © Martin Costello 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("40df62d6-6255-4da3-99c5-2ceab849387b")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="https://github.com/martincostello/adventofcode">
// Martin Costello (c) 2015
// </copyright>
// <license>
// See license.txt in the project root for license information.
// </license>
// <summary>
// AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("AdventOfCode.Day3")]
[assembly: AssemblyDescription("Solution to day 4 of http://adventofcode.com/day/4.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Martin Costello")]
[assembly: AssemblyProduct("AdventOfCode.Day4")]
[assembly: AssemblyCopyright("Copyright © Martin Costello 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("40df62d6-6255-4da3-99c5-2ceab849387b")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
b1d6a340c75daae2595b8692f4030d247cca0c1e | Fix import order | MHeasell/Mappy,MHeasell/Mappy | Mappy/IO/FeatureRenderLoader.cs | Mappy/IO/FeatureRenderLoader.cs | namespace Mappy.IO
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Mappy.Data;
using Mappy.Util;
using TAUtil._3do;
using TAUtil.Hpi;
public class FeatureRenderLoader : AbstractHpiLoader<KeyValuePair<string, OffsetBitmap>>
{
private readonly IDictionary<string, IList<FeatureRecord>> objectMap;
public FeatureRenderLoader(IDictionary<string, IList<FeatureRecord>> objectMap)
{
this.objectMap = objectMap;
}
protected override IEnumerable<string> EnumerateFiles(HpiReader r)
{
return r.GetFilesRecursive("objects3d")
.Select(x => x.Name)
.Where(x =>
x.EndsWith(".3do", StringComparison.OrdinalIgnoreCase)
&& this.objectMap.ContainsKey(HpiPath.GetFileNameWithoutExtension(x)));
}
protected override void LoadFile(HpiReader r, string file)
{
Debug.Assert(file != null, "Null filename");
var records = this.objectMap[HpiPath.GetFileNameWithoutExtension(file)];
using (var b = r.ReadFile(file))
{
var adapter = new ModelEdgeReaderAdapter();
var reader = new ModelReader(b, adapter);
reader.Read();
var wire = Util.RenderWireframe(adapter.Edges);
foreach (var record in records)
{
this.Records.Add(new KeyValuePair<string, OffsetBitmap>(record.Name, wire));
}
}
}
}
}
| namespace Mappy.IO
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Mappy.Data;
using Mappy.Util;
using TAUtil.Hpi;
using TAUtil._3do;
public class FeatureRenderLoader : AbstractHpiLoader<KeyValuePair<string, OffsetBitmap>>
{
private readonly IDictionary<string, IList<FeatureRecord>> objectMap;
public FeatureRenderLoader(IDictionary<string, IList<FeatureRecord>> objectMap)
{
this.objectMap = objectMap;
}
protected override IEnumerable<string> EnumerateFiles(HpiReader r)
{
return r.GetFilesRecursive("objects3d")
.Select(x => x.Name)
.Where(x =>
x.EndsWith(".3do", StringComparison.OrdinalIgnoreCase)
&& this.objectMap.ContainsKey(HpiPath.GetFileNameWithoutExtension(x)));
}
protected override void LoadFile(HpiReader r, string file)
{
Debug.Assert(file != null, "Null filename");
var records = this.objectMap[HpiPath.GetFileNameWithoutExtension(file)];
using (var b = r.ReadFile(file))
{
var adapter = new ModelEdgeReaderAdapter();
var reader = new ModelReader(b, adapter);
reader.Read();
var wire = Util.RenderWireframe(adapter.Edges);
foreach (var record in records)
{
this.Records.Add(new KeyValuePair<string, OffsetBitmap>(record.Name, wire));
}
}
}
}
}
| mit | C# |
1f92334c683e31eee9ab76a2ef6ebb500c858417 | add AsString extension | RobinHerbots/NCDO,RobinHerbots/NCDO | src/NCDO/Extensions/JsonValueExtensions.cs | src/NCDO/Extensions/JsonValueExtensions.cs | using System.Json;
namespace NCDO.Extensions
{
public static class JsonValueExtensions
{
public static string AsString(this JsonValue jsonValue)
{
return jsonValue is JsonPrimitive jsonPrimitiveValue && jsonPrimitiveValue.JsonType == JsonType.String
? (string) jsonValue
: jsonValue.ToString();
}
public static JsonValue Get(this JsonValue jsonValue, string key)
{
return jsonValue.ContainsKey(key) ? jsonValue[key] : new JsonPrimitive((string)null);
}
internal static void Set(this JsonValue jsonValue, string key, JsonValue value)
{
jsonValue[key] = value;
}
public static void ThrowOnErrorResponse(this JsonValue jsonValue)
{
if (jsonValue.ContainsKey("error")) //pas error
{
throw new CDOException(jsonValue.Get("error"), jsonValue.Get("error_description")) { Scope = jsonValue.Get("scope") };
}
if (jsonValue.ContainsKey("_errors")) //progress error
{
string code = "";
string message = jsonValue.Get("_retVal");
var errors = (JsonArray)jsonValue.Get("_errors");
foreach (var error in errors)
{
code = error.Get("_errorNum").ToString();
if (string.IsNullOrEmpty(message)) message = error.Get("_errorMsg");
break;
}
throw new CDOException(code, message);
}
}
}
} | using System.Json;
namespace NCDO.Extensions
{
public static class JsonValueExtensions
{
public static JsonValue Get(this JsonValue jsonValue, string key)
{
return jsonValue.ContainsKey(key) ? jsonValue[key] : new JsonPrimitive((string)null);
}
internal static void Set(this JsonValue jsonValue, string key, JsonValue value)
{
jsonValue[key] = value;
}
public static void ThrowOnErrorResponse(this JsonValue jsonValue)
{
if (jsonValue.ContainsKey("error")) //pas error
{
throw new CDOException(jsonValue.Get("error"), jsonValue.Get("error_description")) { Scope = jsonValue.Get("scope") };
}
if (jsonValue.ContainsKey("_errors")) //progress error
{
string code = "";
string message = jsonValue.Get("_retVal");
var errors = (JsonArray)jsonValue.Get("_errors");
foreach (var error in errors)
{
code = error.Get("_errorNum").ToString();
if (string.IsNullOrEmpty(message)) message = error.Get("_errorMsg");
break;
}
throw new CDOException(code, message);
}
}
}
} | mit | C# |
c945265b332b86b9864553edc8e8fb292e22b768 | Fix invalid tree state in case node is removed and inserted again in the different sub-tree | k-t/SharpHaven | MonoHaven.Lib/Utils/TreeNode.cs | MonoHaven.Lib/Utils/TreeNode.cs | using System.Collections.Generic;
using System.Linq;
namespace MonoHaven.Utils
{
public class TreeNode<T> where T : TreeNode<T>
{
private T parent;
private T prev;
private T next;
private T firstChild;
private T lastChild;
public T Parent
{
get { return parent; }
}
public T Next
{
get { return next; }
}
public T Previous
{
get { return prev; }
}
public T FirstChild
{
get { return firstChild; }
}
public T LastChild
{
get { return lastChild; }
}
public IEnumerable<T> Children
{
get
{
for (var child = firstChild; child != null; child = child.next)
yield return child;
}
}
public IEnumerable<T> Descendants
{
get
{
var stack = new Stack<T>(Children);
while (stack.Any())
{
var node = stack.Pop();
yield return node;
foreach (var child in node.Children)
stack.Push(child);
}
}
}
public bool HasChildren
{
get { return firstChild != null; }
}
/// <summary>
/// Adds specified node as a child to this node.
/// </summary>
public T AddChild(T node)
{
node.Remove();
node.parent = (T)this;
if (this.firstChild == null)
this.firstChild = node;
if (this.lastChild != null)
{
node.prev = this.lastChild;
this.lastChild.next = node;
this.lastChild = node;
}
else
this.lastChild = node;
return (T)this;
}
/// <summary>
/// Adds range of children nodes to this node.
/// </summary>
public T AddChildren(IEnumerable<T> children)
{
foreach (var child in children)
AddChild(child);
return (T)this;
}
/// <summary>
/// Adds range of children nodes to this node.
/// </summary>
public T AddChildren(params T[] children)
{
return AddChildren(children.AsEnumerable());
}
/// <summary>
/// Removes this node from the parent node.
/// </summary>
public void Remove()
{
if (parent != null)
{
if (parent.firstChild == this)
parent.firstChild = next;
if (parent.lastChild == this)
parent.lastChild = prev;
}
if (next != null)
next.prev = prev;
if (prev != null)
prev.next = next;
prev = null;
next = null;
parent = null;
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace MonoHaven.Utils
{
public class TreeNode<T> where T : TreeNode<T>
{
private T parent;
private T prev;
private T next;
private T firstChild;
private T lastChild;
public T Parent
{
get { return parent; }
}
public T Next
{
get { return next; }
}
public T Previous
{
get { return prev; }
}
public T FirstChild
{
get { return firstChild; }
}
public T LastChild
{
get { return lastChild; }
}
public IEnumerable<T> Children
{
get
{
for (var child = firstChild; child != null; child = child.next)
yield return child;
}
}
public IEnumerable<T> Descendants
{
get
{
var stack = new Stack<T>(Children);
while (stack.Any())
{
var node = stack.Pop();
yield return node;
foreach (var child in node.Children)
stack.Push(child);
}
}
}
public bool HasChildren
{
get { return firstChild != null; }
}
/// <summary>
/// Adds specified node as a child to this node.
/// </summary>
public T AddChild(T node)
{
node.Remove();
node.parent = (T)this;
if (this.firstChild == null)
this.firstChild = node;
if (this.lastChild != null)
{
node.prev = this.lastChild;
this.lastChild.next = node;
this.lastChild = node;
}
else
this.lastChild = node;
return (T)this;
}
/// <summary>
/// Adds range of children nodes to this node.
/// </summary>
public T AddChildren(IEnumerable<T> children)
{
foreach (var child in children)
AddChild(child);
return (T)this;
}
/// <summary>
/// Adds range of children nodes to this node.
/// </summary>
public T AddChildren(params T[] children)
{
return AddChildren(children.AsEnumerable());
}
/// <summary>
/// Removes this node from the parent node.
/// </summary>
public void Remove()
{
if (parent != null)
{
if (parent.firstChild == this)
parent.firstChild = next;
if (parent.lastChild == this)
parent.lastChild = prev;
}
if (next != null) next.prev = prev;
if (prev != null) prev.next = next;
parent = null;
}
}
}
| mit | C# |
3cc156b0b9cbf85c0d6c956b556dd352f4604f58 | Remove unused `Unavailable` connection state | pusher-community/pusher-websocket-dotnet | PusherClient/ConnectionState.cs | PusherClient/ConnectionState.cs | namespace PusherClient
{
public enum ConnectionState
{
Initialized,
Connecting,
Connected,
Disconnected,
WaitingToReconnect
}
}
| namespace PusherClient
{
public enum ConnectionState
{
Initialized,
Connecting,
Connected,
Unavailable,
Disconnected,
WaitingToReconnect
}
}
| mit | C# |
fc2d2d18a69ebdf31215da00849a82fea1f383fd | Fix Mac build. | l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto | Source/Eto.Platform.Mac/Forms/Actions/MacButtonAction.cs | Source/Eto.Platform.Mac/Forms/Actions/MacButtonAction.cs | using System;
using Eto.Forms;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
namespace Eto.Platform.Mac.Forms.Actions
{
public class MacButtonAction : ButtonAction
{
public Selector Selector { get; set; }
public MacButtonAction(string id, string text, string selector)
: base(id, text)
{
this.Selector = new Selector(selector);
}
public override MenuItem GenerateMenuItem(Eto.Generator generator)
{
var item = base.GenerateMenuItem(generator) as ImageMenuItem;
var menuItem = (NSMenuItem)item.ControlObject;
menuItem.Target = null;
menuItem.Action = Selector;
return item;
}
public override ToolBarItem GenerateToolBarItem(ActionItem actionItem, Eto.Generator generator, ToolBarTextAlign textAlign)
{
var item = base.GenerateToolBarItem (actionItem, generator, textAlign);
var tb = (NSToolbarItem)item.ControlObject;
tb.Target = null;
tb.Action = Selector;
return item;
}
}
}
| using System;
using Eto.Forms;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
namespace Eto.Platform.Mac.Forms.Actions
{
public class MacButtonAction : ButtonAction
{
public Selector Selector { get; set; }
public MacButtonAction(string id, string text, string selector)
: base(id, text)
{
this.Selector = new Selector(selector);
}
public override MenuItem Generate (ActionItem actionItem, ISubMenuWidget menu)
{
var item = base.GenerateMenuItem(actionItem, menu.Generator) as ImageMenuItem;
var menuItem = (NSMenuItem)item.ControlObject;
menuItem.Target = null;
menuItem.Action = Selector;
return item;
}
public override ToolBarItem GenerateToolBarItem(ActionItem actionItem, Generator generator, ToolBarTextAlign textAlign)
{
var item = base.GenerateToolBarItem (actionItem, generator, textAlign);
var tb = (NSToolbarItem)item.ControlObject;
tb.Target = null;
tb.Action = Selector;
return item;
}
}
}
| bsd-3-clause | C# |
9fcd75b15c371906972393b6540e4384acb28483 | Update BigAppliances.cs | jkanchelov/Telerik-OOP-Team-StarFruit | TeamworkStarFruit/CatalogueLib/Products/BigAppliances.cs | TeamworkStarFruit/CatalogueLib/Products/BigAppliances.cs | namespace CatalogueLib
{
using System.Text;
using CatalogueLib.Products.Enumerations;
public abstract class BigAppliances : Product
{
public BigAppliances()
{
}
public BigAppliances(int ID, decimal price, bool isAvailable, Brand brand, string Color, string CountryOfOrigin)
: base(ID, price, isAvailable, brand)
{
this.Color = Color;
this.CountryOfOrigin = CountryOfOrigin;
}
public string Color { get; private set; }
public string CountryOfOrigin { get; private set; }
public override string ToString()
{
StringBuilder stroitel = new StringBuilder();
stroitel = stroitel.Append(string.Format("{0}", base.ToString()));
stroitel = stroitel.Append(string.Format(" Color: {0}\n Country of origin: {1}", this.Color, this.CountryOfOrigin));
return stroitel.AppendLine().ToString();
}
}
}
| namespace CatalogueLib
{
using CatalogueLib.Products.Enumerations;
public abstract class BigAppliances : Product
{
public BigAppliances()
{
}
public BigAppliances(int ID, decimal price, bool isAvailable, Brand brand, string Color, string CountryOfOrigin)
: base(ID, price, isAvailable, brand)
{
this.Color = Color;
this.CountryOfOrigin = CountryOfOrigin;
}
public string Color { get; private set; }
public string CountryOfOrigin { get; private set; }
public override string ToString()
{
return base.ToString() + $"Color: {this.Color}\nCountry of origin:{this.CountryOfOrigin}";
}
}
}
| mit | C# |
39ca3ee965e85a280499aae16368fa16da568513 | add xml comment to javascripttext property | ObjectivityLtd/Test.Automation,ObjectivityBSS/Test.Automation | Objectivity.Test.Automation.Common/WebElements/JavaScriptAlert.cs | Objectivity.Test.Automation.Common/WebElements/JavaScriptAlert.cs | /*
The MIT License (MIT)
Copyright (c) 2015 Objectivity Bespoke Software Specialists
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.
*/
namespace Objectivity.Test.Automation.Common.WebElements
{
using OpenQA.Selenium;
/// <summary>
/// Implementation for JavaScript Alert interface.
/// </summary>
public class JavaScriptAlert
{
/// <summary>
/// The web driver
/// </summary>
private readonly IWebDriver webDriver;
/// <summary>
/// get Java script popup text
/// </summary>
public string JavaScriptText
{
get { return webDriver.SwitchTo().Alert().Text; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JavaScriptAlert"/> class.
/// </summary>
/// <param name="webDriver">The web driver.</param>
public JavaScriptAlert(IWebDriver webDriver)
{
this.webDriver = webDriver;
}
/// <summary>
/// Confirms the java script alert popup.
/// </summary>
public void ConfirmJavaScriptAlert()
{
this.webDriver.SwitchTo().Alert().Accept();
this.webDriver.SwitchTo().DefaultContent();
}
/// <summary>
/// Dismisses the java script alert popup.
/// </summary>
public void DismissJavaScriptAlert()
{
this.webDriver.SwitchTo().Alert().Dismiss();
}
}
}
| /*
The MIT License (MIT)
Copyright (c) 2015 Objectivity Bespoke Software Specialists
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.
*/
namespace Objectivity.Test.Automation.Common.WebElements
{
using OpenQA.Selenium;
/// <summary>
/// Implementation for JavaScript Alert interface.
/// </summary>
public class JavaScriptAlert
{
/// <summary>
/// The web driver
/// </summary>
private readonly IWebDriver webDriver;
public string JavaScriptText
{
get { return webDriver.SwitchTo().Alert().Text; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JavaScriptAlert"/> class.
/// </summary>
/// <param name="webDriver">The web driver.</param>
public JavaScriptAlert(IWebDriver webDriver)
{
this.webDriver = webDriver;
}
/// <summary>
/// Confirms the java script alert popup.
/// </summary>
public void ConfirmJavaScriptAlert()
{
this.webDriver.SwitchTo().Alert().Accept();
this.webDriver.SwitchTo().DefaultContent();
}
/// <summary>
/// Dismisses the java script alert popup.
/// </summary>
public void DismissJavaScriptAlert()
{
this.webDriver.SwitchTo().Alert().Dismiss();
}
}
}
| mit | C# |
22e4c4e2de308ce60c0e73014efb7e5fc0279ea2 | add Register.RegisterDomainCache() | jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK | src/Senparc.Weixin.Cache/Senparc.Weixin.Cache.Memcached/Register.cs | src/Senparc.Weixin.Cache/Senparc.Weixin.Cache.Memcached/Register.cs | #if NETCOREAPP2_0 || NETCOREAPP2_1
using Microsoft.AspNetCore.Builder;
#endif
namespace Senparc.Weixin.Cache.Memcached
{
public static class Register
{
#if NETCOREAPP2_0 || NETCOREAPP2_1
/// <summary>
/// 注册 Senparc.Weixin.Cache.Memcached
/// </summary>
/// <param name="app"></param>
public static IApplicationBuilder UseSenparcWeixinCacheMemcached(this IApplicationBuilder app)
{
app.UseEnyimMemcached();
RegisterDomainCache();
return app;
}
#endif
/// <summary>
/// 注册领域缓存
/// </summary>
public static void RegisterDomainCache()
{
var cache = MemcachedContainerCacheStrategy.Instance;
}
}
}
| #if !NET45
using Microsoft.AspNetCore.Builder;
namespace Senparc.Weixin.Cache.Memcached
{
public static class Register
{
/// <summary>
/// 注册 Senparc.Weixin.Cache.Memcached
/// </summary>
/// <param name="app"></param>
public static IApplicationBuilder UseSenparcWeixinCacheMemcached(this IApplicationBuilder app)
{
app.UseEnyimMemcached();
var cache = MemcachedContainerCacheStrategy.Instance;
return app;
}
}
}
#endif | apache-2.0 | C# |
1f449a88888080a196d6a575007d523f810ee64c | Stop showing acres of script when the template doesn't compile | awhewell/sql-script-generator | SqlScriptGenerator/Generator.cs | SqlScriptGenerator/Generator.cs | // Copyright © 2017 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RazorTemplates.Core;
using SqlScriptGenerator.Models;
namespace SqlScriptGenerator
{
class Generator
{
public string ApplyModelToTemplate(string templatePath, TemplateModel model)
{
if(!File.Exists(templatePath)) {
throw new FileNotFoundException($"Could not load template {templatePath}, it does not exist");
}
var templateSource = File.ReadAllText(templatePath);
ITemplate<TemplateModel> template;
try {
template = Template.Compile<TemplateModel>(templateSource);
} catch(TemplateCompilationException ex) {
var errors = String.Join(Environment.NewLine, ex.Errors.Select(r => $"Line {r.Line} col {r.Column}: {r.ErrorNumber} {r.ErrorText}"));
throw new InvalidOperationException($"Failed to compile template: {errors}");
}
var result = template.Render(model);
result = TemplateSwitchesStorage.RemoveSwitchesFromSource(result);
return result;
}
}
}
| // Copyright © 2017 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RazorTemplates.Core;
using SqlScriptGenerator.Models;
namespace SqlScriptGenerator
{
class Generator
{
public string ApplyModelToTemplate(string templatePath, TemplateModel model)
{
if(!File.Exists(templatePath)) {
throw new FileNotFoundException($"Could not load template {templatePath}, it does not exist");
}
var templateSource = File.ReadAllText(templatePath);
templateSource = TemplateSwitchesStorage.RemoveSwitchesFromSource(templateSource);
var template = Template.Compile<TemplateModel>(templateSource);
var result = template.Render(model);
return result;
}
}
}
| bsd-3-clause | C# |
9aa9edde0ac11c4250a60b7aaedd07a794332e8f | fix for test finishing early sometimes and failing | Pondidum/Ledger,Pondidum/Ledger | Ledger.Tests/Stores/ProjectionStoreDecoratorTests.cs | Ledger.Tests/Stores/ProjectionStoreDecoratorTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Ledger.Acceptance.TestDomain;
using Ledger.Acceptance.TestDomain.Events;
using Ledger.Stores;
using Shouldly;
using Xunit;
namespace Ledger.Tests.Stores
{
public class ProjectionStoreDecoratorTests
{
[Fact]
public void When_colleting_all_events()
{
var reset = new AutoResetEvent(false);
var projectionist = new Projectionist(reset);
var memoryStore = new InMemoryEventStore();
var wrapped = new ProjectionStoreDecorator(memoryStore, projectionist);
var aggregateStore = new AggregateStore<Guid>(wrapped);
var user = Candidate.Create("test", "[email protected]");
aggregateStore.Save("Users", user);
reset.WaitOne();
memoryStore.AllEvents.Single().ShouldBeOfType<CandidateCreated>();
projectionist.SeenEvents.Single().ShouldBeOfType<CandidateCreated>();
}
private class Projectionist : IProjectionist
{
private readonly AutoResetEvent _reset;
private readonly List<DomainEvent<Guid>> _seenEvents;
public Projectionist(AutoResetEvent reset)
{
_reset = reset;
_seenEvents = new List<DomainEvent<Guid>>();
}
public IEnumerable<DomainEvent<Guid>> SeenEvents => _seenEvents;
public void Project<TKey>(DomainEvent<TKey> domainEvent)
{
_seenEvents.Add(domainEvent as DomainEvent<Guid>);
_reset.Set();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Ledger.Acceptance.TestDomain;
using Ledger.Acceptance.TestDomain.Events;
using Ledger.Stores;
using Shouldly;
using Xunit;
namespace Ledger.Tests.Stores
{
public class ProjectionStoreDecoratorTests
{
[Fact]
public void When_colleting_all_events()
{
var projectionist = new Projectionist();
var memoryStore = new InMemoryEventStore();
var wrapped = new ProjectionStoreDecorator(memoryStore, projectionist);
var aggregateStore = new AggregateStore<Guid>(wrapped);
var user = Candidate.Create("test", "[email protected]");
aggregateStore.Save("Users", user);
memoryStore.AllEvents.Single().ShouldBeOfType<CandidateCreated>();
projectionist.SeenEvents.Single().ShouldBeOfType<CandidateCreated>();
}
private class Projectionist : IProjectionist
{
private readonly List<DomainEvent<Guid>> _seenEvents;
public Projectionist()
{
_seenEvents = new List<DomainEvent<Guid>>();
}
public IEnumerable<DomainEvent<Guid>> SeenEvents => _seenEvents;
public void Project<TKey>(DomainEvent<TKey> domainEvent)
{
_seenEvents.Add(domainEvent as DomainEvent<Guid>);
}
}
}
}
| lgpl-2.1 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.