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 |
|---|---|---|---|---|---|---|---|---|
0e9e9ab4cfaf3e15807dee45e72a18a7573e25c7 | Remove unnecessary synchronization logic. | bgourlie/BriansMod | Oxide.Ext.BriansMod/InjuryTracker.cs | Oxide.Ext.BriansMod/InjuryTracker.cs | namespace Oxide.Ext.BriansMod
{
using System;
using System.Collections.Generic;
using global::Rust;
using Model;
using UnityEngine;
public class InjuryTracker : IInjuryTracker
{
private const string Module = "InjuryTracker";
private static InjuryTracker instance;
public static InjuryTracker Instance => instance ?? (instance = new InjuryTracker());
public readonly Dictionary<ulong, Injury> State = new Dictionary<ulong, Injury>();
private readonly ILogger logger;
public InjuryTracker()
: this(Logger.Instance)
{
}
public InjuryTracker(ILogger logger)
{
this.logger = logger;
}
public void UpdateInjuryStatus(BasePlayer player, HitInfo hitInfo)
{
if (player.IsDead()
|| (player == hitInfo.Initiator && hitInfo.damageTypes.GetMajorityDamageType() == DamageType.Bleeding))
{
// Don't update anything if the player is dead or the "injury" is bleeding caused by a previous injury.
return;
}
// Todo: Have some sort of InjuryFactory that takes over this logic?
var injuryDistance = Vector3.Distance(player.transform.position, hitInfo.Initiator.transform.position);
var majorityDamageType = hitInfo.damageTypes.GetMajorityDamageType();
var newInjury = new Injury(hitInfo.Initiator, majorityDamageType, injuryDistance, DateTime.UtcNow);
bool updated = false;
Injury prevInjury;
if(!this.State.TryGetValue(player.userID, out prevInjury))
{
this.State.Add(player.userID, newInjury);
updated = true;
}
else
{
// If the previous injury and the new injury were both self-inflicted
// and have the same damage type, don't update it (very spammy).
// This is probably a micro optimization, but fuck it.
if (!(prevInjury.CausedBy == player &&
newInjury.CausedBy == player &&
prevInjury.PrimaryDamageType == newInjury.PrimaryDamageType))
{
this.State[player.userID] = newInjury;
updated = true;
}
}
if (updated)
{
this.logger.Debug("Updated injury for {0} to {1}", player.displayName, newInjury);
}
}
public bool TryGetLastInjury(BasePlayer player, out Injury injury)
{
return this.State.TryGetValue(player.userID, out injury);
}
}
} | namespace Oxide.Ext.BriansMod
{
using System;
using System.Collections.Generic;
using global::Rust;
using Model;
using UnityEngine;
public class InjuryTracker : IInjuryTracker
{
private const string Module = "InjuryTracker";
private static InjuryTracker instance;
public static InjuryTracker Instance => instance ?? (instance = new InjuryTracker());
public readonly Dictionary<ulong, Injury> State = new Dictionary<ulong, Injury>();
private readonly ILogger logger;
public InjuryTracker()
: this(Logger.Instance)
{
}
public InjuryTracker(ILogger logger)
{
this.logger = logger;
}
public void UpdateInjuryStatus(BasePlayer player, HitInfo hitInfo)
{
if (player.IsDead()
|| (player == hitInfo.Initiator && hitInfo.damageTypes.GetMajorityDamageType() == DamageType.Bleeding))
{
// Don't update anything if the player is dead or the "injury" is bleeding caused by a previous injury.
return;
}
// Todo: Have some sort of InjuryFactory that takes over this logic?
var injuryDistance = Vector3.Distance(player.transform.position, hitInfo.Initiator.transform.position);
var majorityDamageType = hitInfo.damageTypes.GetMajorityDamageType();
var newInjury = new Injury(hitInfo.Initiator, majorityDamageType, injuryDistance, DateTime.UtcNow);
bool updated = false;
lock (this.State)
{
Injury prevInjury;
if(!this.State.TryGetValue(player.userID, out prevInjury))
{
this.State.Add(player.userID, newInjury);
updated = true;
}
else
{
// If the previous injury and the new injury were both self-inflicted
// and have the same damage type, don't update it (very spammy).
// This is probably a micro optimization, but fuck it.
if (!(prevInjury.CausedBy == player &&
newInjury.CausedBy == player &&
prevInjury.PrimaryDamageType == newInjury.PrimaryDamageType))
{
this.State[player.userID] = newInjury;
updated = true;
}
}
}
if (updated)
{
this.logger.Info(Module, "Damage updated for {0}: {1}", player.displayName, newInjury);
}
}
public bool TryGetLastInjury(BasePlayer player, out Injury injury)
{
lock (this.State)
{
return this.State.TryGetValue(player.userID, out injury);
}
}
}
} | mit | C# |
68036b0da4dc4962facb6c1ea2988e041484bc0e | Add LocationCompleter to HDInsight cmdlets | AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell | src/ResourceManager/HDInsight/Commands.HDInsight/ManagementCommands/GetAzureHDInsightPropertiesCommand.cs | src/ResourceManager/HDInsight/Commands.HDInsight/ManagementCommands/GetAzureHDInsightPropertiesCommand.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.HDInsight.Commands;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.HDInsight.Models;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.HDInsight
{
[Cmdlet(
VerbsCommon.Get,
Constants.CommandNames.AzureHDInsightProperties),
OutputType(
typeof(CapabilitiesResponse))]
public class GetAzureHDInsightPropertiesCommand : HDInsightCmdletBase
{
#region Input Parameter Definitions
[Parameter(
Position = 0,
Mandatory = true,
HelpMessage = "Gets or sets the datacenter location for the cluster.")]
[LocationCompleter("Microsoft.HDInsight/locations/capabilities")]
public string Location { get; set; }
#endregion
public override void ExecuteCmdlet()
{
var result = HDInsightManagementClient.GetCapabilities(Location);
WriteObject(result);
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.HDInsight.Commands;
using Microsoft.Azure.Management.HDInsight.Models;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.HDInsight
{
[Cmdlet(
VerbsCommon.Get,
Constants.CommandNames.AzureHDInsightProperties),
OutputType(
typeof(CapabilitiesResponse))]
public class GetAzureHDInsightPropertiesCommand : HDInsightCmdletBase
{
#region Input Parameter Definitions
[Parameter(
Position = 0,
Mandatory = true,
HelpMessage = "Gets or sets the datacenter location for the cluster.")]
public string Location { get; set; }
#endregion
public override void ExecuteCmdlet()
{
var result = HDInsightManagementClient.GetCapabilities(Location);
WriteObject(result);
}
}
}
| apache-2.0 | C# |
0199c2e5f159ab95697f525643ca528a845a7ac4 | Add GENH support | Thealexbarney/VGAudio,Thealexbarney/LibDspAdpcm,Thealexbarney/VGAudio,Thealexbarney/LibDspAdpcm | src/DspAdpcm.Cli/ContainerTypes.cs | src/DspAdpcm.Cli/ContainerTypes.cs | using System;
using System.Collections.Generic;
using System.IO;
using DspAdpcm.Containers;
using DspAdpcm.Formats;
#if NET20
using DspAdpcm.Compatibility.LinqBridge;
using DspAdpcm.Compatibility.Serialization;
#else
using System.Linq;
#endif
namespace DspAdpcm.Cli
{
internal static class ContainerTypes
{
public static readonly Dictionary<FileType, ContainerType> Containers = new Dictionary<FileType, ContainerType>
{
[FileType.Wave] = new ContainerType(new[] { "wav", "wave" }, WaveReader.Read, (a, s) => new WaveWriter().WriteToStream(a, s)),
[FileType.Dsp] = new ContainerType(new[] { "dsp" }, DspReader.Read, (a, s) => new DspWriter().WriteToStream(a, s)),
[FileType.Brstm] = new ContainerType(new[] { "brstm" }, BrstmReader.Read, (a, s) => new BrstmWriter().WriteToStream(a, s)),
[FileType.Genh] = new ContainerType(new[] { "genh" }, GenhReader.Read, null)
};
public static readonly Dictionary<string, FileType> Extensions =
Containers.SelectMany(x => x.Value.Names.Select(y => new {y, x.Key}))
.ToDictionary(x => x.y, x => x.Key);
}
internal class ContainerType
{
public ContainerType(IEnumerable<string> names, Func<Stream, AudioData> read, Action<AudioData, Stream> write)
{
Names = names;
Read = read;
Write = write;
}
public IEnumerable<string> Names { get; }
public Func<Stream, AudioData> Read { get; }
public Action<AudioData, Stream> Write { get; }
}
} | using System;
using System.Collections.Generic;
using System.IO;
using DspAdpcm.Containers;
using DspAdpcm.Formats;
#if NET20
using DspAdpcm.Compatibility.LinqBridge;
using DspAdpcm.Compatibility.Serialization;
#else
using System.Linq;
#endif
namespace DspAdpcm.Cli
{
internal static class ContainerTypes
{
public static readonly Dictionary<FileType, ContainerType> Containers = new Dictionary<FileType, ContainerType>
{
[FileType.Wave] = new ContainerType(new[] { "wav", "wave" }, WaveReader.Read, (a, s) => new WaveWriter().WriteToStream(a, s)),
[FileType.Dsp] = new ContainerType(new[] { "dsp" }, DspReader.Read, (a, s) => new DspWriter().WriteToStream(a, s)),
[FileType.Brstm] = new ContainerType(new[] { "brstm" }, BrstmReader.Read, (a, s) => new BrstmWriter().WriteToStream(a, s))
};
public static readonly Dictionary<string, FileType> Extensions =
Containers.SelectMany(x => x.Value.Names.Select(y => new {y, x.Key}))
.ToDictionary(x => x.y, x => x.Key);
}
internal class ContainerType
{
public ContainerType(IEnumerable<string> names, Func<Stream, AudioData> read, Action<AudioData, Stream> write)
{
Names = names;
Read = read;
Write = write;
}
public IEnumerable<string> Names { get; }
public Func<Stream, AudioData> Read { get; }
public Action<AudioData, Stream> Write { get; }
}
} | mit | C# |
17a2d6ffb353bee4d592ba8d35254c920682eee4 | revert query processing | stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support | nuget-extensions/nuget-feed/Repo/LightPackageRepository.cs | nuget-extensions/nuget-feed/Repo/LightPackageRepository.cs | using System.Linq;
namespace JetBrains.TeamCity.NuGet.Feed.Repo
{
public class LightPackageRepository
{
private readonly ITeamCityPackagesRepo myRepo;
public LightPackageRepository(ITeamCityPackagesRepo repo)
{
myRepo = repo;
}
public IQueryable<TeamCityPackage> GetPackages()
{
// return new TeamCityQueryablePackages(myRepo).Query;
return myRepo.GetAllPackages().AsQueryable();
}
}
} | using System.Linq;
namespace JetBrains.TeamCity.NuGet.Feed.Repo
{
public class LightPackageRepository
{
private readonly ITeamCityPackagesRepo myRepo;
public LightPackageRepository(ITeamCityPackagesRepo repo)
{
myRepo = repo;
}
public IQueryable<TeamCityPackage> GetPackages()
{
return new TeamCityQueryablePackages(myRepo).Query;
//return myRepo.GetAllPackages().AsQueryable();
}
}
} | apache-2.0 | C# |
4212a9d0d765efd1527701cd9e90559e62ffe131 | Fix incorrect migration conditional | DrabWeb/osu,EVAST9919/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,DrabWeb/osu,ZLima12/osu,johnneijzen/osu,johnneijzen/osu,naoey/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,naoey/osu | osu.Game/Migrations/20180628011956_RemoveNegativeSetIDs.cs | osu.Game/Migrations/20180628011956_RemoveNegativeSetIDs.cs | using Microsoft.EntityFrameworkCore.Migrations;
namespace osu.Game.Migrations
{
public partial class RemoveNegativeSetIDs : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// There was a change that baetmaps were being loaded with "-1" online IDs, which is completely incorrect.
// This ensures there will not be unique key conflicts as a result of these incorrectly imported beatmaps.
migrationBuilder.Sql("UPDATE BeatmapSetInfo SET OnlineBeatmapSetID = null WHERE OnlineBeatmapSetID <= 0");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| using Microsoft.EntityFrameworkCore.Migrations;
namespace osu.Game.Migrations
{
public partial class RemoveNegativeSetIDs : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// There was a change that baetmaps were being loaded with "-1" online IDs, which is completely incorrect.
// This ensures there will not be unique key conflicts as a result of these incorrectly imported beatmaps.
migrationBuilder.Sql("UPDATE BeatmapSetInfo SET OnlineBeatmapSetID = null WHERE OnlineBeatmapSetID < 0");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| mit | C# |
6e98f7a04c0f00048026260b047e3d69c87e4d7f | Update comments | Archie-Yang/PcscDotNet | src/PcscDotNet/SCardDisposition.cs | src/PcscDotNet/SCardDisposition.cs | namespace PcscDotNet
{
/// <summary>
/// Action to take on the card in the connected reader on close.
/// </summary>
public enum SCardDisposition
{
/// <summary>
/// Eject the card on close.
/// </summary>
Eject = 3,
/// <summary>
/// Don't do anything special on close.
/// </summary>
Leave = 0,
/// <summary>
/// Reset the card on close (warm reset).
/// </summary>
Reset = 1,
/// <summary>
/// Power down the card on close (cold reset).
/// </summary>
Unpower = 2
}
}
| namespace PcscDotNet
{
/// <summary>
/// Action to take on the card in the connected reader on close.
/// </summary>
public enum SCardDisposition
{
/// <summary>
/// Eject the card on close.
/// </summary>
Eject = 3,
/// <summary>
/// Don't do anything special on close.
/// </summary>
Leave = 0,
/// <summary>
/// Reset the card on close.
/// </summary>
Reset = 1,
/// <summary>
/// Power down the card on close.
/// </summary>
Unpower = 2
}
}
| mit | C# |
c07fa9d8bbf07a8d6e63351587708e3666db42d9 | Patch 1 (#2) | stanriders/den0bot,stanriders/den0bot | den0bot/Userlist.cs | den0bot/Userlist.cs |
namespace den0bot
{
public enum Users
{
// User(Nickname, osuID)
[User("Фаердиггер", 5292815)]
Digger = 0,
[User("Веточка", 5100305)]
Vetochka = 1,
[User("Шоквейв", 2295157)]
Shockwave = 2,
[User("Амати", 5291370)]
Amaty = 3,
[User("Динозавр", 5385151)]
Denosaur = 4,
[User("Жаба", 6068934)]
Frog = 5,
[User("Оринель", 7589924)]
Orinel = 6,
[User("Сони", 5483135)]
Sony = 7,
[User("Тудути", 5651245)]
Tduty = 8,
[User("Стен", 7217455)]
Stan = 9,
[User("Шладик", 6393126)]
Wlad = 10,
[User("Егорыч", 6468387)]
Egor = 11,
[User("Панда", 5410993)]
Panda = 12,
[User("Ромачка", 5675579)]
Roma = 13,
[User("Куги", 6997572)]
Kugi = 14,
[User("Рефлекс", 5260387)]
Reflex = 15,
[User("Ельцин", 5217336)]
Qwerty = 16,
[User("Жека", 4880222)]
Emabb = 17,
[User("ккк", 4735736)]
Kkk = 18,
[User("Дельта", 8971641)]
deltaflux = 19,
[User("Кирюша", 2746956)]
Railgun = 20,
UserCount = 21
}
}
|
namespace den0bot
{
public enum Users
{
// User(Nickname, osuID)
[User("Фаердиггер", 5292815)]
Digger = 0,
[User("Веточка", 5100305)]
Vetochka = 1,
[User("Шоквейв", 2295157)]
Shockwave = 2,
[User("Амати", 5291370)]
Amaty = 3,
[User("Динозавр", 5385151)]
Denosaur = 4,
[User("Жаба", 6068934)]
Frog = 5,
[User("Оринель", 7589924)]
Orinel = 6,
[User("Сони", 5483135)]
Sony = 7,
[User("Тудути", 5651245)]
Tduty = 8,
[User("Стен", 7217455)]
Stan = 9,
[User("Шладик", 6393126)]
Wlad = 10,
[User("Егорыч", 6468387)]
Egor = 11,
[User("Панда", 5410993)]
Panda = 12,
[User("Ромачка", 5675579)]
Roma = 13,
[User("Куги", 6997572)]
Kugi = 14,
[User("Рефлекс", 5260387)]
Reflex = 15,
[User("Ельцин", 5217336)]
Qwerty = 16,
[User("Жека", 4880222)]
Emabb = 17,
[User("ккк", 4735736)]
Kkk = 18,
[User("Кирюша", 2746956)]
Railgun = 19,
UserCount = 20
}
}
| mit | C# |
23a4517b3463258162c51cd07bc500fc188488f8 | Address CRs | ClogenyTechnologies/azure-powershell,seanbamsft/azure-powershell,bgold09/azure-powershell,yadavbdev/azure-powershell,SarahRogers/azure-powershell,PashaPash/azure-powershell,shuagarw/azure-powershell,rohmano/azure-powershell,AzureRT/azure-powershell,hovsepm/azure-powershell,shuagarw/azure-powershell,zaevans/azure-powershell,krkhan/azure-powershell,atpham256/azure-powershell,shuagarw/azure-powershell,SarahRogers/azure-powershell,mayurid/azure-powershell,akurmi/azure-powershell,rhencke/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,arcadiahlyy/azure-powershell,hovsepm/azure-powershell,DeepakRajendranMsft/azure-powershell,yadavbdev/azure-powershell,oaastest/azure-powershell,alfantp/azure-powershell,rohmano/azure-powershell,zhencui/azure-powershell,jianghaolu/azure-powershell,PashaPash/azure-powershell,AzureAutomationTeam/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,jianghaolu/azure-powershell,rohmano/azure-powershell,dominiqa/azure-powershell,jasper-schneider/azure-powershell,haocs/azure-powershell,mayurid/azure-powershell,DeepakRajendranMsft/azure-powershell,pelagos/azure-powershell,juvchan/azure-powershell,jtlibing/azure-powershell,Matt-Westphal/azure-powershell,zaevans/azure-powershell,dulems/azure-powershell,TaraMeyer/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,rohmano/azure-powershell,enavro/azure-powershell,nemanja88/azure-powershell,jasper-schneider/azure-powershell,mayurid/azure-powershell,nemanja88/azure-powershell,TaraMeyer/azure-powershell,zhencui/azure-powershell,rohmano/azure-powershell,shuagarw/azure-powershell,arcadiahlyy/azure-powershell,haocs/azure-powershell,arcadiahlyy/azure-powershell,tonytang-microsoft-com/azure-powershell,haocs/azure-powershell,ClogenyTechnologies/azure-powershell,seanbamsft/azure-powershell,CamSoper/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,yadavbdev/azure-powershell,SarahRogers/azure-powershell,AzureRT/azure-powershell,mayurid/azure-powershell,chef-partners/azure-powershell,CamSoper/azure-powershell,yoavrubin/azure-powershell,juvchan/azure-powershell,naveedaz/azure-powershell,seanbamsft/azure-powershell,rhencke/azure-powershell,stankovski/azure-powershell,jasper-schneider/azure-powershell,rhencke/azure-powershell,dulems/azure-powershell,AzureAutomationTeam/azure-powershell,juvchan/azure-powershell,pelagos/azure-powershell,CamSoper/azure-powershell,seanbamsft/azure-powershell,alfantp/azure-powershell,CamSoper/azure-powershell,chef-partners/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,haocs/azure-powershell,chef-partners/azure-powershell,bgold09/azure-powershell,SarahRogers/azure-powershell,yadavbdev/azure-powershell,tonytang-microsoft-com/azure-powershell,Matt-Westphal/azure-powershell,zhencui/azure-powershell,devigned/azure-powershell,arcadiahlyy/azure-powershell,dulems/azure-powershell,SarahRogers/azure-powershell,bgold09/azure-powershell,dominiqa/azure-powershell,ankurchoubeymsft/azure-powershell,nemanja88/azure-powershell,DeepakRajendranMsft/azure-powershell,chef-partners/azure-powershell,pomortaz/azure-powershell,PashaPash/azure-powershell,pankajsn/azure-powershell,hovsepm/azure-powershell,Matt-Westphal/azure-powershell,yoavrubin/azure-powershell,akurmi/azure-powershell,zhencui/azure-powershell,alfantp/azure-powershell,AzureAutomationTeam/azure-powershell,enavro/azure-powershell,arcadiahlyy/azure-powershell,devigned/azure-powershell,pomortaz/azure-powershell,DeepakRajendranMsft/azure-powershell,zaevans/azure-powershell,jtlibing/azure-powershell,jianghaolu/azure-powershell,alfantp/azure-powershell,tonytang-microsoft-com/azure-powershell,jasper-schneider/azure-powershell,jtlibing/azure-powershell,pelagos/azure-powershell,yoavrubin/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,AzureRT/azure-powershell,shuagarw/azure-powershell,zaevans/azure-powershell,hovsepm/azure-powershell,bgold09/azure-powershell,rhencke/azure-powershell,akurmi/azure-powershell,ClogenyTechnologies/azure-powershell,pankajsn/azure-powershell,Matt-Westphal/azure-powershell,alfantp/azure-powershell,oaastest/azure-powershell,jtlibing/azure-powershell,dominiqa/azure-powershell,naveedaz/azure-powershell,pomortaz/azure-powershell,zhencui/azure-powershell,tonytang-microsoft-com/azure-powershell,pankajsn/azure-powershell,dominiqa/azure-powershell,pomortaz/azure-powershell,jtlibing/azure-powershell,seanbamsft/azure-powershell,CamSoper/azure-powershell,dulems/azure-powershell,DeepakRajendranMsft/azure-powershell,pelagos/azure-powershell,yantang-msft/azure-powershell,enavro/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,pankajsn/azure-powershell,TaraMeyer/azure-powershell,oaastest/azure-powershell,jianghaolu/azure-powershell,yantang-msft/azure-powershell,enavro/azure-powershell,yantang-msft/azure-powershell,hungmai-msft/azure-powershell,juvchan/azure-powershell,enavro/azure-powershell,jianghaolu/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,bgold09/azure-powershell,krkhan/azure-powershell,stankovski/azure-powershell,PashaPash/azure-powershell,stankovski/azure-powershell,ankurchoubeymsft/azure-powershell,devigned/azure-powershell,pelagos/azure-powershell,atpham256/azure-powershell,oaastest/azure-powershell,ankurchoubeymsft/azure-powershell,zaevans/azure-powershell,PashaPash/azure-powershell,hungmai-msft/azure-powershell,AzureRT/azure-powershell,seanbamsft/azure-powershell,haocs/azure-powershell,nemanja88/azure-powershell,TaraMeyer/azure-powershell,stankovski/azure-powershell,ankurchoubeymsft/azure-powershell,pomortaz/azure-powershell,TaraMeyer/azure-powershell,yoavrubin/azure-powershell,akurmi/azure-powershell,chef-partners/azure-powershell,naveedaz/azure-powershell,AzureRT/azure-powershell,AzureRT/azure-powershell,yoavrubin/azure-powershell,yantang-msft/azure-powershell,yantang-msft/azure-powershell,krkhan/azure-powershell,nemanja88/azure-powershell,juvchan/azure-powershell,akurmi/azure-powershell,hovsepm/azure-powershell,rhencke/azure-powershell,krkhan/azure-powershell,oaastest/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,mayurid/azure-powershell,tonytang-microsoft-com/azure-powershell,zhencui/azure-powershell,jasper-schneider/azure-powershell,Matt-Westphal/azure-powershell,dulems/azure-powershell,ankurchoubeymsft/azure-powershell,yadavbdev/azure-powershell,dominiqa/azure-powershell,naveedaz/azure-powershell,stankovski/azure-powershell,krkhan/azure-powershell,yantang-msft/azure-powershell | src/Common/Commands.Common/ComputeCloudException.cs | src/Common/Commands.Common/ComputeCloudException.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Hyak.Common;
using System;
using System.Linq;
using System.Text;
namespace Microsoft.WindowsAzure.Commands.Common
{
public class ComputeCloudException : CloudException
{
protected const string RequestIdHeaderInResponse = "x-ms-request-id";
public ComputeCloudException(CloudException ex)
: base(GetErrorMessageWithRequestIdInfo(ex), ex)
{
}
protected static string GetErrorMessageWithRequestIdInfo(CloudException cloudException)
{
if (cloudException == null)
{
throw new ArgumentNullException("cloudException");
}
var sb = new StringBuilder();
if (!string.IsNullOrEmpty(cloudException.Message))
{
sb.Append(cloudException.Message);
}
if (cloudException.Response != null &&
cloudException.Response.Headers != null)
{
var headers = cloudException.Response.Headers;
if (headers.ContainsKey(RequestIdHeaderInResponse))
{
sb.AppendLine().AppendFormat(
Properties.Resources.ComputeCloudExceptionOperationIdMessage,
headers[RequestIdHeaderInResponse].FirstOrDefault());
}
}
return sb.ToString();
}
}
} | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Hyak.Common;
using System;
using System.Linq;
using System.Text;
namespace Microsoft.WindowsAzure.Commands.Common
{
public class ComputeCloudException : CloudException
{
protected const string RequestIdHeaderInResponse = "x-ms-request-id";
public ComputeCloudException(CloudException ex)
: base(GetErrorMessageWithRequestIdInfo(ex), ex)
{
}
protected static string GetErrorMessageWithRequestIdInfo(CloudException cloudException)
{
if (cloudException == null)
{
throw new ArgumentNullException("cloudException");
}
var sb = new StringBuilder(cloudException.Message);
if (cloudException.Response != null)
{
var headers = cloudException.Response.Headers;
if (headers != null && headers.ContainsKey(RequestIdHeaderInResponse))
{
if (sb.Length > 0)
{
// If the original exception message is not empty, append a new line here.
sb.Append(Environment.NewLine);
}
sb.AppendFormat(
Properties.Resources.ComputeCloudExceptionOperationIdMessage,
headers[RequestIdHeaderInResponse].FirstOrDefault());
}
}
return sb.ToString();
}
}
} | apache-2.0 | C# |
7494aeeb900828ae8102e99b1bfd5c89b4111ac6 | Fix file version. | antoshkab/unity.wcf,ViceIce/unity.wcf | Unity.Wcf/Properties/AssemblyInfo.cs | Unity.Wcf/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("Unity.Wcf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevTrends")]
[assembly: AssemblyProduct("Unity.Wcf")]
[assembly: AssemblyCopyright("Copyright © DevTrends 2012")]
[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("23d35d8e-4fcf-4883-a014-63e622391798")]
// 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("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0")]
[assembly: AssemblyInformationalVersion("3.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Unity.Wcf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevTrends")]
[assembly: AssemblyProduct("Unity.Wcf")]
[assembly: AssemblyCopyright("Copyright © DevTrends 2012")]
[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("23d35d8e-4fcf-4883-a014-63e622391798")]
// 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("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1")]
[assembly: AssemblyInformationalVersion("3.0.0")]
| mit | C# |
1d77221c5872a97c5cc814c4cb10c0f793d2f1ed | Build failure test | mikeobrien/WcfRestContrib,mikeobrien/WcfRestContrib,mikeobrien/WcfRestContrib | src/WcfRestContrib.Tests/EncodedUrlBehaviorTests.cs | src/WcfRestContrib.Tests/EncodedUrlBehaviorTests.cs | using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using NUnit.Framework;
using Should;
namespace WcfRestContrib.Tests
{
[TestFixture]
public class EncodedUrlBehaviorTests
{
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "/{*value}")]
[OperationContract]
public string Method(string value)
{
return value;
}
}
[Test]
public void Should_Accept_Url_With_Encoded_Forwardslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%2fthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain("this/that@someplace.com");
}
}
[Test]
public void Should_Accept_Url_With_Encoded_Backslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%5cthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain(@"this/that@someplace.com");
}
}
}
} | using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using NUnit.Framework;
using Should;
namespace WcfRestContrib.Tests
{
[TestFixture]
public class EncodedUrlBehaviorTests
{
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "/{*value}")]
[OperationContract]
public string Method(string value)
{
return value;
}
}
[Test]
public void should()
{
throw new Exception();
}
[Test]
public void Should_Accept_Url_With_Encoded_Forwardslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%2fthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain("this/that@someplace.com");
}
}
[Test]
public void Should_Accept_Url_With_Encoded_Backslash()
{
using (var host = new Host<Service>("http://localhost:48645/"))
{
var response = host.Get("this%5cthat@someplace.com");
response.StatusCode.ShouldEqual(HttpStatusCode.OK);
response.Content.ShouldContain(@"this/that@someplace.com");
}
}
}
} | mit | C# |
e7e40dbc5137d7f2cfd0bf03eab353acf8df1a3a | Add missing header | danielmundt/csremote | source/Remoting.Service/Events/EventDispatchedEventArgs.cs | source/Remoting.Service/Events/EventDispatchedEventArgs.cs | #region Header
// Copyright (C) 2012 Daniel Schubert
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion Header
using System;
using System.Collections.Generic;
using System.Text;
namespace Remoting.Service.Events
{
[Serializable]
public class EventDispatchedEventArgs : EventArgs
{
#region Fields
private Object data;
private String sink;
#endregion Fields
#region Constructors
public EventDispatchedEventArgs(String sink, Object data)
{
this.sink = sink;
this.data = data;
}
#endregion Constructors
#region Properties
public String Sink
{
get
{
return sink;
}
}
public Object Data
{
get
{
return data;
}
}
#endregion Properties
}
} | using System;
using System.Collections.Generic;
using System.Text;
namespace Remoting.Service.Events
{
[Serializable]
public class EventDispatchedEventArgs : EventArgs
{
#region Fields
private Object data;
private String sink;
#endregion Fields
#region Constructors
public EventDispatchedEventArgs(String sink, Object data)
{
this.sink = sink;
this.data = data;
}
#endregion Constructors
#region Properties
public String Sink
{
get
{
return sink;
}
}
public Object Data
{
get
{
return data;
}
}
#endregion Properties
}
} | mit | C# |
16e0310874675b2a6c7f04f0c091c89ea64e481d | Rename tests | Domysee/Pather.CSharp | test/Pather.CSharp.UnitTests/ResolverTests.cs | test/Pather.CSharp.UnitTests/ResolverTests.cs | using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pather.CSharp.UnitTests
{
public class ResolverTests
{
public ResolverTests()
{
}
[Fact]
public void SinglePropertyResolution_CorrectSetup_Success()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var result = r.Resolve(o, "Property");
result.Should().Be(value);
}
[Fact]
public void MultiplePropertyResolution_CorrectSetup_Success()
{
var value = "1";
var r = new Resolver();
var o = new { Property1 = new { Property2 = value } };
var result = r.Resolve(o, "Property1.Property2");
result.Should().Be(value);
}
}
}
| using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pather.CSharp.UnitTests
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class ResolverTests
{
public ResolverTests()
{
}
[Fact]
public void SinglePropertyResolution()
{
var value = "1";
var r = new Resolver();
var o = new { Property = value };
var result = r.Resolve(o, "Property");
result.Should().Be(value);
}
[Fact]
public void MultiplePropertyResolution()
{
var value = "1";
var r = new Resolver();
var o = new { Property1 = new { Property2 = value } };
var result = r.Resolve(o, "Property1.Property2");
result.Should().Be(value);
}
}
}
| mit | C# |
8c6274d0e11ee21ed758aa1fb0f6487124c2669d | Add messageworker start to main() | alekratz/apphack2-project | transf/Program.cs | transf/Program.cs | using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Text;
using transf.Log;
namespace transf
{
class Program
{
/// <summary>
/// Prompts for a nickname until a valid nickname is found.
/// </summary>
/// <returns>The valid nickname retrieved from user input</returns>
public static string GetNickname()
{
string prompt = "Type a nickname (4-16 chars, alphanum only): ";
string nickname = "";
do
{
Console.Write (prompt);
nickname = Console.ReadLine();
} while(!Regex.IsMatch (nickname, "[a-zA-Z0-9]{4,16}"));
return nickname;
}
public static void Main (string[] args)
{
// This should be the first thing that's done
Logger.Instance = new Logger (Console.Out);
Logger.Instance.LogLevel = LogLevel.Verbose; // up the verbosity
const int PORT = 44444;
string nickname = GetNickname ();
Logger.WriteDebug (Logger.GROUP_APP, "Using nickname {0}", nickname);
// Start a discovery worker and message worker
MessageWorker msgWorker = MessageWorker.Instance;
msgWorker.Start(PORT);
DiscoveryWorker discWorker = new DiscoveryWorker ();
discWorker.Start (PORT, nickname);
discWorker.Join ();
}
}
}
| using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Text;
using transf.Log;
namespace transf
{
class Program
{
/// <summary>
/// Prompts for a nickname until a valid nickname is found.
/// </summary>
/// <returns>The valid nickname retrieved from user input</returns>
public static string GetNickname()
{
string prompt = "Type a nickname (4-16 chars, alphanum only): ";
string nickname = "";
do
{
Console.Write (prompt);
nickname = Console.ReadLine();
} while(!Regex.IsMatch (nickname, "[a-zA-Z0-9]{4,16}"));
return nickname;
}
public static void Main (string[] args)
{
// This should be the first thing that's done
Logger.Instance = new Logger (Console.Out);
Logger.Instance.LogLevel = LogLevel.Verbose; // up the verbosity
const int PORT = 44444;
string nickname = GetNickname ();
Logger.WriteDebug (Logger.GROUP_APP, "Using nickname {0}", nickname);
DiscoveryWorker discWorker = new DiscoveryWorker ();
discWorker.Start (PORT, nickname);
discWorker.Join ();
}
}
}
| agpl-3.0 | C# |
a322a004ac24666a6019cb2442c2d0f7404b6764 | update route | smbc-digital/iag-contentapi | src/StockportContentApi/Controllers/RedirectsController.cs | src/StockportContentApi/Controllers/RedirectsController.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StockportContentApi.Repositories;
namespace StockportContentApi.Controllers
{
public class RedirectsController : Controller
{
private readonly ResponseHandler _handler;
private readonly RedirectsRepository _repository;
public RedirectsController(ResponseHandler handler,
RedirectsRepository repository)
{
_handler = handler;
_repository = repository;
}
[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet]
[Route("redirects")]
[Route("v1/redirects")]
public async Task<IActionResult> GetRedirects() => await _handler.Get(() => _repository.GetRedirects());
[HttpPatch]
[Route("v1/redirects")]
public async Task<IActionResult> UpdateRedirects() => await _handler.Get(() => _repository.GetUpdatedRedirects());
}
} | using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StockportContentApi.Repositories;
namespace StockportContentApi.Controllers
{
public class RedirectsController : Controller
{
private readonly ResponseHandler _handler;
private readonly RedirectsRepository _repository;
public RedirectsController(ResponseHandler handler,
RedirectsRepository repository)
{
_handler = handler;
_repository = repository;
}
[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet]
[Route("redirects")]
[Route("v1/redirects")]
public async Task<IActionResult> GetRedirects() => await _handler.Get(() => _repository.GetRedirects());
[HttpPatch]
[Route("update-redirects")]
public async Task<IActionResult> UpdateRedirects() => await _handler.Get(() => _repository.GetUpdatedRedirects());
}
} | mit | C# |
2ebcfc190e0004c12443fff5bdafd8e765e2d0e9 | Fix namespaces in the constructor | Team-Captain-Marvel-2016/TeamWorkSkeletonSample,Team-Captain-Marvel-2016/TeamWorkSkeletonSample,Team-Captain-Marvel-2016/Team-Captain-Marvel-2016-Project,Team-Captain-Marvel-2016/Team-Captain-Marvel-2016-Project | TeamWorkSkeleton/FootballPlayerAssembly/FootballPlayerFactoryClasses/VenusianFootballPlayerConstructingMethods.cs | TeamWorkSkeleton/FootballPlayerAssembly/FootballPlayerFactoryClasses/VenusianFootballPlayerConstructingMethods.cs | namespace FootballPlayerAssembly.FootballPlayerFactoryClasses
{
using FootballPlayerAbstractClass;
using SpeciesNameGenerators;
public static partial class FootballPlayerFactory
{
/// <summary>
/// Creates a new Venusian player object
/// applying previously generated set of base
/// FootballPlayer base abstract stats
/// wrapped in a GenericFootballPlayer object
/// </summary>
/// <param name="baseStats">
/// set of stats wrapped in a GenericFootballPlayer object
/// </param>
/// <returns>new Venusian(Position) object</returns>
private static FootballPlayer CreateVenusianAttacker
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.VenusianFootballPlayer.FootballPlayerFactory
.VenusianAttacker(baseStats);
return newPlayer;
}
private static FootballPlayer CreateVenusianDefender
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.VenusianFootballPlayer.FootballPlayerFactory
.VenusianDefender(baseStats);
return newPlayer;
}
private static FootballPlayer CreateVenusianMidfielder
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.VenusianFootballPlayer.FootballPlayerFactory
.VenusianMidfielder(baseStats);
return newPlayer;
}
private static FootballPlayer CreateVenusianGoalkeeper
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.VenusianFootballPlayer.FootballPlayerFactory
.VenusianGoalkeeper(baseStats);
return newPlayer;
}
private static string GetVenusianName()
{
return VenusianNameGenerator.GenerateName();
}
}
}
| namespace FootballPlayerAssembly.FootballPlayerFactoryClasses
{
using FootballPlayerAbstractClass;
using SpeciesNameGenerators;
public static partial class FootballPlayerFactory
{
/// <summary>
/// Creates a new Venusian player object
/// applying previously generated set of base
/// FootballPlayer base abstract stats
/// wrapped in a GenericFootballPlayer object
/// </summary>
/// <param name="baseStats">
/// set of stats wrapped in a GenericFootballPlayer object
/// </param>
/// <returns>new Venusian(Position) object</returns>
private static FootballPlayer CreateVenusianAttacker
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.NeptunianFootballPlayer.FootballPlayerFactory
.VenusianAttacker(baseStats);
return newPlayer;
}
private static FootballPlayer CreateVenusianDefender
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.NeptunianFootballPlayer.FootballPlayerFactory
.VenusianDefender(baseStats);
return newPlayer;
}
private static FootballPlayer CreateVenusianMidfielder
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.NeptunianFootballPlayer.FootballPlayerFactory
.VenusianMidfielder(baseStats);
return newPlayer;
}
private static FootballPlayer CreateVenusianGoalkeeper
(GenericFootballPlayerClasses.FootballPlayerFactory.GenericFootballPlayer baseStats)
{
var newPlayerName = GetVenusianName();
var newPlayer = new RolesClasses.NeptunianFootballPlayer.FootballPlayerFactory
.VenusianGoalkeeper(baseStats);
return newPlayer;
}
private static string GetVenusianName()
{
return VenusianNameGenerator.GenerateName();
}
}
}
| mit | C# |
0aab43385c6b4215075d5b02fe15a613d8171a5b | Revert "Make IssueId public (or powershell can't see it)" | JetBrains/YouTrackSharp,JetBrains/YouTrackSharp | src/YouTrackSharp/Cmdlets/GetIssueCmdlet.cs | src/YouTrackSharp/Cmdlets/GetIssueCmdlet.cs | #region License
// Distributed under the BSD License
//
// YouTrackSharp Copyright (c) 2010-2012, Hadi Hariri and Contributors
// All rights reserved.
//
// Redistribution and use 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 Hadi Hariri nor the
// names of its 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
// <COPYRIGHTHOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#endregion
using System.Management.Automation;
namespace YouTrackSharp.CmdLets
{
[Cmdlet(VerbsCommon.Get, "issue")]
public class GetIssueCmdlet : YouTrackIssueCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "Issue Id")]
[ValidateNotNull]
string IssueId { get; set; }
protected override void ProcessRecord()
{
var issue = IssueManagement.GetIssue(IssueId);
WriteObject(issue);
}
}
} | #region License
// Distributed under the BSD License
//
// YouTrackSharp Copyright (c) 2010-2012, Hadi Hariri and Contributors
// All rights reserved.
//
// Redistribution and use 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 Hadi Hariri nor the
// names of its 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
// <COPYRIGHTHOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#endregion
using System.Management.Automation;
namespace YouTrackSharp.CmdLets
{
using Infrastructure;
[Cmdlet(VerbsCommon.Get, "issue")]
public class GetIssueCmdlet : YouTrackIssueCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "IssueId")]
[ValidateNotNull]
public string IssueId { get; set; }
protected override void ProcessRecord()
{
var issue = IssueManagement.GetIssue(IssueId);
WriteObject(issue);
}
}
} | apache-2.0 | C# |
6521e62ffac84e09f92511588f0f6d77f43c99ed | Fix test | webprofusion/Certify | src/Certify.Tests/Certify.Service.Tests.Integration/ServiceTestBase.cs | src/Certify.Tests/Certify.Service.Tests.Integration/ServiceTestBase.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Certify.SharedUtils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Certify.Service.Tests.Integration
{
public class ServiceTestBase
{
protected Client.CertifyServiceClient _client = null;
private Process _apiService;
[TestInitialize]
public async Task InitTests()
{
_client = new Certify.Client.CertifyServiceClient(new ServiceConfigManager());
// TODO : create API server instance instead of invoking directly
if (_apiService == null)
{
var svcpath = $"{ Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\..\\..\\..\\..\\..\\Certify.Service\\bin\\Debug\\net462\\CertifySSLManager.Service.exe";
_apiService = Process.Start(svcpath);
await Task.Delay(2000);
}
}
[TestCleanup]
public void TestCleanup()
{
if (_apiService != null)
{
_apiService.Kill();
_apiService.WaitForExit();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Certify.SharedUtils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Certify.Service.Tests.Integration
{
public class ServiceTestBase
{
protected Client.CertifyServiceClient _client = null;
private Process _apiService;
[TestInitialize]
public async Task InitTests()
{
_client = new Certify.Client.CertifyServiceClient(new ServiceConfigManager());
// TODO : create API server instance instead of invoking directly
if (_apiService == null)
{
_apiService = Process.Start(@"C:\Work\GIT\certify\src\Certify.Service\bin\Debug\net462\CertifySSLManager.Service.exe");
await Task.Delay(2000);
}
}
[TestCleanup]
public void TestCleanup()
{
if (_apiService != null)
{
_apiService.Kill();
_apiService.WaitForExit();
}
}
}
}
| mit | C# |
02a0e182ea1d211a0c0676048b35d6f03de0b1a2 | Allow for saving of simulations before the slime has fully expanded | willb611/SlimeSimulation | SlimeSimulation/View/WindowComponent/SimulationControlComponent/GrowthPhaseControlBox.cs | SlimeSimulation/View/WindowComponent/SimulationControlComponent/GrowthPhaseControlBox.cs | using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowController.Templates;
namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent
{
internal class GrowthPhaseControlBox : AbstractSimulationControlBox
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public GrowthPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
AddControls(simulationStepAbstractWindowController, parentWindow);
}
private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow));
Add(new SimulationStepUntilFullyGrownComponent(simulationStepAbstractWindowController, parentWindow));
Add(new SimulationSaveComponent(simulationStepAbstractWindowController.SimulationController, parentWindow));
}
}
}
| using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowController.Templates;
namespace SlimeSimulation.View.WindowComponent.SimulationControlComponent
{
internal class GrowthPhaseControlBox : AbstractSimulationControlBox
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public GrowthPhaseControlBox(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
AddControls(simulationStepAbstractWindowController, parentWindow);
}
private void AddControls(SimulationStepAbstractWindowController simulationStepAbstractWindowController, Window parentWindow)
{
Add(new SimulationStepButton(simulationStepAbstractWindowController, parentWindow));
Add(new SimulationStepUntilFullyGrownComponent(simulationStepAbstractWindowController, parentWindow));
}
}
}
| apache-2.0 | C# |
036d0d1232fa2358eb76c141d36572f05c707207 | Verify Code values in instr info table | 0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced | Iced.UnitTests/Intel/InstructionInfoTests/CodeValueTests.cs | Iced.UnitTests/Intel/InstructionInfoTests/CodeValueTests.cs | /*
Copyright (C) 2018 de4dot@gmail.com
This file is part of Iced.
Iced 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 3 of the License, or
(at your option) any later version.
Iced 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 Iced. If not, see <https://www.gnu.org/licenses/>.
*/
#if !NO_INSTR_INFO
using System;
using System.Collections.Generic;
using System.Text;
using Iced.Intel;
using Iced.Intel.InstructionInfoInternal;
using Xunit;
namespace Iced.UnitTests.Intel.InstructionInfoTests {
public sealed class CodeValueTests {
[Fact]
void Make_sure_all_Code_values_are_tested() {
int numCodeValues = -1;
foreach (var f in typeof(Code).GetFields()) {
if (f.IsLiteral) {
int value = (int)f.GetValue(null);
Assert.Equal(numCodeValues + 1, value);
numCodeValues = value;
}
}
numCodeValues++;
var tested = new bool[numCodeValues];
foreach (var info in GetTests())
tested[(int)(Code)info[1]] = true;
var sb = new StringBuilder();
int missing = 0;
var codeNames = Enum.GetNames(typeof(Code));
Assert.Equal(tested.Length, codeNames.Length);
for (int i = 0; i < tested.Length; i++) {
if (!tested[i]) {
sb.Append(codeNames[i] + " ");
missing++;
}
}
Assert.Equal("0 ins ", $"{missing} ins " + sb.ToString());
}
static IEnumerable<object[]> GetTests() {
foreach (var info in InstructionInfoTest_16.Test16_InstructionInfo_Data)
yield return info;
foreach (var info in InstructionInfoTest_32.Test32_InstructionInfo_Data)
yield return info;
foreach (var info in InstructionInfoTest_64.Test64_InstructionInfo_Data)
yield return info;
}
[Fact]
void Verify_Code_values_in_InfoHandlers_table() {
for (int i = 0; i < Iced.Intel.DecoderConstants.NumberOfCodeValues; i++) {
var code = (Code)(InfoHandlers.Data[i * 2] & (uint)InfoFlags1.CodeMask);
Assert.Equal((Code)i, code);
}
}
}
}
#endif
| /*
Copyright (C) 2018 de4dot@gmail.com
This file is part of Iced.
Iced 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 3 of the License, or
(at your option) any later version.
Iced 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 Iced. If not, see <https://www.gnu.org/licenses/>.
*/
#if !NO_INSTR_INFO
using System;
using System.Collections.Generic;
using System.Text;
using Iced.Intel;
using Xunit;
namespace Iced.UnitTests.Intel.InstructionInfoTests {
public sealed class CodeValueTests {
[Fact]
void Make_sure_all_Code_values_are_tested() {
int numCodeValues = -1;
foreach (var f in typeof(Code).GetFields()) {
if (f.IsLiteral) {
int value = (int)f.GetValue(null);
Assert.Equal(numCodeValues + 1, value);
numCodeValues = value;
}
}
numCodeValues++;
var tested = new bool[numCodeValues];
foreach (var info in GetTests())
tested[(int)(Code)info[1]] = true;
var sb = new StringBuilder();
int missing = 0;
var codeNames = Enum.GetNames(typeof(Code));
Assert.Equal(tested.Length, codeNames.Length);
for (int i = 0; i < tested.Length; i++) {
if (!tested[i]) {
sb.Append(codeNames[i] + " ");
missing++;
}
}
Assert.Equal("0 ins ", $"{missing} ins " + sb.ToString());
}
static IEnumerable<object[]> GetTests() {
foreach (var info in InstructionInfoTest_16.Test16_InstructionInfo_Data)
yield return info;
foreach (var info in InstructionInfoTest_32.Test32_InstructionInfo_Data)
yield return info;
foreach (var info in InstructionInfoTest_64.Test64_InstructionInfo_Data)
yield return info;
}
}
}
#endif
| mit | C# |
ac6a083a0e4532f103693ef3a42ba205ffcab37d | Add check box for show in library or not | SoftwareDesign/Library,SoftwareDesign/Library,SoftwareDesign/Library | MMLibrarySystem/MMLibrarySystem/Views/BookList/Index.cshtml | MMLibrarySystem/MMLibrarySystem/Views/BookList/Index.cshtml | @model IPagedList<MMLibrarySystem.Models.BookListController.BookListItem>
@{
ViewBag.Title = "Book List";
}
@using (Ajax.BeginForm(new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "bookListContainer"
}))
{
<fieldset style="border:1px solid black;padding: 1em">
<legend style="display: inline">Filter</legend>
Book name or description: <input type="search" name="searchTerm" />
Show books in library @Html.CheckBox("showInLibrary")
</fieldset>
<input type="submit" value="Search by name or description" />
}
@Html.Partial("_BookList", Model)
| @model IPagedList<MMLibrarySystem.Models.BookListController.BookListItem>
@{
ViewBag.Title = "Book List";
}
@using (Ajax.BeginForm(new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "bookListContainer"
}))
{
<fieldset style="border:1px solid black;padding: 1em">
<legend style="display: inline" >Filter</legend>
Book name or description: <input type="search" name="searchTerm" />
Show books in library @Html.CheckBox("showInLibrary")
</fieldset>
<input type="submit" value="Search by name or description" />
}
@Html.Partial("_BookList", Model)
| apache-2.0 | C# |
1448308b01b64477d06add1b1b23cc6e1d158996 | Migrate away from using job system to trigger background task to retain cross-version compatibility (#333) | kamsar/Unicorn,kamsar/Unicorn | src/Unicorn/Pipelines/UnicornSyncEnd/SendSerializationCompleteEvent.cs | src/Unicorn/Pipelines/UnicornSyncEnd/SendSerializationCompleteEvent.cs | using System.Linq;
using System.Threading;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Serialization;
using Sitecore.Diagnostics;
using Sitecore.Eventing;
using Sitecore.Sites;
using Unicorn.Predicates;
// ReSharper disable UnusedMember.Global
namespace Unicorn.Pipelines.UnicornSyncEnd
{
public class SendSerializationCompleteEvent : IUnicornSyncEndProcessor
{
public void Process(UnicornSyncEndPipelineArgs args)
{
var databases = args.SyncedConfigurations
.SelectMany(config => config.Resolve<IPredicate>().GetRootPaths())
.Select(path => path.DatabaseName)
.Distinct();
foreach (var database in databases)
{
DeserializationComplete(database);
}
}
protected virtual void DeserializationComplete(string databaseName)
{
Assert.ArgumentNotNullOrEmpty(databaseName, "databaseName");
// raising this event can take a long time. like 16 seconds. So we boot it as a job so it can go in the background.
Log.Info($"Job started: Raise deserialization complete async ({typeof(SendSerializationCompleteEvent).FullName})", this);
ThreadPool.QueueUserWorkItem(RaiseEvent, databaseName);
}
public virtual void RaiseEvent(object state)
{
using (new SiteContextSwitcher(SiteContext.GetSite("shell")))
{
var databaseName = state.ToString();
EventManager.RaiseEvent(new SerializationFinishedEvent());
Database database = Factory.GetDatabase(databaseName, false);
database?.RemoteEvents.Queue.QueueEvent(new SerializationFinishedEvent());
}
Log.Info($"Job ended: Raise deserialization complete async ({typeof(SendSerializationCompleteEvent).FullName})", this);
}
}
}
| using System.Linq;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Serialization;
using Sitecore.Diagnostics;
using Sitecore.Eventing;
using Sitecore.Jobs;
using Unicorn.Predicates;
// ReSharper disable UnusedMember.Global
namespace Unicorn.Pipelines.UnicornSyncEnd
{
public class SendSerializationCompleteEvent : IUnicornSyncEndProcessor
{
public void Process(UnicornSyncEndPipelineArgs args)
{
var databases = args.SyncedConfigurations
.SelectMany(config => config.Resolve<IPredicate>().GetRootPaths())
.Select(path => path.DatabaseName)
.Distinct();
foreach (var database in databases)
{
DeserializationComplete(database);
}
}
protected virtual void DeserializationComplete(string databaseName)
{
Assert.ArgumentNotNullOrEmpty(databaseName, "databaseName");
// raising this event can take a long time. like 16 seconds. So we boot it as a job so it can go in the background.
Job asyncSerializationFinished = new Job(new JobOptions("Raise deserialization complete async", "serialization", "shell", this, "RaiseEvent", new object[] { databaseName }));
JobManager.Start(asyncSerializationFinished);
}
public virtual void RaiseEvent(string databaseName)
{
EventManager.RaiseEvent(new SerializationFinishedEvent());
Database database = Factory.GetDatabase(databaseName, false);
database?.RemoteEvents.Queue.QueueEvent(new SerializationFinishedEvent());
}
}
}
| mit | C# |
e8b0a1289b1f324f7a76378eb4dfcbd799f8a5e1 | 添加一个备注。 | yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate,yoyocms/YoYoCms.AbpProjectTemplate | src/YoYoCms.AbpProjectTemplate.WebApi/WebApi/Providers/OAuthOptions.cs | src/YoYoCms.AbpProjectTemplate.WebApi/WebApi/Providers/OAuthOptions.cs | using System;
using Abp.Dependency;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
namespace YoYoCms.AbpProjectTemplate.WebApi.Providers
{
/// <summary>
/// Class OAuthOptions.
/// </summary>
public class OAuthOptions
{
/// <summary>
/// Gets or sets the server options.
/// </summary>
/// <value>The server options.</value>
private static OAuthAuthorizationServerOptions _serverOptions;
/// <summary>
/// Creates the server options.
/// </summary>
/// <returns>OAuthAuthorizationServerOptions.</returns>
public static OAuthAuthorizationServerOptions CreateServerOptions()
{
if (_serverOptions == null)
{
var provider = IocManager.Instance.Resolve<SimpleAuthorizationServerProvider>();
var refreshTokenProvider = IocManager.Instance.Resolve<SimpleRefreshTokenProvider>();
_serverOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/oauth/token"),
Provider = provider,
RefreshTokenProvider = refreshTokenProvider,
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30),
AllowInsecureHttp = true
};
}
//todo:考虑在最外面包一层数据,感觉问题不大。。下午研究研究,看看可以实验下不。
return _serverOptions;
}
}
} | using System;
using Abp.Dependency;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
namespace YoYoCms.AbpProjectTemplate.WebApi.Providers
{
/// <summary>
/// Class OAuthOptions.
/// </summary>
public class OAuthOptions
{
/// <summary>
/// Gets or sets the server options.
/// </summary>
/// <value>The server options.</value>
private static OAuthAuthorizationServerOptions _serverOptions;
/// <summary>
/// Creates the server options.
/// </summary>
/// <returns>OAuthAuthorizationServerOptions.</returns>
public static OAuthAuthorizationServerOptions CreateServerOptions()
{
if (_serverOptions == null)
{
var provider = IocManager.Instance.Resolve<SimpleAuthorizationServerProvider>();
var refreshTokenProvider = IocManager.Instance.Resolve<SimpleRefreshTokenProvider>();
_serverOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/oauth/token"),
Provider = provider,
RefreshTokenProvider = refreshTokenProvider,
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30),
AllowInsecureHttp = true
};
}
return _serverOptions;
}
}
} | apache-2.0 | C# |
61a38ab93d197b5a1283c408fd93b157a0efb74e | add link to gallery | IskraNikolova/OnlineAtelier,IskraNikolova/OnlineAtelier | Source/Web/OnlineAtelier.Web/Views/Users/ProfilePage.cshtml | Source/Web/OnlineAtelier.Web/Views/Users/ProfilePage.cshtml | @using Microsoft.AspNet.Identity
@model OnlineAtelier.Web.Models.ViewModels.Users.ProfileViewModel
@{
ViewBag.Title = "Profile Page";
}
<div class="row">
<div class="col-md-3">
<br />
<div class="panel panel-body">
<img class="userPhoto" src="@Url.Action("UserPhotos", "Users", new {id = Model.Id})" />
<h3>@Html.DisplayFor(m => m.FullName)</h3>
<div>
@Html.ActionLink("Качване на нова снимка", "Edit", new {id=User.Identity.GetUserId()})
</div>
<div>
@Html.ActionLink("Направи Поръчка", "Add", "Order", null, new {@class = "btn btn-primary"})
</div>
</div>
</div>
<div class="col-md-5">
<br />
@Html.Action("GetOrders", "Order", new { id = Model.Id })
</div>
<div class="col-md-4">
<h4>Приятелите на With love Eli: са дали най-много гласове за тези продукти</h4>
@Html.Action("Rating","Posts")
@Html.ActionLink("Виж още в галерия", "PostGallery", "Posts")
</div>
</div> | @using Microsoft.AspNet.Identity
@model OnlineAtelier.Web.Models.ViewModels.Users.ProfileViewModel
@{
ViewBag.Title = "Profile Page";
}
<div class="row">
<div class="col-md-3">
<br />
<div class="panel panel-body">
<img class="userPhoto" src="@Url.Action("UserPhotos", "Users", new {id = Model.Id})" />
<h3>@Html.DisplayFor(m => m.FullName)</h3>
<div>
@Html.ActionLink("Качване на нова снимка", "Edit", new {id=User.Identity.GetUserId()})
</div>
<div>
@Html.ActionLink("Направи Поръчка", "Add", "Order", null, new {@class = "btn btn-primary"})
</div>
</div>
</div>
<div class="col-md-5">
<br />
@Html.Action("GetOrders", "Order", new { id = Model.Id })
</div>
<div class="col-md-4">
<h4>Приятелите на With love Eli: са дали най-много гласове за тези продукти</h4>
@Html.Action("Rating","Posts")
</div>
</div> | mit | C# |
f06327190d427783575f1fa9c366e275847f45bb | Increment the app version. | ladimolnar/BitcoinDatabaseGenerator | Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs | Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
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("BitcoinDatabaseGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitcoinDatabaseGenerator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("372a7f52-b038-43aa-a42c-3ff0ecab1124")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
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("BitcoinDatabaseGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitcoinDatabaseGenerator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("372a7f52-b038-43aa-a42c-3ff0ecab1124")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
0f8c8aef22ceb85061bbaff1d0f238ef7b2e51e5 | Fix parsing reverse bug when unsupported options are passed as arguments | getmillipede/millipede-csharp | millipede.cs | millipede.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace millipede
{
class Program
{
static void Main(string[] args)
{
int[] padding_offsets = new int[] { 2, 1, 0, 1, 2, 3, 4, 4, 3 };
int i = 0;
int size = 20;
bool isReverse = false;
string head = "╚⊙ ⊙╝";
string body = "╚═(███)═╝";
if (args.Length > 0)
{
for (i = 0; i < args.Length; i++)
{
string tok = args[i];
int tmp = 0;
if (!int.TryParse(tok, out tmp) && !isReverse)
isReverse = tok == "-r";
else
size = tmp;
}
}
if (isReverse)
{
head = "╔⊙ ⊙╗";
body = "╔═(███)═╗";
for (i = size; i > 0; i--)
{
Console.WriteLine(new string(' ', padding_offsets[i % 9]) + body);
}
Console.WriteLine(new string(' ', padding_offsets[i % 9]+1) + head);
}
else
{
Console.WriteLine(new string(' ', padding_offsets[0]+1) + head);
for (i = 1; i < size; i++)
{
Console.WriteLine(new string(' ', padding_offsets[i % 9]) + body);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace millipede
{
class Program
{
static void Main(string[] args)
{
int[] padding_offsets = new int[] { 2, 1, 0, 1, 2, 3, 4, 4, 3 };
int i = 0;
int size = 20;
bool isReverse = false;
string head = "╚⊙ ⊙╝";
string body = "╚═(███)═╝";
if (args.Length > 0)
{
for (i = 0; i < args.Length; i++)
{
string tok = args[i];
int tmp = 0;
if (!int.TryParse(tok, out tmp))
isReverse = tok == "-r";
else
size = tmp;
}
}
if (isReverse)
{
head = "╔⊙ ⊙╗";
body = "╔═(███)═╗";
for (i = size; i > 0; i--)
{
Console.WriteLine(new string(' ', padding_offsets[i % 9]) + body);
}
Console.WriteLine(new string(' ', padding_offsets[i % 9]+1) + head);
}
else
{
Console.WriteLine(new string(' ', padding_offsets[0]+1) + head);
for (i = 1; i < size; i++)
{
Console.WriteLine(new string(' ', padding_offsets[i % 9]) + body);
}
}
}
}
}
| mit | C# |
4af4144a5d3b62daf25717dd468350528f362167 | Update RemoteNLogViewerOptionsPartialConfigurationValidator.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Logging/NLog/RemoteNLogViewerOptionsPartialConfigurationValidator.cs | TIKSN.Core/Analytics/Logging/NLog/RemoteNLogViewerOptionsPartialConfigurationValidator.cs | using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class
RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<
RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator() =>
this.RuleFor(instance => instance.Url.Scheme)
.Must(IsProperScheme)
.When(instance => instance.Url != null);
private static bool IsProperScheme(string scheme) => scheme.ToLowerInvariant() switch
{
"tcp" or "tcp4" or "tcp6" or "udp" or "udp4" or "udp6" or "http" or "https" => true,
_ => false,
};
}
}
| using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class
RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<
RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator() =>
this.RuleFor(instance => instance.Url.Scheme)
.Must(IsProperScheme)
.When(instance => instance.Url != null);
private static bool IsProperScheme(string scheme)
{
return scheme.ToLowerInvariant() switch
{
"tcp" or "tcp4" or "tcp6" or "udp" or "udp4" or "udp6" or "http" or "https" => true,
_ => false,
};
}
}
}
| mit | C# |
515c426f1a1ce2bea88aae3cacd5ed7cc8e244b2 | Test fixups | martinsmith1968/DNX.Helpers.Console | Test.DNX.Helpers.Console/CommandLine/Templating/DotLiquid/DotLiquidTemplateEngineTests.cs | Test.DNX.Helpers.Console/CommandLine/Templating/DotLiquid/DotLiquidTemplateEngineTests.cs | using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using DNX.Helpers.Assemblies;
using DNX.Helpers.Console.CommandLine.Help;
using DNX.Helpers.Console.CommandLine.Help.Maps;
using DNX.Helpers.Console.CommandLine.Templating.DotLiquid;
using DNX.Helpers.Linq;
using DNX.Helpers.Reflection;
using NUnit.Framework;
using Shouldly;
namespace Test.DNX.Helpers.Console.CommandLine.Templating.DotLiquid
{
internal class TestArguments
{
}
[TestFixture]
public class DotLiquidTemplateEngineTests
{
private DotLiquidTemplateEngine _templateEngine;
[SetUp]
public void TestInitialise()
{
_templateEngine = new DotLiquidTemplateEngine();
}
[Test]
public void RenderTest()
{
// Arrange
var assemblyDetails = new AssemblyDetails(Assembly.GetExecutingAssembly());
_templateEngine.AddObject("Program", assemblyDetails);
var argumentsMap = ArgumentsMap.Create<TestArguments>();
_templateEngine.AddObject("Arguments", argumentsMap);
var errors = new List<IDictionary<string, object>>()
{
new ParserErrorInfo() {Message = "Invalid argument: -k"}.ToDictionary()
};
dynamic result = new ExpandoObject();
result.Errors = errors;
result.Failed = errors.HasAny();
_templateEngine.AddObject("ParserResult", result);
// Act
var resultText = _templateEngine.Render(Templates.StandardTemplate);
// Assert
resultText.ShouldNotBeNullOrEmpty();
resultText.Length.ShouldBeGreaterThan(0);
//resultLines.Count.ShouldBe(Templates.StandardTemplateLines.Length - 1);
//
//resultLines.Skip(0).First().ShouldBe(string.Format("{0} v{1} - {2}", assemblyDetails.Title, assemblyDetails.SimplifiedVersion, assemblyDetails.Description));
//resultLines.Skip(1).First().ShouldBe(string.Format("{0}", assemblyDetails.Copyright));
//resultLines.Skip(2).First().ShouldBe("");
//resultLines.Skip(3).First().ShouldBe("Usage:");
//resultLines.Skip(4).First().ShouldBe(string.Format("{0}", assemblyDetails.FileName));
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using DNX.Helpers.Assemblies;
using DNX.Helpers.Console.CommandLine.Help;
using DNX.Helpers.Console.CommandLine.Help.Maps;
using DNX.Helpers.Console.CommandLine.Templating.DotLiquid;
using DNX.Helpers.Reflection;
using NUnit.Framework;
using Shouldly;
namespace Test.DNX.Helpers.Console.CommandLine.Templating.DotLiquid
{
internal class TestArguments
{
}
[TestFixture]
public class DotLiquidTemplateEngineTests
{
private DotLiquidTemplateEngine _templateEngine;
[SetUp]
public void TestInitialise()
{
_templateEngine = new DotLiquidTemplateEngine();
}
[Test]
public void RenderTest()
{
// Arrange
var assemblyDetails = new AssemblyDetails(Assembly.GetExecutingAssembly());
_templateEngine.AddObject("Program", assemblyDetails);
var argumentsMap = ArgumentsMap.Create<TestArguments>();
_templateEngine.AddObject("Arguments", argumentsMap);
dynamic result = new ExpandoObject();
result.Failed = true;
result.Errors = new List<IDictionary<string, object>>()
{
new ParserErrorInfo() {Message = "Invalid argument: -k"}.ToDictionary()
};
_templateEngine.AddObject("ParserResult", result);
// Act
var resultText = _templateEngine.Render(Templates.StandardTemplate);
// Assert
resultText.ShouldNotBeNullOrEmpty();
resultText.Length.ShouldBeGreaterThan(0);
//resultLines.Count.ShouldBe(Templates.StandardTemplateLines.Length - 1);
//
//resultLines.Skip(0).First().ShouldBe(string.Format("{0} v{1} - {2}", assemblyDetails.Title, assemblyDetails.SimplifiedVersion, assemblyDetails.Description));
//resultLines.Skip(1).First().ShouldBe(string.Format("{0}", assemblyDetails.Copyright));
//resultLines.Skip(2).First().ShouldBe("");
//resultLines.Skip(3).First().ShouldBe("Usage:");
//resultLines.Skip(4).First().ShouldBe(string.Format("{0}", assemblyDetails.FileName));
}
}
}
| mit | C# |
a730b4117b01589c465d489fca20cd73f0263863 | fix exception in AlbumPriceIsReallyTooMuchValidation | Jack109/MahApps.Metro,jumulr/MahApps.Metro,xxMUROxx/MahApps.Metro,Danghor/MahApps.Metro,ye4241/MahApps.Metro,chuuddo/MahApps.Metro,pfattisc/MahApps.Metro,Evangelink/MahApps.Metro,p76984275/MahApps.Metro,MahApps/MahApps.Metro,batzen/MahApps.Metro,psinl/MahApps.Metro | samples/MetroDemo/ValueConverter/AlbumPriceIsTooMuchConverter.cs | samples/MetroDemo/ValueConverter/AlbumPriceIsTooMuchConverter.cs | using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using MetroDemo.Models;
namespace MetroDemo.ValueConverter
{
public class AlbumPriceIsTooMuchConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is decimal)
{
var price = (decimal)value;
if (price > 15 && price < 20)
{
return true;
}
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
public class AlbumPriceIsReallyTooMuchValidation : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
var bindingGroup = value as BindingGroup;
var album = bindingGroup?.Items.OfType<Album>().ElementAtOrDefault(0);
if (album != null && album.Price >= 20)
{
return new ValidationResult(false, $"The price {album.Price} of the album '{album.Title}' by '{album.Artist.Name}' is too much!");
}
return ValidationResult.ValidResult;
}
}
} | using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using MetroDemo.Models;
namespace MetroDemo.ValueConverter
{
public class AlbumPriceIsTooMuchConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is decimal)
{
var price = (decimal)value;
if (price > 15 && price < 20)
{
return true;
}
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
public class AlbumPriceIsReallyTooMuchValidation : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
var bindingGroup = value as BindingGroup;
if (bindingGroup != null)
{
var album = (Album)bindingGroup.Items[0];
if (album.Price >= 20)
{
return new ValidationResult(false, string.Format("The price {0} of the album '{1}' by '{2}' is too much!", album.Price, album.Title, album.Artist.Name));
}
}
return ValidationResult.ValidResult;
}
}
} | mit | C# |
a11eeb12d668997ac2e8589ad3f6c722d3af9003 | add correct attribute | smhinsey/Fulcrum,smhinsey/Fulcrum,smhinsey/Fulcrum | seed/FulcrumSeed/Components/UserAccounts/Commands/EditAccount.cs | seed/FulcrumSeed/Components/UserAccounts/Commands/EditAccount.cs | using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Fulcrum.Core;
using Fulcrum.Core.Security;
namespace FulcrumSeed.Components.UserAccounts.Commands
{
[RequiresClaim(ClaimTypes.Role, UserRoles.Admin)]
public class EditAccount : DefaultCommand
{
[Required]
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid Id { get; set; }
//public Guid[] GroupIds { get; set; }
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Fulcrum.Core;
using Fulcrum.Core.Security;
namespace FulcrumSeed.Components.UserAccounts.Commands
{
//[RequiresClaim(ClaimTypes.Role, UserRoles.Admin)]
[RequiresClaim(ClaimTypes.Role, "whateverman")]
public class EditAccount : DefaultCommand
{
[Required]
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid Id { get; set; }
//public Guid[] GroupIds { get; set; }
}
}
| bsd-3-clause | C# |
698048ab59a773bd9cedac5dc01d74005dad56ad | Send a POST to light up the HockeyGoalLight | TeamGOOOOAAAAAALLL/Azure | AzureCloudService1/GOALWorker/LightNotifier.cs | AzureCloudService1/GOALWorker/LightNotifier.cs | using System.Diagnostics;
using System.Net;
using System.Text;
using System.IO;
namespace GOALWorker
{
public static class LightNotifier
{
//TODO: Jared Implement call to each light here for their team
public static void NotifyLightsForTeam(string teamname)
{
Trace.TraceInformation("GOALWorker is Sending Light Request for {0}", teamname);
WebRequest request = WebRequest.Create("https://api.spark.io/v1/devices/DEVICEID/score");
request.Method = "POST";
string postData = "access_token=ACCESSTOKEN¶ms=0%2C255%2C0";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
request.GetResponse();
}
}
}
| using System.Diagnostics;
namespace GOALWorker
{
public static class LightNotifier
{
//TODO: Jared Implement call to each light here for their team
public static void NotifyLightsForTeam(string teamname)
{
Trace.TraceInformation("GOALWorker is Sending Light Request for {0}", teamname);
}
}
}
| bsd-3-clause | C# |
e85c005b04da24cdd62ad65066ccc409ca856a23 | Disable autoloading of Interactive Window (#1299) | lukedgr/nodejstools,kant2002/nodejstools,mjbvz/nodejstools,kant2002/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,paladique/nodejstools,paulvanbrenk/nodejstools,paladique/nodejstools,mjbvz/nodejstools,paladique/nodejstools,paladique/nodejstools,mjbvz/nodejstools,Microsoft/nodejstools,mjbvz/nodejstools,kant2002/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,Microsoft/nodejstools,paulvanbrenk/nodejstools,mjbvz/nodejstools,Microsoft/nodejstools,paulvanbrenk/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools,paladique/nodejstools,lukedgr/nodejstools | Common/Product/ReplWindow/ReplWindowPackage.cs | Common/Product/ReplWindow/ReplWindowPackage.cs | /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
#if NTVS_FEATURE_INTERACTIVEWINDOW
using Microsoft.VisualStudio;
namespace Microsoft.NodejsTools.Repl {
#else
namespace Microsoft.VisualStudio.Repl {
#endif
/// <summary>
/// This is the class that implements the package exposed by this assembly.
///
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
// a package.
[PackageRegistration(UseManagedResourcesOnly = true)]
#if NTVS_FEATURE_INTERACTIVEWINDOW
[Description("Node.js Tools - Interactive Window")]
#else
[Description("Visual Studio Interactive Window")]
#endif
// This attribute is needed to let the shell know that this package exposes some menus.
[ProvideKeyBindingTable(ReplWindow.TypeGuid, 200)] // Resource ID: "Interactive Console"
[ProvideToolWindow(typeof(ReplWindow), Style = VsDockStyle.Linked, Orientation = ToolWindowOrientation.none, Window = ToolWindowGuids80.Outputwindow, MultiInstances = true)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(Guids.guidReplWindowPkgString)]
internal sealed class ReplWindowPackage : Package, IVsToolWindowFactory {
int IVsToolWindowFactory.CreateToolWindow(ref Guid toolWindowType, uint id) {
if (toolWindowType == typeof(ReplWindow).GUID) {
var model = (IComponentModel)GetService(typeof(SComponentModel));
var replProvider = (ReplWindowProvider)model.GetService<IReplWindowProvider>();
return replProvider.CreateFromRegistry(model, (int)id) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
return VSConstants.E_FAIL;
}
}
}
| /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
#if NTVS_FEATURE_INTERACTIVEWINDOW
using Microsoft.VisualStudio;
namespace Microsoft.NodejsTools.Repl {
#else
namespace Microsoft.VisualStudio.Repl {
#endif
/// <summary>
/// This is the class that implements the package exposed by this assembly.
///
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
// a package.
[PackageRegistration(UseManagedResourcesOnly = true)]
#if NTVS_FEATURE_INTERACTIVEWINDOW
[Description("Node.js Tools - Interactive Window")]
#else
[Description("Visual Studio Interactive Window")]
#endif
// This attribute is needed to let the shell know that this package exposes some menus.
[ProvideKeyBindingTable(ReplWindow.TypeGuid, 200)] // Resource ID: "Interactive Console"
[ProvideToolWindow(typeof(ReplWindow), Style = VsDockStyle.Linked, Orientation = ToolWindowOrientation.none, Window = ToolWindowGuids80.Outputwindow, MultiInstances = true)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideAutoLoad(Microsoft.VisualStudio.Shell.Interop.UIContextGuids.NoSolution)]
[ProvideAutoLoad(Microsoft.VisualStudio.Shell.Interop.UIContextGuids.SolutionExists)]
[Guid(Guids.guidReplWindowPkgString)]
internal sealed class ReplWindowPackage : Package, IVsToolWindowFactory {
int IVsToolWindowFactory.CreateToolWindow(ref Guid toolWindowType, uint id) {
if (toolWindowType == typeof(ReplWindow).GUID) {
var model = (IComponentModel)GetService(typeof(SComponentModel));
var replProvider = (ReplWindowProvider)model.GetService<IReplWindowProvider>();
return replProvider.CreateFromRegistry(model, (int)id) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
return VSConstants.E_FAIL;
}
}
}
| apache-2.0 | C# |
28f4d3852750bdcb071e489a5e92c3988b6b667a | Remove error in case the searchString is empty | ismaelbelghiti/Tigwi,ismaelbelghiti/Tigwi | Core/Tigwi.UI/Views/Account/ShowAccount.cshtml | Core/Tigwi.UI/Views/Account/ShowAccount.cshtml | @model Tigwi.UI.Models.IAccountModel
@{
ViewBag.Title = "ShowAccount";
}
@section LeftInfos
{
<h3>@Model.Name</h3>
<p>@Model.Description</p>
@if(User.Identity.IsAuthenticated)
{
@Html.Partial("_FollowPerson", Model)
@Html.Partial("_AccountFollowedPublicLists", Model)
}
}
@Html.Partial("_ViewPostList", Model.PersonalList.PostsAfter(DateTime.MinValue, 10)) | @model Tigwi.UI.Models.IAccountModel
@{
ViewBag.Title = "ShowAccount";
}
@section LeftInfos
{
<p>Oh Hai @Model.Name</p>
@if(User.Identity.IsAuthenticated)
{
@Html.Partial("_FollowPerson", Model)
@Html.Partial("_AccountFollowedPublicLists", Model)
}
}
@Html.Partial("_ViewPostList", Model.PersonalList.PostsAfter(DateTime.MinValue, 10)) | bsd-3-clause | C# |
83d2558acac1ea15270f5b37a871136ba86d84fb | Implement Equals for ImmutableSolidColorBrush. | akrisiun/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.Visuals/Media/Immutable/ImmutableSolidColorBrush.cs | src/Avalonia.Visuals/Media/Immutable/ImmutableSolidColorBrush.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
namespace Avalonia.Media.Immutable
{
/// <summary>
/// Fills an area with a solid color.
/// </summary>
public readonly struct ImmutableSolidColorBrush : ISolidColorBrush, IEquatable<ImmutableSolidColorBrush>
{
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSolidColorBrush"/> class.
/// </summary>
/// <param name="color">The color to use.</param>
/// <param name="opacity">The opacity of the brush.</param>
public ImmutableSolidColorBrush(Color color, double opacity = 1)
{
Color = color;
Opacity = opacity;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSolidColorBrush"/> class.
/// </summary>
/// <param name="color">The color to use.</param>
public ImmutableSolidColorBrush(uint color)
: this(Color.FromUInt32(color))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSolidColorBrush"/> class.
/// </summary>
/// <param name="source">The brush from which this brush's properties should be copied.</param>
public ImmutableSolidColorBrush(ISolidColorBrush source)
: this(source.Color, source.Opacity)
{
}
/// <summary>
/// Gets the color of the brush.
/// </summary>
public Color Color { get; }
/// <summary>
/// Gets the opacity of the brush.
/// </summary>
public double Opacity { get; }
public bool Equals(ImmutableSolidColorBrush other)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
return Color == other.Color && Opacity == other.Opacity;
}
public override bool Equals(object obj)
{
return obj is ImmutableSolidColorBrush other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return (Color.GetHashCode() * 397) ^ Opacity.GetHashCode();
}
}
public static bool operator ==(ImmutableSolidColorBrush left, ImmutableSolidColorBrush right)
{
return left.Equals(right);
}
public static bool operator !=(ImmutableSolidColorBrush left, ImmutableSolidColorBrush right)
{
return !left.Equals(right);
}
/// <summary>
/// Returns a string representation of the brush.
/// </summary>
/// <returns>A string representation of the brush.</returns>
public override string ToString()
{
return Color.ToString();
}
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
namespace Avalonia.Media.Immutable
{
/// <summary>
/// Fills an area with a solid color.
/// </summary>
public readonly struct ImmutableSolidColorBrush : ISolidColorBrush
{
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSolidColorBrush"/> class.
/// </summary>
/// <param name="color">The color to use.</param>
/// <param name="opacity">The opacity of the brush.</param>
public ImmutableSolidColorBrush(Color color, double opacity = 1)
{
Color = color;
Opacity = opacity;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSolidColorBrush"/> class.
/// </summary>
/// <param name="color">The color to use.</param>
public ImmutableSolidColorBrush(uint color)
: this(Color.FromUInt32(color))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSolidColorBrush"/> class.
/// </summary>
/// <param name="source">The brush from which this brush's properties should be copied.</param>
public ImmutableSolidColorBrush(ISolidColorBrush source)
: this(source.Color, source.Opacity)
{
}
/// <summary>
/// Gets the color of the brush.
/// </summary>
public Color Color { get; }
/// <summary>
/// Gets the opacity of the brush.
/// </summary>
public double Opacity { get; }
/// <summary>
/// Returns a string representation of the brush.
/// </summary>
/// <returns>A string representation of the brush.</returns>
public override string ToString()
{
return Color.ToString();
}
}
}
| mit | C# |
5897fb217d1d913d2acf843f4dc950d358b90f17 | remove xunit 1.x namespace | MehdiK/Humanizer,Flatlineato/Humanizer,jaxx-rep/Humanizer,Flatlineato/Humanizer,hazzik/Humanizer,aloisdg/Humanizer | src/Humanizer.Tests/Localisation/es/NumberToWordsFeminineTest.cs | src/Humanizer.Tests/Localisation/es/NumberToWordsFeminineTest.cs | using Xunit;
namespace Humanizer.Tests.Localisation.es
{
public class NumberToWordsFeminineTests : AmbientCulture
{
public NumberToWordsFeminineTests() : base("es-ES") { }
[Theory]
[InlineData(1, "una")]
[InlineData(21, "veintiuna")]
[InlineData(31, "treinta y una")]
[InlineData(81, "ochenta y una")]
[InlineData(500, "quinientas")]
[InlineData(701, "setecientas una")]
[InlineData(3500, "tres mil quinientas")]
[InlineData(200121, "doscientas mil ciento veintiuna")]
[InlineData(200000121, "doscientos millones ciento veintiuna")]
[InlineData(1000001, "un millón una")]
public void ToWords(int number, string expected)
{
Assert.Equal(expected, number.ToWords(GrammaticalGender.Feminine));
}
}
}
| using Xunit;
using Xunit.Extensions;
namespace Humanizer.Tests.Localisation.es
{
public class NumberToWordsFeminineTests : AmbientCulture
{
public NumberToWordsFeminineTests() : base("es-ES") { }
[Theory]
[InlineData(1, "una")]
[InlineData(21, "veintiuna")]
[InlineData(31, "treinta y una")]
[InlineData(81, "ochenta y una")]
[InlineData(500, "quinientas")]
[InlineData(701, "setecientas una")]
[InlineData(3500, "tres mil quinientas")]
[InlineData(200121, "doscientas mil ciento veintiuna")]
[InlineData(200000121, "doscientos millones ciento veintiuna")]
[InlineData(1000001, "un millón una")]
public void ToWords(int number, string expected)
{
Assert.Equal(expected, number.ToWords(GrammaticalGender.Feminine));
}
}
}
| mit | C# |
2731be1739ee2c126f55ce85408b4d5b023776ad | Change test method to async | kiyoaki/JpPublicHolidays.NET | JpPublicHolidays.Test/PublicHolidaysApiTest.cs | JpPublicHolidays.Test/PublicHolidaysApiTest.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PublicHolidays.Test
{
[TestClass]
public class PublicHolidaysApiTest
{
[TestMethod]
public async Task TestGet()
{
var holidays = await JpPublicHolidays.PublicHolidays.Get();
Assert.IsTrue(holidays.Length >= 20);
var day = holidays.FirstOrDefault(x => x.Date == new DateTime(DateTime.Now.Year, 1, 1));
Assert.IsNotNull(day);
Assert.AreEqual(day.Name, "元日");
}
}
}
| using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PublicHolidays.Test
{
[TestClass]
public class PublicHolidaysApiTest
{
[TestMethod]
public void TestGet()
{
var holidays = JpPublicHolidays.PublicHolidays.Get().Result;
Assert.IsTrue(holidays.Length >= 20);
var day = holidays.FirstOrDefault(x => x.Date == new DateTime(DateTime.Now.Year, 1, 1));
Assert.IsNotNull(day);
Assert.AreEqual(day.Name, "元日");
}
}
}
| mit | C# |
060fb19a6dc4339593c97705b402ecfcb8060947 | Update NativeImageJsonConverter.cs | ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET | ElectronNET.API/Entities/NativeImageJsonConverter.cs | ElectronNET.API/Entities/NativeImageJsonConverter.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Newtonsoft.Json;
namespace ElectronNET.API.Entities
{
internal class NativeImageJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is NativeImage nativeImage)
{
var scaledImages = nativeImage.GetAllScaledImages();
serializer.Serialize(writer, scaledImages);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var dict = serializer.Deserialize<Dictionary<string, string>>(reader);
var newDictionary = new Dictionary<float, Image>();
foreach (var item in dict)
{
if (float.TryParse(item.Key, out var size))
{
var bytes = Convert.FromBase64String(item.Value);
newDictionary.Add(size, Image.FromStream(new MemoryStream(bytes)));
}
}
return new NativeImage(newDictionary);
}
public override bool CanConvert(Type objectType) => objectType == typeof(NativeImage);
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Newtonsoft.Json;
namespace ElectronNET.API.Entities
{
internal class NativeImageJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is NativeImage nativeImage)
{
var scaledImages = nativeImage.GetAllScaledImages();
serializer.Serialize(writer, scaledImages);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var dict = serializer.Deserialize<Dictionary<float, string>>(reader);
var newDictionary = new Dictionary<float, Image>();
foreach (var item in dict)
{
var bytes = Convert.FromBase64String(item.Value);
newDictionary.Add(item.Key, Image.FromStream(new MemoryStream(bytes)));
}
return new NativeImage(newDictionary);
}
public override bool CanConvert(Type objectType) => objectType == typeof(NativeImage);
}
}
| mit | C# |
ad31476ee2c1708b3f35417d65f06dd30cfc7226 | Apply suggestions from code review | StephenHodgson/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/_Core/Services/BaseExtensionService.cs | Assets/MixedRealityToolkit/_Core/Services/BaseExtensionService.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//using Microsoft.MixedReality.Toolkit.Core.Definitions;
using Microsoft.MixedReality.Toolkit.Core.Interfaces;
namespace Microsoft.MixedReality.Toolkit.Core.Services
{
/// <summary>
/// The base extension service implements <see cref="IMixedRealityExtensionService"/> and provides default properties for all extension services.
/// </summary>
/// <remarks>
/// Empty, but reserved for future use, in case additional <see cref="IMixedRealityExtensionService"/> properties or methods are assigned.
/// </remarks>
public abstract class BaseExtensionService : BaseServiceWithConstructor, IMixedRealityExtensionService
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name"></param>
/// <param name="priority"></param>
/// TODO Uncomment out profile after spatial observer and controller data provider refactor.
public BaseExtensionService(string name, uint priority/*, BaseMixedRealityExtensionServiceProfile profile*/) : base(name, priority) { }
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//using Microsoft.MixedReality.Toolkit.Core.Definitions;
using Microsoft.MixedReality.Toolkit.Core.Interfaces;
namespace Microsoft.MixedReality.Toolkit.Core.Services
{
/// <summary>
/// The base extension service implements <see cref="IMixedRealityExtensionService"/> and provides default properties for all extension services.
/// </summary>
/// <remarks>
/// Empty, but reserved for future use, in case additional <see cref="IMixedRealityExtensionService"/> properties or methods are assigned.
/// </remarks>
public abstract class BaseExtensionService : BaseServiceWithConstructor, IMixedRealityExtensionService
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name"></param>
/// <param name="priority"></param>
/// TODO Uncomment out profile after controller data provider refactor.
public BaseExtensionService(string name, uint priority/*, BaseMixedRealityExtensionServiceProfile profile*/) : base(name, priority) { }
}
} | mit | C# |
42e9e8d795cfa7e53f271697b87a65aa6787de6a | Implement some actions for Admins. | enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api | Infopulse.EDemocracy.Data/Repositories/PetitionAdminRepository.cs | Infopulse.EDemocracy.Data/Repositories/PetitionAdminRepository.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Infopulse.EDemocracy.Data.Interfaces;
using Infopulse.EDemocracy.Model;
using Infopulse.EDemocracy.Model.ClientEntities.Search;
using Infopulse.EDemocracy.Model.Enum;
namespace Infopulse.EDemocracy.Data.Repositories
{
public class PetitionAdminRepository : PetitionRepository, IPetitionAdminRepository
{
public IEnumerable<Petition> GetPetitionForAdmin(SearchParameters searchParameters)
{
if (searchParameters == null) searchParameters = new SearchParameters();
searchParameters.SetEmptyValues();
var orderBy = $"{searchParameters.OrderBy} {searchParameters.OrderDirection}";
//var petitions = this.Get(searchParameters, true);
using (var db = new EDEntities())
{
var petitions = db.Petitions
.Include(p => p.Approver)
.Include(p => p.Approver.UserDetails)
.Include(p => p.Approver.UserDetails.Select(ud => ud.User))
.Include(p => p.Author)
.Include(p => p.Author.UserDetails)
.Include(p => p.Organization)
.Include(p => p.Category)
.Include(p => p.Category.EntityGroup)
.Include(p => p.PetitionLevel)
.Include(p => p.PetitionStatus);
if (orderBy.Equals("ID ASC", StringComparison.InvariantCultureIgnoreCase))
petitions = petitions.OrderBy(p => p.ID);
else if (orderBy.Equals("ID DESC", StringComparison.InvariantCultureIgnoreCase))
petitions = petitions.OrderByDescending(p => p.ID);
else if (orderBy.Equals("CreatedDate ASC", StringComparison.InvariantCultureIgnoreCase))
petitions = petitions.OrderBy(p => p.CreatedDate);
else if (orderBy.Equals("CreatedDate DESC", StringComparison.InvariantCultureIgnoreCase))
petitions = petitions.OrderByDescending(p => p.CreatedDate);
else if (orderBy.Equals("Approver ASC", StringComparison.InvariantCultureIgnoreCase))
petitions = petitions.OrderBy(p => p.Approver.Email);
else if (orderBy.Equals("Approver DESC", StringComparison.InvariantCultureIgnoreCase))
petitions = petitions.OrderByDescending(p => p.Approver.Email);
return petitions
.Skip(searchParameters.PageSize.Value * (searchParameters.PageNumber.Value - 1))
.Take(searchParameters.PageSize.Value)
.ToList();
}
}
public void AssignApprover(int userID, IEnumerable<long> petitionIDs)
{
using (var db = new EDEntities())
{
var petitions = db.Petitions.Where(p => petitionIDs.Contains(p.ID));
foreach (var petition in petitions)
{
petition.ApprovedBy = userID;
petition.PetitionStatusID = (int)PetitionStatusEnum.Moderation;
}
db.SaveChanges();
}
}
public void ApprovePetitions(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
public void RejectPetitions(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
public void EscalatePetitions(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
}
} | using System.Collections.Generic;
using Infopulse.EDemocracy.Data.Interfaces;
using Infopulse.EDemocracy.Model;
using Infopulse.EDemocracy.Model.ClientEntities.Search;
namespace Infopulse.EDemocracy.Data.Repositories
{
public class PetitionAdminRepository : PetitionRepository, IPetitionAdminRepository
{
public IEnumerable<Petition> GetPetitionForAdmin(SearchParameters searchParameters)
{
var petitions = this.Get(searchParameters, true);
return petitions;
}
public void AssignApprover(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
public void ApprovePetitions(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
public void RejectPetitions(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
public void EscalatePetitions(int userID, IEnumerable<long> petitionIDs)
{
throw new System.NotImplementedException();
}
}
} | cc0-1.0 | C# |
b743d72c6804e31ce8359317315fe4868be8893d | Update the version to 1.6 | ladimolnar/BitcoinDatabaseGenerator | Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs | Sources/BitcoinDatabaseGenerator/Properties/AssemblyInfo.cs | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
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("BitcoinDatabaseGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitcoinDatabaseGenerator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("372a7f52-b038-43aa-a42c-3ff0ecab1124")]
// 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.6.0.0")]
[assembly: AssemblyFileVersion("1.6.0.0")]
| //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
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("BitcoinDatabaseGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BitcoinDatabaseGenerator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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("372a7f52-b038-43aa-a42c-3ff0ecab1124")]
// 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")]
| apache-2.0 | C# |
264c4912a89c1a1fded802832fb7d00b54743dd6 | Update CurrencyUnionRedirectionOptions.cs | tiksn/TIKSN-Framework | TIKSN.Core/Globalization/CurrencyUnionRedirectionOptions.cs | TIKSN.Core/Globalization/CurrencyUnionRedirectionOptions.cs | using System.Collections.Generic;
namespace TIKSN.Globalization
{
public class CurrencyUnionRedirectionOptions
{
public CurrencyUnionRedirectionOptions() =>
this.CurrencyUnionRedirections = new Dictionary<string, string>
{
{"GGP", "en-GB" /*"en-GG"*/},
{"JEP", "en-GB" /*"en-JE"*/},
{"IMP", "en-GB" /*"en-IM"*/},
{"FKP", "en-GB"},
{"GIP", "en-GB"},
{"SHP", "en-GB"}
};
public Dictionary<string, string> CurrencyUnionRedirections { get; set; }
}
}
| using System.Collections.Generic;
namespace TIKSN.Globalization
{
public class CurrencyUnionRedirectionOptions
{
public CurrencyUnionRedirectionOptions()
{
CurrencyUnionRedirections = new Dictionary<string, string>
{
{ "GGP", "en-GB" /*"en-GG"*/},
{ "JEP", "en-GB" /*"en-JE"*/},
{ "IMP", "en-GB" /*"en-IM"*/},
{ "FKP", "en-GB"},
{ "GIP", "en-GB"},
{ "SHP", "en-GB"}
};
}
public Dictionary<string, string> CurrencyUnionRedirections { get; set; }
}
} | mit | C# |
cc1a17ff1887d28d8e0ea061ad66301501085431 | Optimize WaitForSecondsWithCancel changes | CaitSith2/KtaneTwitchPlays,samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/Helpers/WaitForSecondsWithCancel.cs | TwitchPlaysAssembly/Src/Helpers/WaitForSecondsWithCancel.cs | using UnityEngine;
public static class CoroutineCanceller
{
public static void SetCancel()
{
ShouldCancel = true;
}
public static void ResetCancel()
{
ShouldCancel = false;
}
public static bool ShouldCancel
{
get;
private set;
}
}
public class WaitForSecondsWithCancel : CustomYieldInstruction
{
public WaitForSecondsWithCancel(float seconds, bool resetCancel=true, ComponentSolver solver=null)
{
_seconds = seconds;
_startingTime = Time.time;
_resetCancel = resetCancel;
_solver = solver;
_startingStrikes = _solver?.StrikeCount ?? 0;
}
public override bool keepWaiting
{
get
{
if (!CoroutineCanceller.ShouldCancel && !(_solver?.Solved ?? false) && (_solver?.StrikeCount ?? 0) == _startingStrikes)
return (Time.time - _startingTime) < _seconds;
if(CoroutineCanceller.ShouldCancel && _resetCancel)
CoroutineCanceller.ResetCancel();
return false;
}
}
private readonly float _seconds = 0.0f;
private readonly float _startingTime = 0.0f;
private readonly bool _resetCancel = true;
private readonly int _startingStrikes = 0;
private readonly ComponentSolver _solver = null;
}
| using UnityEngine;
public static class CoroutineCanceller
{
public static void SetCancel()
{
ShouldCancel = true;
}
public static void ResetCancel()
{
ShouldCancel = false;
}
public static bool ShouldCancel
{
get;
private set;
}
}
public class WaitForSecondsWithCancel : CustomYieldInstruction
{
public WaitForSecondsWithCancel(float seconds, bool resetCancel=true, ComponentSolver solver=null)
{
_seconds = seconds;
_startingTime = Time.time;
_resetCancel = resetCancel;
_solver = solver;
_startingStrikes = _solver?.StrikeCount ?? 0;
}
public override bool keepWaiting
{
get
{
int currentStrikes = _solver?.StrikeCount ?? 0;
if (!CoroutineCanceller.ShouldCancel && !(_solver?.Solved ?? false) && currentStrikes == _startingStrikes)
return (Time.time - _startingTime) < _seconds;
if (!CoroutineCanceller.ShouldCancel)
return false;
if(_resetCancel)
CoroutineCanceller.ResetCancel();
return false;
}
}
private readonly float _seconds = 0.0f;
private readonly float _startingTime = 0.0f;
private readonly bool _resetCancel = true;
private readonly int _startingStrikes = 0;
private readonly ComponentSolver _solver = null;
}
| mit | C# |
46133b58a4eb3f92b9feed4719ea072247a1f131 | Refactor LambdaExpressionGenerator for better readability | sean-gilliam/AutoFixture,zvirja/AutoFixture,Pvlerick/AutoFixture,AutoFixture/AutoFixture | Src/AutoFixture/LambdaExpressionGenerator.cs | Src/AutoFixture/LambdaExpressionGenerator.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoFixture.Kernel;
namespace AutoFixture
{
/// <summary>
/// Creates new lambda expressions represented by the <see cref="Expression{TDelegate}"/> type.
/// </summary>
/// <remarks>
/// Specimens are typically either of type <see>
/// <cref>Expression{Func{T}}</cref>
/// </see>
/// or <see cref="Expression{Action}"/>.
/// </remarks>
public class LambdaExpressionGenerator : ISpecimenBuilder
{
/// <summary>
/// Creates a new lambda expression represented by the <see cref="Expression{TDelegate}"/> type.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">Not used.</param>
/// <returns>
/// A new <see cref="Expression{TDelegate}"/> instance, if <paramref name="request"/> is a request for a
/// <see cref="Expression{TDelegate}"/>; otherwise, a <see cref="NoSpecimen"/> instance.
/// </returns>
public object Create(object request, ISpecimenContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var requestType = request as Type;
if (requestType == null)
return new NoSpecimen();
if (requestType.BaseType() != typeof(LambdaExpression))
return new NoSpecimen();
var delegateType = requestType.GetTypeInfo().GetGenericArguments().Single();
var genericArguments = delegateType.GetTypeInfo()
.GetGenericArguments()
.Select(Expression.Parameter)
.ToList();
if (delegateType == typeof(Action))
{
return Expression.Lambda(Expression.Empty());
}
if (delegateType.FullName.StartsWith("System.Action`", StringComparison.Ordinal))
{
return Expression.Lambda(Expression.Empty(), genericArguments);
}
var body = context.Resolve(delegateType.GetTypeInfo().GetGenericArguments().Last());
var parameters = genericArguments.Except(new[] { genericArguments.Last() });
return Expression.Lambda(Expression.Constant(body), parameters);
}
}
} | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoFixture.Kernel;
namespace AutoFixture
{
/// <summary>
/// Creates new lambda expressions represented by the <see cref="Expression{TDelegate}"/> type.
/// </summary>
/// <remarks>
/// Specimens are typically either of type <see>
/// <cref>Expression{Func{T}}</cref>
/// </see>
/// or <see cref="Expression{Action}"/>.
/// </remarks>
public class LambdaExpressionGenerator : ISpecimenBuilder
{
/// <summary>
/// Creates a new lambda expression represented by the <see cref="Expression{TDelegate}"/> type.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">Not used.</param>
/// <returns>
/// A new <see cref="Expression{TDelegate}"/> instance, if <paramref name="request"/> is a request for a
/// <see cref="Expression{TDelegate}"/>; otherwise, a <see cref="NoSpecimen"/> instance.
/// </returns>
public object Create(object request, ISpecimenContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var requestType = request as Type;
if (requestType == null)
{
return new NoSpecimen();
}
if (requestType.BaseType() != typeof(LambdaExpression))
{
return new NoSpecimen();
}
var delegateType = requestType.GetTypeInfo().GetGenericArguments().Single();
var genericArguments = delegateType.GetTypeInfo().GetGenericArguments().Select(Expression.Parameter).ToList();
if (delegateType == typeof(Action))
{
return Expression.Lambda(Expression.Empty());
}
if (delegateType.FullName.StartsWith("System.Action`", StringComparison.Ordinal))
{
return Expression.Lambda(Expression.Empty(), genericArguments);
}
var body = context.Resolve(delegateType.GetTypeInfo().GetGenericArguments().Last());
var parameters = genericArguments.Except(new[] { genericArguments.Last() });
return Expression.Lambda(Expression.Constant(body), parameters);
}
}
} | mit | C# |
75ec321303f5025f08f662367302f27bd152f133 | Rework the way DB access is done | codemonkey85/PKMDS-Save-Editor | PKMDS-Save-Editor/PKMDS-Save-Editor/frmMain.cs | PKMDS-Save-Editor/PKMDS-Save-Editor/frmMain.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PKMDS_CS;
namespace PKMDS_Save_Editor
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void loadSaveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Test to make sure the dependencies are working correctly
PKMDS.OpenDB("F:\\Dropbox\\PKMDS Databases\\veekun-pokedex.sqlite");
this.Text = PKMDS.GetPKMName(4, 9);
PKMDS.CloseDB();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PKMDS_CS;
namespace PKMDS_Save_Editor
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void loadSaveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Test to make sure the dependencies are working correctly
//this.Text = PKMDS.GetPKMName(4, 9, "F:\\Dropbox\\PKMDS Databases\\veekun-pokedex.sqlite");
}
}
}
| unlicense | C# |
a940ac69eeb06ef259dc4b5fadd6649c9c99e0a1 | Update ReadonlyDomainRepository.cs | ericburcham/Highway.Data,HighwayFramework/Highway.Data | src/Highway.Data.EntityFramework/Repositories/ReadonlyDomainRepository.cs | src/Highway.Data.EntityFramework/Repositories/ReadonlyDomainRepository.cs | using Highway.Data.EventManagement;
namespace Highway.Data.Repositories
{
public class ReadonlyDomainRepository<T> : ReadonlyRepository, IReadonlyDomainRepository<T>
where T : class, IDomain
{
public ReadonlyDomainRepository(IReadonlyDomainContext<T> context, T domain)
: base(context)
{
var eventManager = new ReadonlyEventManager<T>(this);
if (domain.Events == null)
{
return;
}
foreach (var @event in domain.Events)
{
eventManager.Register(@event);
}
}
public IReadonlyDomainContext<T> DomainContext => (IReadonlyDomainContext<T>)Context;
}
}
| using Highway.Data.EventManagement;
namespace Highway.Data.Repositories
{
public class ReadonlyDomainRepository<T> : ReadonlyRepository, IReadonlyDomainRepository<T>
where T : class, IDomain
{
public ReadonlyDomainRepository(IReadonlyDomainContext<T> context, IDomain domain)
: base(context)
{
var eventManager = new ReadonlyEventManager<T>(this);
if (domain.Events == null)
{
return;
}
foreach (var @event in domain.Events)
{
eventManager.Register(@event);
}
}
public IReadonlyDomainContext<T> DomainContext => (IReadonlyDomainContext<T>)Context;
}
}
| mit | C# |
0f0a14395fc2f6b77080327cd635d7bf807f80d2 | fix compilazione | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.FakePersistance.ExternalAPI/Servizi/ESRI/GetJobId.cs | src/backend/SO115App.FakePersistance.ExternalAPI/Servizi/ESRI/GetJobId.cs | using Microsoft.Extensions.Configuration;
using SO115App.ExternalAPI.Client;
using SO115App.Models.Classi.ESRI;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.ESRI;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
namespace SO115App.ExternalAPI.Fake.Servizi.ESRI
{
public class GetJobId : IGetJobId
{
private readonly IHttpRequestManager<ESRI_JobId> _client;
private readonly IConfiguration _config;
public GetJobId(IHttpRequestManager<ESRI_JobId> client, IConfiguration config)
{
_client = client;
_config = config;
}
public async Task<string> Get(string token, ESRI_DistanzaTempoMezzi obj)
{
try
{
var url = new Uri(_config.GetSection("ESRI").GetSection("URLJobId").Value.Replace("{token}", token));
var json = JsonSerializer.Serialize(obj);
var result = _client.PostAsync(url, new StringContent(json)).Result;
return result.jobId;
}
catch (Exception e)
{
throw new Exception("Errore servizio ESRI (GetJobId)");
}
}
}
}
| using Microsoft.Extensions.Configuration;
using SO115App.ExternalAPI.Client;
using SO115App.Models.Classi.ESRI;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.ESRI;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
namespace SO115App.ExternalAPI.Fake.Servizi.ESRI
{
public class GetJobId : IGetJobId
{
private readonly IHttpRequestManager<ESRI_JobId> _client;
private readonly IConfiguration _config;
public GetJobId(IHttpRequestManager<ESRI_JobId> client, IConfiguration config)
{
_client = client;
_config = config;
}
public async Task<string> Get(string token, ESRI_DistanzaTempoMezzi obj)
{
try
{
var url = new Uri(_config.GetSection("ESRI").GetSection("URLJobId").Value.Replace("{token}", token));
var json = JsonSerializer.Serialize(obj);
var result = _client.PostAsync(url, new StringContent(json)).Result;
return result.jobId;
}
catch (Exception e)
{
throw new Exception("Errore servizio ESRI (GetJobId)");
}
}
}
}
| agpl-3.0 | C# |
6585a42b4022f001d399efd5188e1bb4d003998c | Add more RuneTek5Cache tests | villermen/runescape-cache-tools,villermen/runescape-cache-tools | RuneScapeCacheToolsTests/RuneTek5CacheTests.cs | RuneScapeCacheToolsTests/RuneTek5CacheTests.cs | using RuneScapeCacheToolsTests.Fixtures;
using Villermen.RuneScapeCacheTools.Cache;
using Villermen.RuneScapeCacheTools.Cache.RuneTek5;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
[Collection("TestCache")]
public class RuneTek5CacheTests
{
private ITestOutputHelper Output { get; }
private CacheFixture Fixture { get; }
public RuneTek5CacheTests(ITestOutputHelper output, CacheFixture fixture)
{
Output = output;
Fixture = fixture;
}
/// <summary>
/// Test for a file that exists, an archive file that exists and a file that doesn't exist.
/// </summary>
[Fact]
public void TestGetFile()
{
var file = Fixture.RuneTek5Cache.GetFile(12, 3);
var fileData = file.Data;
Assert.True(fileData.Length > 0, "File's data is empty.");
var archiveFile = Fixture.RuneTek5Cache.GetFile(17, 5);
var archiveEntry = archiveFile.Entries[255];
Assert.True(archiveEntry.Length > 0, "Archive entry's data is empty.");
try
{
Fixture.RuneTek5Cache.GetFile(40, 30);
Assert.True(false, "Cache returned a file that shouldn't exist.");
}
catch (CacheException exception)
{
Assert.True(exception.Message.Contains("incomplete"), "Non-existent file cache exception had the wrong message.");
}
}
[Fact]
public void TestGetReferenceTable()
{
Fixture.RuneTek5Cache.GetReferenceTable(40);
}
[Fact(Skip = "Not implemented")]
public void TestGetReferenceTableReferenceTable()
{
Fixture.RuneTek5Cache.GetReferenceTable(RuneTek5Cache.MetadataIndexId);
}
}
} | using RuneScapeCacheToolsTests.Fixtures;
using Villermen.RuneScapeCacheTools.Cache;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
[Collection("TestCache")]
public class RuneTek5CacheTests
{
private readonly ITestOutputHelper _output;
private readonly CacheFixture _fixture;
public RuneTek5CacheTests(ITestOutputHelper output, CacheFixture fixture)
{
_output = output;
_fixture = fixture;
}
/// <summary>
/// Test for a file that exists, an archive file that exists and a file that doesn't exist.
/// </summary>
[Fact]
public void TestGetFile()
{
var file = _fixture.RuneTek5Cache.GetFile(12, 3);
var fileData = file.Data;
Assert.True(fileData.Length > 0, "File's data is empty.");
var archiveFile = _fixture.RuneTek5Cache.GetFile(17, 5);
var archiveEntry = archiveFile.Entries[255];
Assert.True(archiveEntry.Length > 0, "Archive entry's data is empty.");
try
{
_fixture.RuneTek5Cache.GetFile(40, 30);
Assert.True(false, "Cache returned a file that shouldn't exist.");
}
catch (CacheException exception)
{
Assert.True(exception.Message.Contains("incomplete"), "Non-existent file cache exception had the wrong message.");
}
}
}
} | mit | C# |
be6ea2cb2fcb09ee6da00de9fe28622d0d591cb7 | Bump version and simplify | mj1856/SimpleImpersonation | SimpleImpersonation/Properties/AssemblyInfo.cs | SimpleImpersonation/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SimpleImpersonation")]
[assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")]
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Simple Impersonation")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.1.0.*")]
[assembly: AssemblyInformationalVersion("1.1.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SimpleImpersonation")]
[assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")]
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Simple Impersonation")]
[assembly: AssemblyCopyright("Copyright © 2013, Matt Johnson")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1.2")]
[assembly: AssemblyInformationalVersion("1.0.1")]
| mit | C# |
3532b092c05dc9a1ae69efcb41ecc0b9eb0d338a | Remove call to App.Invoke | lytico/xwt,sevoku/xwt,mminns/xwt,hwthomas/xwt,mminns/xwt,steffenWi/xwt,directhex/xwt,mono/xwt,cra0zy/xwt,residuum/xwt,TheBrainTech/xwt,antmicro/xwt,iainx/xwt,hamekoz/xwt,akrisiun/xwt | Xwt.Gtk/Xwt.GtkBackend/ProgressBarBackend.cs | Xwt.Gtk/Xwt.GtkBackend/ProgressBarBackend.cs | //
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <knocte@gmail.com>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// 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.Timers;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
public ProgressBarBackend ()
{
}
uint? timerId = null;
public override void Initialize ()
{
var progressBar = new Gtk.ProgressBar ();
Widget = progressBar;
Widget.Show ();
}
private bool Pulse ()
{
Widget.Pulse ();
return true;
}
protected new Gtk.ProgressBar Widget {
get { return (Gtk.ProgressBar)base.Widget; }
set { base.Widget = value; }
}
public void SetIndeterminate (bool value) {
if (value) {
if (timerId != null)
return;
timerId = GLib.Timeout.Add (100, Pulse);
} else {
if (timerId == null)
return;
DisposeTimeout ();
}
}
public void SetFraction (double fraction)
{
Widget.Fraction = fraction;
}
protected void DisposeTimeout ()
{
if (timerId != null) {
GLib.Source.Remove (timerId.Value);
timerId = null;
}
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
DisposeTimeout ();
}
}
}
| //
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <knocte@gmail.com>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// 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.Timers;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
public ProgressBarBackend ()
{
}
uint? timerId = null;
public override void Initialize ()
{
var progressBar = new Gtk.ProgressBar ();
Widget = progressBar;
Widget.Show ();
}
private bool Pulse ()
{
Application.Invoke (() => Widget.Pulse ());
return true;
}
protected new Gtk.ProgressBar Widget {
get { return (Gtk.ProgressBar)base.Widget; }
set { base.Widget = value; }
}
public void SetIndeterminate (bool value) {
if (value) {
if (timerId != null)
return;
timerId = GLib.Timeout.Add (100, Pulse);
} else {
if (timerId == null)
return;
DisposeTimeout ();
}
}
public void SetFraction (double fraction)
{
Widget.Fraction = fraction;
}
protected void DisposeTimeout ()
{
if (timerId != null) {
GLib.Source.Remove (timerId.Value);
timerId = null;
}
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
DisposeTimeout ();
}
}
}
| mit | C# |
94ff0b6ad14fa51c1368a8ec91372880f6b796ca | Fix SvgImage button overlay demo on Android. | twintechs/TwinTechsFormsLib,patridge/TwinTechsFormsLib | TwinTechsForms/TwinTechsFormsExample/TwinTechs/Example/SvgImageSample/SvgImageSamplePage.cs | TwinTechsForms/TwinTechsFormsExample/TwinTechs/Example/SvgImageSample/SvgImageSamplePage.cs | using System;
using System.Reflection;
using Xamarin.Forms;
using TwinTechs.Controls;
namespace TwinTechs.Example.SvgImageSample
{
public class SvgImageSamplePage : ContentPage
{
readonly SvgImageSamplePageViewModel _ViewModel;
public SvgImageSamplePage ()
{
_ViewModel = new SvgImageSamplePageViewModel();
var insetLabel = new Label();
insetLabel.SetBinding(Label.TextProperty, nameof(SvgImageSamplePageViewModel.SvgInsets), stringFormat: "Stretchable Insets: {0:C2}");
var resourcePicker = new Picker() {
HorizontalOptions = LayoutOptions.FillAndExpand,
};
foreach (var resourceName in SvgImageSamplePageViewModel.AvailableResourceNames) {
resourcePicker.Items.Add(resourceName);
}
resourcePicker.SetBinding(Picker.SelectedIndexProperty, nameof(SvgImageSamplePageViewModel.SvgResourceIndex), BindingMode.TwoWay);
var insetSlider = new Slider() {
Minimum = 0,
Maximum = 35,
Value = _ViewModel.AllSidesInset,
};
insetSlider.SetBinding(Slider.ValueProperty, nameof(SvgImageSamplePageViewModel.AllSidesInset), BindingMode.TwoWay);
var slicingSvg = new SvgImage() {
SvgAssembly = typeof(App).GetTypeInfo().Assembly,
WidthRequest = 300,
HeightRequest = 300,
};
slicingSvg.SetBinding(SvgImage.SvgStretchableInsetsProperty, nameof(SvgImageSamplePageViewModel.SvgInsets));
slicingSvg.SetBinding(SvgImage.SvgPathProperty, nameof(SvgImageSamplePageViewModel.SvgResourcePath));
var svgButton = new Button() {
WidthRequest = 300,
HeightRequest = 300,
BackgroundColor = Color.Transparent,
};
// The root page of your application
Title = "9-Slice SVG Scaling";
Content = new StackLayout {
VerticalOptions = LayoutOptions.Start,
HorizontalOptions = LayoutOptions.Center,
Children = {
insetLabel,
resourcePicker,
insetSlider,
new AbsoluteLayout() {
WidthRequest = 300,
HeightRequest = 300,
Children = {
slicingSvg,
svgButton,
},
},
},
BindingContext = _ViewModel,
};
svgButton.Clicked += (sender, e) => {
DisplayAlert("Tapped!", "SVG button tapped!", "OK");
};
}
}
}
| using System;
using System.Reflection;
using Xamarin.Forms;
using TwinTechs.Controls;
namespace TwinTechs.Example.SvgImageSample
{
public class SvgImageSamplePage : ContentPage
{
readonly SvgImageSamplePageViewModel _ViewModel;
public SvgImageSamplePage ()
{
_ViewModel = new SvgImageSamplePageViewModel();
var insetLabel = new Label();
insetLabel.SetBinding(Label.TextProperty, nameof(SvgImageSamplePageViewModel.SvgInsets), stringFormat: "Stretchable Insets: {0:C2}");
var resourcePicker = new Picker() {
HorizontalOptions = LayoutOptions.FillAndExpand,
};
foreach (var resourceName in SvgImageSamplePageViewModel.AvailableResourceNames) {
resourcePicker.Items.Add(resourceName);
}
resourcePicker.SetBinding(Picker.SelectedIndexProperty, nameof(SvgImageSamplePageViewModel.SvgResourceIndex), BindingMode.TwoWay);
var insetSlider = new Slider() {
Minimum = 0,
Maximum = 35,
Value = _ViewModel.AllSidesInset,
};
insetSlider.SetBinding(Slider.ValueProperty, nameof(SvgImageSamplePageViewModel.AllSidesInset), BindingMode.TwoWay);
var slicingSvg = new SvgImage() {
SvgAssembly = typeof(App).GetTypeInfo().Assembly,
WidthRequest = 300,
HeightRequest = 300,
};
slicingSvg.SetBinding(SvgImage.SvgStretchableInsetsProperty, nameof(SvgImageSamplePageViewModel.SvgInsets));
slicingSvg.SetBinding(SvgImage.SvgPathProperty, nameof(SvgImageSamplePageViewModel.SvgResourcePath));
var svgButton = new Button() {
WidthRequest = 300,
HeightRequest = 300,
};
// The root page of your application
Title = "9-Slice SVG Scaling";
Content = new StackLayout {
VerticalOptions = LayoutOptions.Start,
HorizontalOptions = LayoutOptions.Center,
Children = {
insetLabel,
resourcePicker,
insetSlider,
new AbsoluteLayout() {
WidthRequest = 300,
HeightRequest = 300,
Children = {
slicingSvg,
svgButton,
},
},
},
BindingContext = _ViewModel,
};
svgButton.Clicked += (sender, e) => {
DisplayAlert("Tapped!", "SVG button tapped!", "OK");
};
}
}
}
| apache-2.0 | C# |
469bd1b28fe530e77093fdbe42923f37f6949bf4 | Include work from #802 | Redth/ZXing.Net.Mobile | ZXing.Net.Mobile/MacOS/BitmapRenderer.macos.cs | ZXing.Net.Mobile/MacOS/BitmapRenderer.macos.cs | using System;
using ZXing.Rendering;
using Foundation;
using CoreFoundation;
using CoreGraphics;
using AppKit;
using ZXing.Common;
namespace ZXing.Mobile
{
public class BitmapRenderer : IBarcodeRenderer<NSImage>
{
public NSImage Render(BitMatrix matrix, BarcodeFormat format, string content)
{
return Render(matrix, format, content, new EncodingOptions());
}
public NSImage Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
{
var context = new CGBitmapContext(null, matrix.Width, matrix.Height, 8, 0, CGColorSpace.CreateGenericGray(), CGBitmapFlags.None);
var black = new CGColor(0f, 0f, 0f);
var white = new CGColor(1.0f, 1.0f, 1.0f);
for (var x = 0; x < matrix.Width; x++)
{
for (var y = 0; y < matrix.Height; y++)
{
var (cgX, cgY) = TransformToCoreGraphicsCoords(x, y, matrix);
context.SetFillColor(matrix[cgX, cgY] ? black : white);
context.FillRect(new CGRect(x, y, 1, 1));
}
}
var img = new NSImage(context.ToImage(), new CGSize(matrix.Width, matrix.Height));
context.Dispose();
return img;
}
static (int cgX, int cgY) TransformToCoreGraphicsCoords(int x, int y, BitMatrix matrix)
=> (x, Math.Abs(y - matrix.Height + 1));
}
} | using System;
using ZXing.Rendering;
using Foundation;
using CoreFoundation;
using CoreGraphics;
using AppKit;
using ZXing.Common;
namespace ZXing.Mobile
{
public class BitmapRenderer : IBarcodeRenderer<NSImage>
{
public NSImage Render(BitMatrix matrix, BarcodeFormat format, string content)
{
return Render(matrix, format, content, new EncodingOptions());
}
public NSImage Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
{
var context = new CGBitmapContext(null, matrix.Width, matrix.Height, 8, 0, CGColorSpace.CreateGenericGray(), CGBitmapFlags.None);
var black = new CGColor(0f, 0f, 0f);
var white = new CGColor(1.0f, 1.0f, 1.0f);
for (var x = 0; x < matrix.Width; x++)
{
for (var y = 0; y < matrix.Height; y++)
{
context.SetFillColor(matrix[x, y] ? black : white);
context.FillRect(new CGRect(x, y, 1, 1));
}
}
var img = new NSImage(context.ToImage(), new CGSize(matrix.Width, matrix.Height));
context.Dispose();
return img;
}
}
} | apache-2.0 | C# |
5818ed4c8c66bb749a83e700c16fde831ba56b4c | Remove unused DI resolution | smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu | osu.Game/Skinning/LegacyAccuracyCounter.cs | osu.Game/Skinning/LegacyAccuracyCounter.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : GameplayAccuracyCounter, ISkinnableComponent
{
public LegacyAccuracyCounter()
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.6f);
Margin = new MarginPadding(10);
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() => new LegacySpriteText(LegacyFont.Score)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : GameplayAccuracyCounter, ISkinnableComponent
{
[Resolved]
private ISkinSource skin { get; set; }
public LegacyAccuracyCounter()
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.6f);
Margin = new MarginPadding(10);
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() => new LegacySpriteText(LegacyFont.Score)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
}
}
| mit | C# |
322279c9abd719e95e4b6a8c6028c45996fe21ce | handle some invalid error outputs | poxet/tharga-console | Tharga.Toolkit.Console/Helpers/ExceptionExtension.cs | Tharga.Toolkit.Console/Helpers/ExceptionExtension.cs | using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace Tharga.Toolkit.Console.Helpers
{
internal static class ExceptionExtension
{
public static string ToFormattedString(this Exception exception)
{
return ToFormattedString(exception, 0).TrimEnd(Environment.NewLine.ToCharArray());
}
private static string ToFormattedString(this Exception exception, int indentationLevel)
{
var sb = new StringBuilder();
var indentation = new string(' ', indentationLevel * 2);
sb.AppendLine($"{indentation}{exception.Message}");
foreach (DictionaryEntry data in exception.Data)
{
sb.AppendLine($"{indentation}{data.Key}: {data.Value}");
}
if (exception.InnerException != null)
{
sb.AppendLine(exception.InnerException.ToFormattedString(++indentationLevel));
}
try
{
//NOTE: Make it configurable if to include stacktrace or not
sb.AppendLine();
sb.AppendLine("Stack trace:");
var stackTrace = exception.StackTrace.Split(new[] { " at " }, StringSplitOptions.None);
foreach (var line in stackTrace.Where(x => !string.IsNullOrWhiteSpace(x)))
{
var pair = line.Split(new[] { " in " }, StringSplitOptions.None);
if (pair.Length == 2)
{
sb.AppendLine(pair[0].Trim());
sb.AppendLine($" {pair[1].Trim()}");
}
else
sb.AppendLine(line);
}
}
catch (Exception e)
{
//TODO: Oups, unable to parse
}
var result = sb.ToString();
return result;
}
}
} | using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace Tharga.Toolkit.Console.Helpers
{
internal static class ExceptionExtension
{
public static string ToFormattedString(this Exception exception)
{
return ToFormattedString(exception, 0).TrimEnd(Environment.NewLine.ToCharArray());
}
private static string ToFormattedString(this Exception exception, int indentationLevel)
{
var sb = new StringBuilder();
var indentation = new string(' ', indentationLevel * 2);
sb.AppendLine($"{indentation}{exception.Message}");
foreach (DictionaryEntry data in exception.Data)
{
sb.AppendLine($"{indentation}{data.Key}: {data.Value}");
}
if (exception.InnerException != null)
{
sb.AppendLine(exception.InnerException.ToFormattedString(++indentationLevel));
}
//NOTE: Make it configurable if to include stacktrace or not
sb.AppendLine();
sb.AppendLine("Stack trace:");
var stackTrace = exception.StackTrace.Split(new[] { " at " }, StringSplitOptions.None);
foreach (var line in stackTrace.Where(x => !string.IsNullOrWhiteSpace(x)))
{
var pair = line.Split(new[] { " in " }, StringSplitOptions.None);
sb.AppendLine(pair[0].Trim());
sb.AppendLine($" {pair[1].Trim()}");
}
var result = sb.ToString();
return result;
}
}
} | mit | C# |
08d7c2df703bd60b364d43308f0bdb432f79b2e6 | Fix extra hard-rock flipping for sliders | ppy/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,naoey/osu,NeoAdonis/osu,ppy/osu,naoey/osu,smoogipoo/osu,peppy/osu,naoey/osu,peppy/osu,EVAST9919/osu,DrabWeb/osu,2yangk23/osu,peppy/osu,DrabWeb/osu,ZLima12/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,johnneijzen/osu,smoogipooo/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,DrabWeb/osu,smoogipoo/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu | osu.Game.Rulesets.Osu/Mods/OsuModHardRock.cs | osu.Game.Rulesets.Osu/Mods/OsuModHardRock.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModHardRock : ModHardRock, IApplicableToHitObject
{
public override double ScoreMultiplier => 1.06;
public override bool Ranked => true;
public void ApplyToHitObject(HitObject hitObject)
{
var osuObject = (OsuHitObject)hitObject;
osuObject.Position = new Vector2(osuObject.Position.X, OsuPlayfield.BASE_SIZE.Y - osuObject.Y);
var slider = hitObject as Slider;
if (slider == null)
return;
slider.NestedHitObjects.OfType<SliderTick>().ForEach(h => h.Position = new Vector2(h.Position.X, OsuPlayfield.BASE_SIZE.Y - h.Position.Y));
slider.NestedHitObjects.OfType<RepeatPoint>().ForEach(h => h.Position = new Vector2(h.Position.X, OsuPlayfield.BASE_SIZE.Y - h.Position.Y));
var newControlPoints = new Vector2[slider.Path.ControlPoints.Length];
for (int i = 0; i < slider.Path.ControlPoints.Length; i++)
newControlPoints[i] = new Vector2(slider.Path.ControlPoints[i].X, -slider.Path.ControlPoints[i].Y);
slider.Path = new SliderPath(slider.Path.Type, newControlPoints, slider.Path.ExpectedDistance);
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModHardRock : ModHardRock, IApplicableToHitObject
{
public override double ScoreMultiplier => 1.06;
public override bool Ranked => true;
public void ApplyToHitObject(HitObject hitObject)
{
var osuObject = (OsuHitObject)hitObject;
osuObject.Position = new Vector2(osuObject.Position.X, OsuPlayfield.BASE_SIZE.Y - osuObject.Y);
var slider = hitObject as Slider;
if (slider == null)
return;
slider.HeadCircle.Position = new Vector2(slider.HeadCircle.Position.X, OsuPlayfield.BASE_SIZE.Y - slider.HeadCircle.Position.Y);
slider.TailCircle.Position = new Vector2(slider.TailCircle.Position.X, OsuPlayfield.BASE_SIZE.Y - slider.TailCircle.Position.Y);
slider.NestedHitObjects.OfType<SliderTick>().ForEach(h => h.Position = new Vector2(h.Position.X, OsuPlayfield.BASE_SIZE.Y - h.Position.Y));
slider.NestedHitObjects.OfType<RepeatPoint>().ForEach(h => h.Position = new Vector2(h.Position.X, OsuPlayfield.BASE_SIZE.Y - h.Position.Y));
var newControlPoints = new Vector2[slider.Path.ControlPoints.Length];
for (int i = 0; i < slider.Path.ControlPoints.Length; i++)
newControlPoints[i] = new Vector2(slider.Path.ControlPoints[i].X, -slider.Path.ControlPoints[i].Y);
slider.Path = new SliderPath(slider.Path.Type, newControlPoints, slider.Path.ExpectedDistance);
}
}
}
| mit | C# |
b20972d2d812492dbd5c809f67b27b5bb010fdb5 | Add a hang mitigating timeout to CSharpBuild.BuildWithCommandLine | diryboy/roslyn,genlu/roslyn,brettfo/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,brettfo/roslyn,AlekseyTs/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,gafter/roslyn,wvdd007/roslyn,heejaechang/roslyn,weltkante/roslyn,tannergooding/roslyn,stephentoub/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,aelij/roslyn,panopticoncentral/roslyn,aelij/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,eriawan/roslyn,tmat/roslyn,eriawan/roslyn,genlu/roslyn,tmat/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,physhi/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,genlu/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,bartdesmet/roslyn,davkean/roslyn,wvdd007/roslyn,KevinRansom/roslyn,davkean/roslyn,gafter/roslyn,jmarolf/roslyn,davkean/roslyn,sharwell/roslyn,gafter/roslyn,stephentoub/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,diryboy/roslyn,jmarolf/roslyn,dotnet/roslyn,mavasani/roslyn,panopticoncentral/roslyn,weltkante/roslyn,tmat/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,aelij/roslyn,tannergooding/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,stephentoub/roslyn | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpBuild.cs | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpBuild.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.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpBuild : AbstractIntegrationTest
{
public CSharpBuild(VisualStudioInstanceFactory instanceFactory, ITestOutputHelper testOutputHelper)
: base(instanceFactory, testOutputHelper)
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.SolutionExplorer.CreateSolution(nameof(CSharpBuild));
VisualStudio.SolutionExplorer.AddProject(new ProjectUtils.Project("TestProj"), WellKnownProjectTemplates.ConsoleApplication, LanguageNames.CSharp);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Build)]
public void BuildProject()
{
var editorText = @"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
VisualStudio.Editor.SetText(editorText);
// TODO: Validate build works as expected
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Build)]
public void BuildWithCommandLine()
{
VisualStudio.SolutionExplorer.SaveAll();
var pathToDevenv = Path.Combine(VisualStudio.InstallationPath, @"Common7\IDE\devenv.exe");
var pathToSolution = VisualStudio.SolutionExplorer.SolutionFileFullPath;
var logFileName = pathToSolution + ".log";
File.Delete(logFileName);
var commandLine = $"\"{pathToSolution}\" /Rebuild Debug /Out \"{logFileName}\" {VisualStudioInstanceFactory.VsLaunchArgs}";
var process = Process.Start(pathToDevenv, commandLine);
Assert.True(process.WaitForExit((int)Helper.HangMitigatingTimeout.TotalMilliseconds));
Assert.Contains("Rebuild All: 1 succeeded, 0 failed, 0 skipped", File.ReadAllText(logFileName));
Assert.Equal(0, process.ExitCode);
}
}
}
| // 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.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpBuild : AbstractIntegrationTest
{
public CSharpBuild(VisualStudioInstanceFactory instanceFactory, ITestOutputHelper testOutputHelper)
: base(instanceFactory, testOutputHelper)
{
}
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.SolutionExplorer.CreateSolution(nameof(CSharpBuild));
VisualStudio.SolutionExplorer.AddProject(new ProjectUtils.Project("TestProj"), WellKnownProjectTemplates.ConsoleApplication, LanguageNames.CSharp);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Build)]
public void BuildProject()
{
var editorText = @"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
VisualStudio.Editor.SetText(editorText);
// TODO: Validate build works as expected
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Build)]
public void BuildWithCommandLine()
{
VisualStudio.SolutionExplorer.SaveAll();
var pathToDevenv = Path.Combine(VisualStudio.InstallationPath, @"Common7\IDE\devenv.exe");
var pathToSolution = VisualStudio.SolutionExplorer.SolutionFileFullPath;
var logFileName = pathToSolution + ".log";
File.Delete(logFileName);
var commandLine = $"\"{pathToSolution}\" /Rebuild Debug /Out \"{logFileName}\" {VisualStudioInstanceFactory.VsLaunchArgs}";
var process = Process.Start(pathToDevenv, commandLine);
process.WaitForExit();
Assert.Contains("Rebuild All: 1 succeeded, 0 failed, 0 skipped", File.ReadAllText(logFileName));
Assert.Equal(0, process.ExitCode);
}
}
}
| mit | C# |
21b6f8501bfaa28ef51f79a43fe8a30777c74cd9 | Create server side API for single multiple answer question | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
/// <summary>
/// Adding single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| mit | C# |
9567abb6ce15b29cc59ab36c0172d31aa9c661fe | Use dot instead of dash to separate build metadata | ParticularLabs/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,ermshiperete/GitVersion,ParticularLabs/GitVersion,dazinator/GitVersion,dazinator/GitVersion,gep13/GitVersion | build/version.cake | build/version.cake | public class BuildVersion
{
public GitVersion GitVersion { get; private set; }
public string Version { get; private set; }
public string Milestone { get; private set; }
public string SemVersion { get; private set; }
public string GemVersion { get; private set; }
public string VsixVersion { get; private set; }
public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion)
{
var version = gitVersion.MajorMinorPatch;
var semVersion = gitVersion.LegacySemVer;
var vsixVersion = gitVersion.MajorMinorPatch;
if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
semVersion += "." + gitVersion.BuildMetaData;
vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
}
return new BuildVersion
{
GitVersion = gitVersion,
Milestone = version,
Version = version,
SemVersion = semVersion,
GemVersion = semVersion.Replace("-", "."),
VsixVersion = vsixVersion,
};
}
}
| public class BuildVersion
{
public GitVersion GitVersion { get; private set; }
public string Version { get; private set; }
public string Milestone { get; private set; }
public string SemVersion { get; private set; }
public string GemVersion { get; private set; }
public string VsixVersion { get; private set; }
public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion)
{
var version = gitVersion.MajorMinorPatch;
var semVersion = gitVersion.LegacySemVer;
var vsixVersion = gitVersion.MajorMinorPatch;
if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
semVersion += "-" + gitVersion.BuildMetaData;
vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
}
return new BuildVersion
{
GitVersion = gitVersion,
Milestone = version,
Version = version,
SemVersion = semVersion,
GemVersion = semVersion.Replace("-", "."),
VsixVersion = vsixVersion,
};
}
}
| mit | C# |
ad22cb7a014b843189d257d5929c7d89f93b5cc5 | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.31.*")]
| 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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.30.*")]
| mit | C# |
2408d6f4a97defc01d3efd0b221b9f8481d1efaf | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.3.*")]
| 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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.2.*")]
| mit | C# |
e7ef79cd48233d4da90d27bb69eadef6707cf314 | make internals visible to unit test project | dkackman/FakeHttp | MockHttp/Properties/AssemblyInfo.cs | MockHttp/Properties/AssemblyInfo.cs | using System.Resources;
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("MockHttp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MockHttp")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("MockHttp.UnitTests")] | using System.Resources;
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("MockHttp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MockHttp")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
6d1bfed9e4e6169100ac07a4cbb7f41883f46942 | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.32.*")]
| 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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.31.*")]
| mit | C# |
6ed3d86ae24e5e88f1ff19e3fa37c1aba4609946 | Refactor Address equality code | ajlopez/BlockchainSharp | Src/BlockchainSharp/Core/Address.cs | Src/BlockchainSharp/Core/Address.cs | namespace BlockchainSharp.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Address
{
private static Random random = new Random();
private byte[] bytes;
public Address()
{
this.bytes = new byte[20];
random.NextBytes(this.bytes);
}
public Address(byte[] bytes)
{
this.bytes = bytes;
}
public byte[] Bytes { get { return this.bytes; } }
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (!(obj is Address))
return false;
Address h = (Address)obj;
if (this.bytes.Length != h.bytes.Length)
return false;
return this.bytes.SequenceEqual(h.bytes);
}
public override int GetHashCode()
{
int value = 0;
for (int k = 0; k < this.bytes.Length; k++)
{
value += this.bytes[k];
value <<= 1;
}
return value;
}
public override string ToString()
{
return ByteArrayToString(this.bytes);
}
private static string ByteArrayToString(byte[] bytes)
{
StringBuilder hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
}
| namespace BlockchainSharp.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Address
{
private static Random random = new Random();
private byte[] bytes;
public Address()
{
this.bytes = new byte[20];
random.NextBytes(this.bytes);
}
public Address(byte[] bytes)
{
this.bytes = bytes;
}
public byte[] Bytes { get { return this.bytes; } }
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (!(obj is Address))
return false;
Address h = (Address)obj;
if (this.bytes.Length != h.bytes.Length)
return false;
for (int k = 0; k < this.bytes.Length; k++)
if (this.bytes[k] != h.bytes[k])
return false;
return true;
}
public override int GetHashCode()
{
int value = 0;
for (int k = 0; k < this.bytes.Length; k++)
{
value += this.bytes[k];
value <<= 1;
}
return value;
}
public override string ToString()
{
return ByteArrayToString(this.bytes);
}
private static string ByteArrayToString(byte[] bytes)
{
StringBuilder hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
}
| mit | C# |
43a1db3645ecf7c74f22099837d822a12bce3fd7 | Fix preview not updating on TextField with type of "Predefined List" (#3763) | stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,petedavis/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2 | src/OrchardCore.Modules/OrchardCore.ContentFields/Views/TextField-PredefinedList.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.ContentFields/Views/TextField-PredefinedList.Edit.cshtml | @model OrchardCore.ContentFields.ViewModels.EditTextFieldViewModel
@using OrchardCore.ContentFields.Settings
@using OrchardCore.ContentManagement.Metadata.Models
@{
var settings = Model.PartFieldDefinition.Settings.ToObject<TextFieldSettings>();
var listSettings = Model.PartFieldDefinition.GetSettings<TextFieldPredefinedListEditorSettings>();
var options = new List<SelectListItem>();
var selectedValue = String.IsNullOrEmpty(Model.Text) ? listSettings.DefaultValue : Model.Text;
foreach (var option in listSettings.Options)
{
var isSelected = option.Value == selectedValue
|| (String.IsNullOrEmpty(option.Value) && String.IsNullOrEmpty(selectedValue));
options.Add(new SelectListItem { Text = option.Name, Value = option.Value, Selected = isSelected });
}
}
<fieldset class="form-group">
@if (listSettings.Editor == EditorOption.Radio)
{
var i = 0;
<label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label>
@foreach (var option in options)
{
<div class="custom-control custom-radio" asp-for="Text">
@Html.RadioButton("Text", option.Value, option.Selected, new { @class = "custom-control-input content-preview-text", id = Html.IdFor(m => m.Text) + "_" + i })
<label class="custom-control-label" for="@(Html.IdFor(m => m.Text) + "_" + i)">@option.Text</label>
</div>
i++;
}
}
@if (listSettings.Editor == EditorOption.Dropdown)
{
<label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label>
<select class="form-control content-preview-select" asp-for="Text" asp-items="options"></select>
}
@if (!String.IsNullOrEmpty(settings.Hint))
{
<span class="hint">— @settings.Hint</span>
}
</fieldset>
| @model OrchardCore.ContentFields.ViewModels.EditTextFieldViewModel
@using OrchardCore.ContentFields.Settings
@using OrchardCore.ContentManagement.Metadata.Models
@{
var settings = Model.PartFieldDefinition.Settings.ToObject<TextFieldSettings>();
var listSettings = Model.PartFieldDefinition.GetSettings<TextFieldPredefinedListEditorSettings>();
var options = new List<SelectListItem>();
var selectedValue = String.IsNullOrEmpty(Model.Text) ? listSettings.DefaultValue : Model.Text;
foreach (var option in listSettings.Options)
{
var isSelected = option.Value == selectedValue
|| (String.IsNullOrEmpty(option.Value) && String.IsNullOrEmpty(selectedValue));
options.Add(new SelectListItem { Text = option.Name, Value = option.Value, Selected = isSelected });
}
}
<fieldset class="form-group">
@if (listSettings.Editor == EditorOption.Radio)
{
var i = 0;
<label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label>
@foreach (var option in options)
{
<div class="custom-control custom-radio" asp-for="Text">
@Html.RadioButton("Text", option.Value, option.Selected, new { @class = "custom-control-input", id = Html.IdFor(m => m.Text) + "_" + i })
<label class="custom-control-label" for="@(Html.IdFor(m => m.Text) + "_" + i)">@option.Text</label>
</div>
i++;
}
}
@if (listSettings.Editor == EditorOption.Dropdown)
{
<label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label>
<select class="form-control" asp-for="Text" asp-items="options"></select>
}
@if (!String.IsNullOrEmpty(settings.Hint))
{
<span class="hint">— @settings.Hint</span>
}
</fieldset>
| bsd-3-clause | C# |
a34f4909bad85ebdb7777b2fe8a823d879f3c48d | Fix #445 - Update link for cron expression. | Azure/azure-webjobs-sdk-extensions | src/WebJobs.Extensions/Extensions/Timers/TimerTriggerAttribute.cs | src/WebJobs.Extensions/Extensions/Timers/TimerTriggerAttribute.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.Azure.WebJobs.Description;
using Microsoft.Azure.WebJobs.Extensions.Timers;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Attribute used to mark a job function that should be invoked periodically based on
/// a timer schedule. The trigger parameter type must be <see cref="TimerInfo"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Binding]
public sealed class TimerTriggerAttribute : Attribute
{
/// <summary>
/// Constructs a new instance based on the schedule expression passed in.
/// </summary>
/// <param name="scheduleExpression">A schedule expression. This can either be a 6 field crontab expression
/// <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer#cron-expressions"/> or a <see cref="TimeSpan"/>
/// string (e.g. "00:30:00"). On Azure Functions, a TimeSpan string is only supported
/// when running on an App Service Plan.</param>
public TimerTriggerAttribute(string scheduleExpression)
{
ScheduleExpression = scheduleExpression;
UseMonitor = true;
}
/// <summary>
/// Constructs a new instance using the specified <see cref="TimerSchedule"/> type.
/// </summary>
/// <param name="scheduleType">The type of schedule to use.</param>
public TimerTriggerAttribute(Type scheduleType)
{
ScheduleType = scheduleType;
UseMonitor = true;
}
/// <summary>
/// Gets the schedule expression.
/// </summary>
public string ScheduleExpression { get; private set; }
/// <summary>
/// Gets the <see cref="TimerSchedule"/> type.
/// </summary>
public Type ScheduleType { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the schedule should be monitored.
/// Schedule monitoring persists schedule occurrences to aid in ensuring the
/// schedule is maintained correctly even when roles restart.
/// If not set explicitly, this will default to true for schedules that have a recurrence
/// interval greater than 1 minute (i.e., for schedules that occur more than once
/// per minute, persistence will be disabled).
/// </summary>
public bool UseMonitor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the function should be invoked
/// immediately on startup. After the initial startup run, the function will
/// be run on schedule thereafter.
/// </summary>
public bool RunOnStartup { get; set; }
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.Azure.WebJobs.Description;
using Microsoft.Azure.WebJobs.Extensions.Timers;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Attribute used to mark a job function that should be invoked periodically based on
/// a timer schedule. The trigger parameter type must be <see cref="TimerInfo"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
[Binding]
public sealed class TimerTriggerAttribute : Attribute
{
/// <summary>
/// Constructs a new instance based on the schedule expression passed in.
/// </summary>
/// <param name="scheduleExpression">A schedule expression. This can either be a 6 field crontab expression
/// <a href="http://en.wikipedia.org/wiki/Cron#CRON_expression"/> or a <see cref="TimeSpan"/>
/// string (e.g. "00:30:00"). On Azure Functions, a TimeSpan string is only supported
/// when running on an App Service Plan.</param>
public TimerTriggerAttribute(string scheduleExpression)
{
ScheduleExpression = scheduleExpression;
UseMonitor = true;
}
/// <summary>
/// Constructs a new instance using the specified <see cref="TimerSchedule"/> type.
/// </summary>
/// <param name="scheduleType">The type of schedule to use.</param>
public TimerTriggerAttribute(Type scheduleType)
{
ScheduleType = scheduleType;
UseMonitor = true;
}
/// <summary>
/// Gets the schedule expression.
/// </summary>
public string ScheduleExpression { get; private set; }
/// <summary>
/// Gets the <see cref="TimerSchedule"/> type.
/// </summary>
public Type ScheduleType { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the schedule should be monitored.
/// Schedule monitoring persists schedule occurrences to aid in ensuring the
/// schedule is maintained correctly even when roles restart.
/// If not set explicitly, this will default to true for schedules that have a recurrence
/// interval greater than 1 minute (i.e., for schedules that occur more than once
/// per minute, persistence will be disabled).
/// </summary>
public bool UseMonitor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the function should be invoked
/// immediately on startup. After the initial startup run, the function will
/// be run on schedule thereafter.
/// </summary>
public bool RunOnStartup { get; set; }
}
}
| mit | C# |
e527793530d57d0926bb60996400defd0a35e2e4 | Fix title | proyecto26/RestClient | demo/Assets/MainScript.cs | demo/Assets/MainScript.cs | using UnityEngine;
using UnityEditor;
using Models;
using Proyecto26;
using System.Collections.Generic;
public class MainScript : MonoBehaviour {
string basePath = "https://jsonplaceholder.typicode.com";
public void Get(){
// We can add default request headers for all requests
RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ...";
RequestHelper requestOptions = null;
RestClient.GetArray<Post>(new RequestHelper{ url = basePath + "/posts" }).Then(res => {
EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok");
return RestClient.GetArray<Todo>(basePath + "/todos");
}).Then(res => {
EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok");
return RestClient.GetArray<User>(basePath + "/users");
}).Then(res => {
EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok");
// We can add specific options and override default headers for a request
requestOptions = new RequestHelper {
url = basePath + "/photos",
headers = new Dictionary<string, string>{
{ "Authorization", "Other token..." }
}
};
return RestClient.GetArray<Photo>(requestOptions);
}).Then(res => {
EditorUtility.DisplayDialog("Header", requestOptions.GetRequestHeader("Authorization"), "Ok");
// And later we can clean the default headers for all requests
RestClient.CleanDefaultHeaders();
}).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok"));
}
public void Post(){
RestClient.Post<Models.Post>(basePath + "/posts", new {
title = "foo",
body = "bar",
userId = 1
}, (err, res, body) => {
if(err != null){
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
}
else{
EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok");
}
});
}
public void Put(){
RestClient.Put<Post>(basePath + "/posts/1", new {
title = "foo",
body = "bar",
userId = 1
}, (err, res, body) => {
if(err != null){
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
}
else{
EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok");
}
});
}
public void Delete(){
RestClient.Delete(basePath + "/posts/1", (err, res) => {
if(err != null){
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
}
else{
EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok");
}
});
}
} | using UnityEngine;
using UnityEditor;
using Models;
using Proyecto26;
using System.Collections.Generic;
public class MainScript : MonoBehaviour {
string basePath = "https://jsonplaceholder.typicode.com";
public void Get(){
// We can add default request headers for all requests
RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ...";
RequestHelper requestOptions = null;
RestClient.GetArray<Post>(new RequestHelper{ url = basePath + "/posts" }).Then(res => {
EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok");
return RestClient.GetArray<Todo>(basePath + "/todos");
}).Then(res => {
EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok");
return RestClient.GetArray<User>(basePath + "/users");
}).Then(res => {
EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok");
// We can add specific options and override default headers for a request
requestOptions = new RequestHelper {
url = basePath + "/photos",
headers = new Dictionary<string, string>{
{ "Authorization", "Other token..." }
}
};
return RestClient.GetArray<Photo>(requestOptions);
}).Then(res => {
EditorUtility.DisplayDialog("Autorization header", requestOptions.GetRequestHeader("Authorization"), "Ok");
// And later we can clean the default headers for all requests
RestClient.CleanDefaultHeaders();
}).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok"));
}
public void Post(){
RestClient.Post<Models.Post>(basePath + "/posts", new {
title = "foo",
body = "bar",
userId = 1
}, (err, res, body) => {
if(err != null){
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
}
else{
EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok");
}
});
}
public void Put(){
RestClient.Put<Post>(basePath + "/posts/1", new {
title = "foo",
body = "bar",
userId = 1
}, (err, res, body) => {
if(err != null){
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
}
else{
EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok");
}
});
}
public void Delete(){
RestClient.Delete(basePath + "/posts/1", (err, res) => {
if(err != null){
EditorUtility.DisplayDialog ("Error", err.Message, "Ok");
}
else{
EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok");
}
});
}
} | mit | C# |
0a15825bcd1e7ad69abd3fdc10e2653f4387a23f | Add comments for XBox360ControllerManager static class | mina-asham/XBox360ControllerManager | XBox360ControllerManager/XBox360.cs | XBox360ControllerManager/XBox360.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace XBox360ControllerManager
{
/// <summary>
/// Static class for managing XBox 360 controllers
/// </summary>
public static class XBox360
{
/// <summary>
/// XInput DLL, this is compatible with Windows 8+, for previous versions we might need to change this one
/// </summary>
private const String XInputDll = "XInput1_4.dll";
/// <summary>
/// Secret entry point for GetGamepad function
/// Other entry point mentioned in XInput documentations doesn't provide the Guide button
/// </summary>
/// <param name="playerIndex">Player/gamepad index</param>
/// <param name="gamepad">Output gamepad info</param>
/// <returns>Connected if gamepad is connected, NotConnected otherwise</returns>
[DllImport(XInputDll, EntryPoint = "#100")]
private static extern XBox360GamepadState GetGamepad(XBox360PlayerIndex playerIndex, out XBox360Gamepad gamepad);
/// <summary>
/// Secret entry point for PowerOffGamepad function
/// </summary>
/// <param name="playerIndex">Player/gamepad index</param>
/// <returns>Connected if gamepad is connected, NotConnected otherwise</returns>
[DllImport(XInputDll, EntryPoint = "#103")]
public static extern XBox360GamepadState PowerOffGamepad(XBox360PlayerIndex playerIndex);
/// <summary>
/// Get gamepad given a player/gamepad index
/// </summary>
/// <param name="playerIndex">Player/gamepad index</param>
/// <returns>The corresponding gamepad</returns>
public static XBox360Gamepad GetGamepad(XBox360PlayerIndex playerIndex)
{
XBox360Gamepad gamepad;
GetGamepad(playerIndex, out gamepad);
return gamepad;
}
/// <summary>
/// Get all four gamepads
/// </summary>
/// <returns>All four gamepads</returns>
public static List<XBox360Gamepad> GetGamepads()
{
return Enum.GetValues(typeof(XBox360PlayerIndex))
.Cast<XBox360PlayerIndex>()
.Select(GetGamepad)
.ToList();
}
/// <summary>
/// Power off all connected gamepad
/// </summary>
public static void PowerOffGamepads()
{
foreach (XBox360PlayerIndex playerIndex in Enum.GetValues(typeof(XBox360PlayerIndex)))
{
PowerOffGamepad(playerIndex);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace XBox360ControllerManager
{
public static class XBox360
{
//Might need to change on systems earlier to Windows 8
private const String XInputDll = "XInput1_4.dll";
[DllImport(XInputDll, EntryPoint = "#100")]
private static extern XBox360GamepadState GetGamepad(XBox360PlayerIndex playerIndex, out XBox360Gamepad gamepad);
[DllImport(XInputDll, EntryPoint = "#103")]
public static extern XBox360GamepadState PowerOffGamepad(XBox360PlayerIndex playerIndex);
public static XBox360Gamepad GetGamepad(XBox360PlayerIndex playerIndex)
{
XBox360Gamepad gamepad;
GetGamepad(playerIndex, out gamepad);
return gamepad;
}
public static List<XBox360Gamepad> GetGamepads()
{
return Enum.GetValues(typeof(XBox360PlayerIndex))
.Cast<XBox360PlayerIndex>()
.Select(GetGamepad)
.ToList();
}
public static void PowerOffGamepads()
{
foreach (XBox360PlayerIndex playerIndex in Enum.GetValues(typeof(XBox360PlayerIndex)))
{
PowerOffGamepad(playerIndex);
}
}
}
}
| mit | C# |
466a0be84c8a2753aae4e5cec2cffbe262488dcd | Implement HasVisibleChildren on UmbracoNavigationRedirectElement | Gibe/Gibe.Navigation | Gibe.Navigation.Umbraco/Models/UmbracoNavigationRedirectElement.cs | Gibe.Navigation.Umbraco/Models/UmbracoNavigationRedirectElement.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gibe.DittoProcessors.Processors;
using Gibe.DittoProcessors.Processors.Models;
using Gibe.Navigation.Models;
using Our.Umbraco.Ditto;
namespace Gibe.Navigation.Umbraco.Models
{
public class UmbracoNavigationRedirectElement : INavigationElement
{
[UmbracoProperty("Name")]
public string Title { get; set; }
public string NavTitle { get; set; }
[UmbracoProperty("redirect")]
[LinkPicker]
public LinkPickerModel Redirect { get; set; }
[DittoIgnore]
public string Url => Redirect.Url;
public bool IsActive { get; set; }
public IEnumerable<INavigationElement> Items { get; set; }
[DittoIgnore]
public string Target => Redirect.Target;
public bool IsVisible { get; set; }
public bool IsConcrete => false;
public bool HasVisibleChildren => Items.Any(x => x.IsVisible);
public object Clone()
{
return new UmbracoNavigationRedirectElement
{
Title = Title,
NavTitle = NavTitle,
Redirect = Redirect,
IsActive = IsActive,
Items = Items.Select(i => (INavigationElement)i.Clone()).ToList(),
IsVisible = IsVisible,
};
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gibe.DittoProcessors.Processors;
using Gibe.DittoProcessors.Processors.Models;
using Gibe.Navigation.Models;
using Our.Umbraco.Ditto;
namespace Gibe.Navigation.Umbraco.Models
{
public class UmbracoNavigationRedirectElement : INavigationElement
{
[UmbracoProperty("Name")]
public string Title { get; set; }
public string NavTitle { get; set; }
[UmbracoProperty("redirect")]
[LinkPicker]
public LinkPickerModel Redirect { get; set; }
[DittoIgnore]
public string Url => Redirect.Url;
public bool IsActive { get; set; }
public IEnumerable<INavigationElement> Items { get; set; }
[DittoIgnore]
public string Target => Redirect.Target;
public bool IsVisible { get; set; }
public bool IsConcrete => false;
public object Clone()
{
return new UmbracoNavigationRedirectElement
{
Title = Title,
NavTitle = NavTitle,
Redirect = Redirect,
IsActive = IsActive,
Items = Items.Select(i => (INavigationElement)i.Clone()).ToList(),
IsVisible = IsVisible,
};
}
}
}
| mit | C# |
0c79c18b2ecbb6b61dffd2ba18ce8a39cec5c77d | Clean R type | michael-reichenauer/GitMind | GitMind/Utils/R.cs | GitMind/Utils/R.cs | using System;
namespace GitMind.Utils
{
public class R
{
public static R Ok = new R(Error.None);
public static R NoValue = new R(Error.NoValue);
protected R(Error error)
{
Error = error;
}
public Error Error { get; }
public bool IsFaulted => Error != Error.None;
public bool IsOk => Error == Error.None;
public string Message => Error.Message;
public static R<T> From<T>(T result) => new R<T>(result);
public static implicit operator R(Error error) => new R(error);
public static implicit operator R(Exception e) => new R(Error.From(e));
public static implicit operator bool(R r) => r.IsOk;
public override string ToString() => IsOk ? "OK" : $"Error: {Error}";
}
public class R<T> : R
{
private readonly T storedValue;
public new static R<T> NoValue = new R<T>(Error.NoValue);
public R(T value) : base(Error.None) => this.storedValue = value;
public R(Error error)
: base(error)
{
}
public static implicit operator R<T>(Error error) => new R<T>(error);
public static implicit operator R<T>(Exception e) => new R<T>(Error.From(e));
public static implicit operator bool(R<T> r) => r.IsOk;
public static implicit operator R<T>(T value)
{
if (value == null)
{
throw Asserter.FailFast("Value cannot be null");
}
return new R<T>(value);
}
public T Value => !IsFaulted ? storedValue : throw Asserter.FailFast(Error);
public bool HasValue(out T value)
{
if (!IsFaulted)
{
value = storedValue;
return true;
}
else
{
value = default(T);
return false;
}
}
public T Or(T defaultValue) => IsFaulted ? defaultValue : Value;
public override string ToString() =>
IsFaulted ? $"Error: {Error}" : (storedValue?.ToString() ?? "");
}
} | using System;
namespace GitMind.Utils
{
public class R
{
public static R Ok = new R(Error.None);
public static R NoValue = new R(Error.NoValue);
protected R(Error error)
{
Error = error;
}
public Error Error { get; }
public bool IsFaulted => Error != Error.None;
public bool IsOk => Error == Error.None;
public string Message => Error.Message;
public static R<T> From<T>(T result) => new R<T>(result);
public static implicit operator R(Error error) => new R(error);
public static implicit operator R(Exception e) => new R(Error.From(e));
public static implicit operator bool(R r) => !r.IsFaulted;
public override string ToString()
{
if (IsFaulted)
{
return $"Error: {Error}";
}
return "OK";
}
}
public class R<T> : R
{
private readonly T storedValue;
public new static R<T> NoValue = new R<T>(Error.NoValue);
public R(T value)
: base(Error.None)
{
this.storedValue = value;
}
public R(Error error)
: base(error)
{
}
public static implicit operator R<T>(Error error) => new R<T>(error);
public static implicit operator R<T>(Exception e) => new R<T>(Error.From(e));
public static implicit operator bool(R<T> r) => !r.IsFaulted;
public static implicit operator R<T>(T value)
{
if (value == null)
{
throw Asserter.FailFast("Value cannot be null");
}
return new R<T>(value);
}
public T Value
{
get
{
if (!IsFaulted)
{
return storedValue;
}
throw Asserter.FailFast(Error);
}
}
//public bool HasValue => ;
public bool HasValue(out T value)
{
if (!IsFaulted)
{
value = storedValue;
return true;
}
else
{
value = default(T);
return false;
}
}
public T Or(T defaultValue)
{
if (IsFaulted)
{
return defaultValue;
}
return Value;
}
public override string ToString()
{
if (IsFaulted)
{
return $"Error: {Error}";
}
return storedValue?.ToString() ?? "";
}
}
} | mit | C# |
1bed1d787013b62eb7df465275fe7e50e7ccdedb | Update Program.cs | IanMcT/StockMarketGame | SMG/SMG/Program.cs | SMG/SMG/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMG
{
static class Program
{
public static User user;
public static double difficulty = 1000.00;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var MainForm = new Form1();
MainForm.Show();
Application.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMG
{
static class Program
{
public static User user;
public static User difficulty;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var MainForm = new Form1();
MainForm.Show();
Application.Run();
}
}
}
| apache-2.0 | C# |
551d1ccddaba4d35b25dd869bb286296cd15ee0f | change version tag in nuspec for test package | secana/CakeApp | build.cake | build.cake |
/*
1) clean old packages DONE
2) ensure all needed directories exist DONE
3) package test version of template
4) install test version of template
5) create new sln with test version
6) test test version
7) if successful: package to release version
8) publish package to nuget
*/
var target = Argument("target", "Default");
var testFailed = false;
var solutionDir = System.IO.Directory.GetCurrentDirectory();
var testDirectory = Argument("testDirectory", System.IO.Path.Combine(solutionDir, "test")); // ./build.sh --target publish -testDirectory="somedir"
var artifactDir = Argument("artifactDir", "./artifacts"); // ./build.sh --target publish -artifactDir="somedir"
Task("Clean")
.Does(() =>
{
if(DirectoryExists(testDirectory))
DeleteDirectory(testDirectory, recursive:true);
if(DirectoryExists(artifactDir))
DeleteDirectory(artifactDir, recursive:true);
});
Task("PrepareDirectories")
.IsDependentOn("Clean")
.Does(() =>
{
EnsureDirectoryExists(testDirectory);
EnsureDirectoryExists(artifactDir);
});
Task("PrepareTestNuSpec")
.IsDependentOn("PrepareDirectories")
.Does(() =>
{
var testSpecPath = System.IO.Path.Combine(testDirectory, "CakeApp-test.nuspec");
CopyFile("CakeApp.nuspec", testSpecPath);
var version = GetNuSpecVersion(testSpecPath);
var testVersion = $"{version}-test";
// Replace the version value with the test version value
ChangeNuSpecVersion(testSpecPath, testVersion);
});
Task("Default")
.IsDependentOn("Clean")
.Does(() =>
{
Information("Build and test the whole solution.");
Information("To pack (nuget) the application use the cake build argument: --target Pack");
Information("To publish (to run it somewhere else) the application use the cake build argument: --target Publish");
});
void ChangeNuSpecVersion(string nuspecPath, string newVersion)
{
var doc = System.Xml.Linq.XDocument.Load(nuspecPath);
doc.Descendants().First(p => p.Name.LocalName == "version").Value = newVersion;
var fileStream = new System.IO.FileStream(nuspecPath, FileMode.Open);
doc.Save(fileStream);
Information($"Changed version from {nuspecPath} to {newVersion}");
}
string GetNuSpecVersion(string nuspecPath)
{
var doc = System.Xml.Linq.XDocument.Load(nuspecPath);
var version = doc.Descendants().First(p => p.Name.LocalName == "version").Value;
Information($"Extrated version {version} from {nuspecPath}");
return version;
}
RunTarget(target); |
/*
1) clean old packages
2) ensure all needed directories exist
3) package test version of template
4) install test version of template
5) create new sln with test version
6) test test version
7) if successful: package to release version
8) publish package to nuget
*/
var target = Argument("target", "Default");
var testFailed = false;
var solutionDir = System.IO.Directory.GetCurrentDirectory();
var testDirectory = Argument("testDirectory", System.IO.Path.Combine(solutionDir, "test")); // ./build.sh --target publish -testDirectory="somedir"
var artifactDir = Argument("artifactDir", "./artifacts"); // ./build.sh --target publish -artifactDir="somedir"
Task("Clean")
.Does(() =>
{
if(DirectoryExists(testDirectory))
DeleteDirectory(testDirectory, recursive:true);
if(DirectoryExists(artifactDir))
DeleteDirectory(artifactDir, recursive:true);
});
Task("PrepareDirectories")
.Does(() =>
{
EnsureDirectoryExists(testDirectory);
EnsureDirectoryExists(artifactDir);
});
Task("Default")
.IsDependentOn("PrepareDirectories")
.Does(() =>
{
Information("Build and test the whole solution.");
Information("To pack (nuget) the application use the cake build argument: --target Pack");
Information("To publish (to run it somewhere else) the application use the cake build argument: --target Publish");
});
RunTarget(target); | apache-2.0 | C# |
431b934fb577550c901a375859a7e1af96f44a3f | Add generated Tags class | GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,Forage/gstreamer-sharp,Forage/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,Forage/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,Forage/gstreamer-sharp | gstreamer-sharp/Tags.cs | gstreamer-sharp/Tags.cs | namespace Gst {
public static class Tags {
public const string Title = "title";
public const string TitleSortname = "title-sortname";
public const string Artist = "artist";
public const string ArtistSortname = "musicbrainz-sortname";
public const string Album = "album";
public const string AlbumSortname = "album-sortname";
public const string Composer = "composer";
public const string Date = "date";
public const string Genre = "genre";
public const string Comment = "comment";
public const string ExtendedComment = "extended-comment";
public const string TrackNumber = "track-number";
public const string TrackCount = "track-count";
public const string AlbumVolumeNumber = "album-disc-number";
public const string AlbumVolumeCount = "album-disc-count";
public const string Location = "location";
public const string Homepage = "homepage";
public const string Description = "description";
public const string Version = "version";
public const string Isrc = "isrc";
public const string Organization = "organization";
public const string Copyright = "copyright";
public const string CopyrightUri = "copyright-uri";
public const string Contact = "contact";
public const string License = "license";
public const string LicenseUri = "license-uri";
public const string Performer = "performer";
public const string Duration = "duration";
public const string Codec = "codec";
public const string VideoCodec = "video-codec";
public const string AudioCodec = "audio-codec";
public const string SubtitleCodec = "subtitle-codec";
public const string Bitrate = "bitrate";
public const string NominalBitrate = "nominal-bitrate";
public const string MinimumBitrate = "minimum-bitrate";
public const string MaximumBitrate = "maximum-bitrate";
public const string Serial = "serial";
public const string Encoder = "encoder";
public const string EncoderVersion = "encoder-version";
public const string TrackGain = "replaygain-track-gain";
public const string TrackPeak = "replaygain-track-peak";
public const string AlbumGain = "replaygain-album-gain";
public const string AlbumPeak = "replaygain-album-peak";
public const string ReferenceLevel = "replaygain-reference-level";
public const string LanguageCode = "language-code";
public const string Image = "image";
public const string PreviewImage = "preview-image";
public const string Attachment = "attachment";
public const string BeatsPerMinute = "beats-per-minute";
public const string Keywords = "keywords";
public const string GeoLocationName = "geo-location-name";
public const string GeoLocationLatitude = "geo-location-latitude";
public const string GeoLocationLongitude = "geo-location-longitude";
public const string GeoLocationElevation = "geo-location-elevation";
}
}
| namespace Gst {
public static class Tags {
public const string Title = "title";
public const string TitleSortname = "title-sortname";
public const string Artist = "artist";
public const string ArtistSortname = "musicbrainz-sortname";
public const string Album = "album";
public const string AlbumSortname = "album-sortname";
public const string Composer = "composer";
public const string Date = "date";
public const string Genre = "genre";
public const string Comment = "comment";
public const string ExtendedComment = "extended-comment";
public const string TrackNumber = "track-number";
public const string TrackCount = "track-count";
public const string AlbumVolumeNumber = "album-disc-number";
public const string AlbumVolumeCount = "album-disc-count";
public const string Location = "location";
public const string Homepage = "homepage";
public const string Description = "description";
public const string Version = "version";
public const string Isrc = "isrc";
public const string Organization = "organization";
public const string Copyright = "copyright";
public const string CopyrightUri = "copyright-uri";
public const string Contact = "contact";
public const string License = "license";
public const string LicenseUri = "license-uri";
public const string Performer = "performer";
public const string Duration = "duration";
public const string Codec = "codec";
public const string VideoCodec = "video-codec";
public const string AudioCodec = "audio-codec";
public const string SubtitleCodec = "subtitle-codec";
public const string Bitrate = "bitrate";
public const string NominalBitrate = "nominal-bitrate";
public const string MinimumBitrate = "minimum-bitrate";
public const string MaximumBitrate = "maximum-bitrate";
public const string Serial = "serial";
public const string Encoder = "encoder";
public const string EncoderVersion = "encoder-version";
public const string TrackGain = "replaygain-track-gain";
public const string TrackPeak = "replaygain-track-peak";
public const string AlbumGain = "replaygain-album-gain";
public const string AlbumPeak = "replaygain-album-peak";
public const string ReferenceLevel = "replaygain-reference-level";
public const string LanguageCode = "language-code";
public const string Image = "image";
public const string PreviewImage = "preview-image";
public const string Attachment = "attachment";
public const string BeatsPerMinute = "beats-per-minute";
public const string Keywords = "keywords";
public const string GeoLocationName = "geo-location-name";
public const string GeoLocationLatitude = "geo-location-latitude";
public const string GeoLocationLongitude = "geo-location-longitude";
public const string GeoLocationElevation = "geo-location-elevation";
}
}
| lgpl-2.1 | C# |
8de75f23148c86fc07eb661e9c10975c1086ab61 | Add sentence segmentation example to Program.cs | hrzafer/nuve | nuve.client/Program.cs | nuve.client/Program.cs | using System;
using Nuve.Lang;
using Nuve.Sentence;
using Nuve.Tokenizers;
namespace Nuve.Client
{
public class Program
{
private static readonly Language Turkish = LanguageFactory.Create(LanguageType.Turkish);
private static void Main(string[] args)
{
//Benchmarker.TestWithAMillionTokens(Turkish.Analyze);
//Benchmarker.TestWithAMillionWords(Turkish.Analyze);
//GitHubReadmeExamples();
//AnalysisHelper.Analyze(Turkish, new[] { "eşkali", "eşkâli" });
SentenceSegmentation();
}
private static void GitHubReadmeExamples()
{
var tr = LanguageFactory.Create(LanguageType.Turkish);
var solutions = tr.Analyze("yolsuzu");
foreach (var solution in solutions)
{
Console.WriteLine("\t{0}", solution);
Console.WriteLine("\toriginal:{0} stem:{1} root:{2}\n",
solution.GetSurface(),
solution.GetStem().GetSurface(),
solution.Root); //Stemming
}
//Method 1: Specify the ids of the morphemes that constitute the word
var word1 = tr.Generate("kitap/ISIM", "IC_COGUL_lAr", "IC_SAHIPLIK_BEN_(U)m",
"IC_HAL_BULUNMA_DA", "IC_AITLIK_ki", "IC_COGUL_lAr", "IC_HAL_AYRILMA_DAn");
//Method 2: Specify the string representation of the analysis of the word.
var analysis = "kitap/ISIM IC_COGUL_lAr IC_SAHIPLIK_BEN_(U)m";
var word2 = tr.GetWord(analysis);
Console.WriteLine(word1.GetSurface());
Console.WriteLine(word2.GetSurface());
}
private static void AnalysisAndStemming()
{
}
private static void Generation()
{
}
private static void SentenceSegmentation()
{
var paragraph = "Prof. Dr. Ahmet Bey 1.6 oranında artış var dedi 2. kez. E-posta adresi ahmet.bilir@prof.dr imiş! Doğru mu?";
ITokenizer tokenizer = new ClassicTokenizer(true);
SentenceSegmenter segmenter = new TokenBasedSentenceSegmenter(tokenizer);
var sentences = segmenter.GetSentences(paragraph);
foreach (string sentence in sentences)
{
Console.WriteLine(sentence);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nuve.Client.Benchmark;
using Nuve.Lang;
namespace Nuve.Client
{
public class Program
{
private static readonly Language Turkish = LanguageFactory.Create(LanguageType.Turkish);
static void Main(string[] args)
{
//Benchmarker.TestWithAMillionTokens(Turkish.Analyze);
//Benchmarker.TestWithAMillionWords(Turkish.Analyze);
GitHubReadmeExamples();
}
static void GitHubReadmeExamples()
{
var tr = LanguageFactory.Create(LanguageType.Turkish);
var solutions = tr.Analyze("yolsuzu");
foreach (var solution in solutions)
{
Console.WriteLine("\t{0}", solution);
Console.WriteLine("\toriginal:{0} stem:{1} root:{2}\n",
solution.GetSurface(),
solution.GetStem().GetSurface(),
solution.Root); //Stemming
}
//Method 1: Specify the ids of the morphemes that constitute the word
var word1 = tr.Generate("kitap/ISIM", "IC_COGUL_lAr", "IC_SAHIPLIK_BEN_(U)m",
"IC_HAL_BULUNMA_DA", "IC_AITLIK_ki", "IC_COGUL_lAr", "IC_HAL_AYRILMA_DAn");
//Method 2: Specify the string representation of the analysis of the word.
string analysis = "kitap/ISIM IC_COGUL_lAr IC_SAHIPLIK_BEN_(U)m";
var word2 = tr.GetWord(analysis);
Console.WriteLine(word1.GetSurface());
Console.WriteLine(word2.GetSurface());
}
}
}
| mit | C# |
d6f54cbf76832964bb1682be61076adf8716eb27 | Update CompactBinaryBondSerializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/Bond/CompactBinaryBondSerializer.cs | TIKSN.Core/Serialization/Bond/CompactBinaryBondSerializer.cs | using Bond.IO.Safe;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class CompactBinaryBondSerializer : SerializerBase<byte[]>
{
protected override byte[] SerializeInternal<T>(T obj)
{
var output = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(output);
global::Bond.Serialize.To(writer, obj);
return output.Data.Array;
}
}
}
| using Bond.IO.Safe;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class CompactBinaryBondSerializer : SerializerBase<byte[]>
{
protected override byte[] SerializeInternal<T>(T obj)
{
var output = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(output);
global::Bond.Serialize.To(writer, obj);
return output.Data.Array;
}
}
} | mit | C# |
d25add8c53764a6569b231a9b1778a29a0f317bd | Hide results until results are available | thabofletcher/psychic-dangerzone,thabofletcher/psychic-dangerzone | psychic-dangerzone/Views/Home/Index.cshtml | psychic-dangerzone/Views/Home/Index.cshtml | @model string
<div class="container">
<form action="/" method="POST">
<div class="control-group">
<div class="controls controls-row">
<div class="input-prepend">
<span class="add-on">Ask me</span>
<input id="query" name="query" class="input-xlarge" placeholder="What is the meaing of life?" type="text">
</div>
</div>
</div>
<button id="submit" type="submit" class="btn btn-danger btn-large">Ask the psychic dangerzone</button>
</form>
@if (!string.IsNullOrEmpty(Model))
{
<center>
<div id="results-wrapper">
<div id="results-header">
<h2>Welcome to the dangerzone</h2>
</div>
<div id="results">
<p>@Model</p>
</div>
</div>
</center>
}
</div> | @model string
<div class="container">
<form action="/" method="POST">
<div class="control-group">
<div class="controls controls-row">
<div class="input-prepend">
<span class="add-on">Ask me</span>
<input id="query" name="query" class="input-xlarge" placeholder="What is the meaing of life?" type="text">
</div>
</div>
</div>
<button id="submit" type="submit" class="btn btn-inverse btn-large">Ask the psychic dangerzone</button>
</form>
<div id="results-wrapper">
<div id="results-header">
<h2>Welcome to the dangerzone</h2>
</div>
<div id="results">
<p>@Model</p>
</div>
</div>
</div> | mit | C# |
7dfe507844a97613298c6501646a470b60c3b9e4 | Remove bad detection of application quit (was called when reloading current scene) | clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,xtralifecloud/unity-sdk | CotcSdk/HighLevel/CotcGameObject.cs | CotcSdk/HighLevel/CotcGameObject.cs | using System;
using UnityEngine;
namespace CotcSdk
{
/// @ingroup main_classes
/// <summary>
/// Place this object on all scenes where you would like to use CotC functionality, as described @ref cotcgameobject_ref "in this tutorial".
///
/// Then call #GetCloud to get a Cloud object, which provides an entry point (through sub objects) to all functionality provided by the SDK.
/// </summary>
public class CotcGameObject : MonoBehaviour {
private Promise<Cloud> whenStarted = new Promise<Cloud>();
/// <summary>
/// Use this to get a Cloud object, as shown below:
/// @code{.cs}
/// var cotc = FindObjectOfType<CotcGameObject>();
/// cotc.GetCloud(cloud => {
/// cloud.Login(...);
/// } @endcode
/// </summary>
/// <returns>A promise that returns a Cloud object to be used for most operations. Although the returned object may be shared among
/// multiple scenes, you need to place a CotcGameObject and call GetCloud on all your scenes to ensure proper operations.</returns>
public Promise<Cloud> GetCloud() {
return whenStarted;
}
void Start() {
CotcSettings s = CotcSettings.Instance;
// No need to initialize it once more
if (s == null || string.IsNullOrEmpty(s.Environments[s.SelectedEnvironment].ApiKey) ||
string.IsNullOrEmpty(s.Environments[s.SelectedEnvironment].ApiSecret))
{
throw new ArgumentException("!!!! You need to set up the credentials of your application in the settings of your Cotc object !!!!");
}
CotcSettings.Environment env = s.Environments[s.SelectedEnvironment];
Cotc.Setup(env.ApiKey, env.ApiSecret, env.ServerUrl, env.LbCount, env.HttpVerbose, env.HttpTimeout)
.Then(result => {
Common.Log("CotC inited");
whenStarted.Resolve(result);
});
}
void Update() {
Cotc.Update();
}
void OnApplicationFocus(bool focused) {
Common.Log(focused ? "CotC resumed" : "CotC suspended");
Cotc.OnApplicationFocus(focused);
}
void OnApplicationQuit() {
Common.Log("CotC destroyed");
Cotc.OnApplicationQuit();
}
}
}
| using System;
using UnityEngine;
namespace CotcSdk
{
/// @ingroup main_classes
/// <summary>
/// Place this object on all scenes where you would like to use CotC functionality, as described @ref cotcgameobject_ref "in this tutorial".
///
/// Then call #GetCloud to get a Cloud object, which provides an entry point (through sub objects) to all functionality provided by the SDK.
/// </summary>
public class CotcGameObject : MonoBehaviour {
private Promise<Cloud> whenStarted = new Promise<Cloud>();
/// <summary>
/// Use this to get a Cloud object, as shown below:
/// @code{.cs}
/// var cotc = FindObjectOfType<CotcGameObject>();
/// cotc.GetCloud(cloud => {
/// cloud.Login(...);
/// } @endcode
/// </summary>
/// <returns>A promise that returns a Cloud object to be used for most operations. Although the returned object may be shared among
/// multiple scenes, you need to place a CotcGameObject and call GetCloud on all your scenes to ensure proper operations.</returns>
public Promise<Cloud> GetCloud() {
return whenStarted;
}
void Start() {
CotcSettings s = CotcSettings.Instance;
// No need to initialize it once more
if (s == null || string.IsNullOrEmpty(s.Environments[s.SelectedEnvironment].ApiKey) ||
string.IsNullOrEmpty(s.Environments[s.SelectedEnvironment].ApiSecret))
{
throw new ArgumentException("!!!! You need to set up the credentials of your application in the settings of your Cotc object !!!!");
}
CotcSettings.Environment env = s.Environments[s.SelectedEnvironment];
Cotc.Setup(env.ApiKey, env.ApiSecret, env.ServerUrl, env.LbCount, env.HttpVerbose, env.HttpTimeout)
.Then(result => {
Common.Log("CotC inited");
whenStarted.Resolve(result);
});
}
void Update() {
Cotc.Update();
}
void OnApplicationFocus(bool focused) {
Common.Log(focused ? "CotC resumed" : "CotC suspended");
Cotc.OnApplicationFocus(focused);
}
void OnDestroy()
{
if (Application.isEditor)
{
if (GameObject.FindObjectsOfType<CotcGameObject>().Length < 1)
{
Debug.Log("Forcing destroy CotC");
Cotc.OnApplicationQuit();
}
}
}
void OnApplicationQuit() {
Cotc.OnApplicationQuit();
}
}
}
| mit | C# |
f25c61bee487035b16b3dc3d8e035d8199849a72 | remove blank line | peppy/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,2yangk23/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,DrabWeb/osu,smoogipooo/osu,ppy/osu,DrabWeb/osu,smoogipoo/osu,DrabWeb/osu,johnneijzen/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu | osu.iOS/Application.cs | osu.iOS/Application.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using UIKit;
namespace osu.iOS
{
public class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using UIKit;
namespace osu.iOS
{
public class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| mit | C# |
64348dbc4ee0c31f3565c0e1f7b2db38cb27bfd3 | Fix loop flag. | nessos/Eff | src/Eff.Core/EffExecutor.cs | src/Eff.Core/EffExecutor.cs | #pragma warning disable 1998
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Eff.Core
{
public static class EffExecutor
{
public static async Task<TResult> Run<TResult>(this Eff<TResult> eff, IEffectHandler handler)
{
var effMethodHandler = new EffMethodHandler<TResult>();
var result = default(TResult);
var done = false;
while (!done)
{
switch (eff)
{
case SetResult<TResult> setResult:
result = setResult.Result;
done = true;
break;
default:
eff = await eff.Handle(effMethodHandler, handler);
break;
}
}
return result;
}
}
}
| #pragma warning disable 1998
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Eff.Core
{
public static class EffExecutor
{
public static async Task<TResult> Run<TResult>(this Eff<TResult> eff, IEffectHandler handler)
{
var effMethodHandler = new EffMethodHandler<TResult>();
var result = default(TResult);
var done = false;
while (done)
{
switch (eff)
{
case SetResult<TResult> setResult:
result = setResult.Result;
done = true;
break;
default:
eff = await eff.Handle(effMethodHandler, handler);
break;
}
}
return result;
}
}
}
| mit | C# |
2f084aa75a4fe2b0bfad0e0b003a67f4dfa3512f | Update EnumerableExtensions.cs | keith-hall/Extensions,keith-hall/Extensions | src/EnumerableExtensions.cs | src/EnumerableExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{ // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count)
{
return enumerable.Take(count + 1).Count() > count;
}
public static IEnumerable<T> AsSingleEnumerable<T> (this T value)
{
//x return Enumerable.Repeat(value, 1);
return new [] { value };
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{ // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count)
{
return enumerable.Take(count + 1).Count() > count;
}
}
| apache-2.0 | C# |
0917ea6da7d4a789aee9dd5e1fe7f7df8999d17c | Use passed in handedness when initializing hand tracking events | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,vladkol/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,vladkol/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,vladkol/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/EventDatum/Input/HandTrackingInputEventData.cs | Assets/MixedRealityToolkit/EventDatum/Input/HandTrackingInputEventData.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Input
{
public class HandTrackingInputEventData : InputEventData<Vector3>
{
/// <summary>
/// Constructor creates a default EventData object.
/// Requires initialization.
/// </summary>
/// <param name="eventSystem"></param>
public HandTrackingInputEventData(EventSystem eventSystem) : base(eventSystem) { }
public IMixedRealityController Controller { get; set; }
/// <summary>
/// This function is called to fill the HandTrackingIntputEventData object with information
/// </summary>
/// <param name="inputSource">Reference to the HandTrackingInputSource that created the EventData</param>
/// <param name="controller">Reference to the IMixedRealityController that created the EventData</param>
/// <param name="sourceHandedness">Handedness of the HandTrackingInputSource that created the EventData</param>
/// <param name="touchPoint">Global position of the HandTrackingInputSource that created the EventData</param>
public void Initialize(IMixedRealityInputSource inputSource, IMixedRealityController controller, Handedness sourceHandedness, Vector3 touchPoint)
{
Initialize(inputSource, sourceHandedness, MixedRealityInputAction.None, touchPoint);
Controller = controller;
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Input
{
public class HandTrackingInputEventData : InputEventData<Vector3>
{
/// <summary>
/// Constructor creates a default EventData object.
/// Requires initialization.
/// </summary>
/// <param name="eventSystem"></param>
public HandTrackingInputEventData(EventSystem eventSystem) : base(eventSystem) { }
public IMixedRealityController Controller { get; set; }
/// <summary>
/// This function is called to fill the HandTrackingIntputEventData object with information
/// </summary>
/// <param name="inputSource">This is a reference to the HandTrackingInputSource that created the EventData</param>
/// <param name="controller">This is a reference to the IMixedRealityController that created the EventData</param>
/// <param name="grabbing">This is a the state (grabbing or not grabbing) of the HandTrackingInputSource that created the EventData</param>
/// <param name="pressing">This is a the state (pressing or not pressing) of the HandTrackingInputSource that created the EventData</param>
/// <param name="actionPoint">This is a the global position grabbed by the HandTrackingInputSource that created the EventData</param>
/// <param name="touchedObject">This is a the global position of the HandTrackingInputSource that created the EventData</param>
public void Initialize(IMixedRealityInputSource inputSource, IMixedRealityController controller, Handedness sourceHandedness, Vector3 touchPoint)
{
Initialize(inputSource, Handedness.None, MixedRealityInputAction.None, touchPoint);
Controller = controller;
}
}
}
| mit | C# |
199fb7cdcd582105a9acfb10abddb11562b18df8 | Fix instantiation of generic state objects. | gigya/orleans,shayhatsor/orleans,waynemunro/orleans,cato541265/orleans,tsibelman/orleans,NaseUkolyCZ/orleans,dVakulen/orleans,dVakulen/orleans,ashkan-saeedi-mazdeh/orleans,dariobottazzi/orleans,ReubenBond/orleans,jason-bragg/orleans,kylemc/orleans,bstauff/orleans,ticup/orleans,xclayl/orleans,Joshua-Ferguson/orleans,gabikliot/orleans,ElanHasson/orleans,tsibelman/orleans,rore/orleans,jokin/orleans,jokin/orleans,LoveElectronics/orleans,jthelin/orleans,cbredlow/orleans,kowalot/orleans,ticup/orleans,dotnet/orleans,dariobottazzi/orleans,modulexcite/orleans,MikeHardman/orleans,xclayl/orleans,rrector/orleans,hoopsomuah/orleans,amccool/orleans,benjaminpetit/orleans,modulexcite/orleans,kucheruk/orleans,TedDBarr/orleans,amccool/orleans,jkonecki/orleans,Carlm-MS/orleans,garbervetsky/orleans,ashkan-saeedi-mazdeh/orleans,jkonecki/orleans,skalpin/orleans,jdom/orleans,ElanHasson/orleans,SoftWar1923/orleans,kucheruk/orleans,pherbel/orleans,carlos-sarmiento/orleans,shlomiw/orleans,sebastianburckhardt/orleans,amccool/orleans,NaseUkolyCZ/orleans,Liversage/orleans,centur/orleans,gigya/orleans,SoftWar1923/orleans,skalpin/orleans,sergeybykov/orleans,zhangf911/orleans,jdom/orleans,Liversage/orleans,jokin/orleans,yevhen/orleans,hoopsomuah/orleans,ibondy/orleans,yevhen/orleans,brhinescot/orleans,centur/orleans,shayhatsor/orleans,galvesribeiro/orleans,kangkot/orleans,zhangf911/orleans,kowalot/orleans,Carlm-MS/orleans,garbervetsky/orleans,shlomiw/orleans,MikeHardman/orleans,galvesribeiro/orleans,brhinescot/orleans,dotnet/orleans,cbredlow/orleans,LoveElectronics/orleans,ibondy/orleans,TedDBarr/orleans,rore/orleans,rrector/orleans,gabikliot/orleans,sebastianburckhardt/orleans,Joshua-Ferguson/orleans,kylemc/orleans,kangkot/orleans,waynemunro/orleans,carlos-sarmiento/orleans,pherbel/orleans,brhinescot/orleans,dVakulen/orleans,sergeybykov/orleans,veikkoeeva/orleans,ashkan-saeedi-mazdeh/orleans,Liversage/orleans,bstauff/orleans,cato541265/orleans | src/OrleansRuntime/GrainTypeManager/GenericGrainTypeData.cs | src/OrleansRuntime/GrainTypeManager/GenericGrainTypeData.cs | /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Orleans.Runtime
{
[Serializable]
internal class GenericGrainTypeData : GrainTypeData
{
private readonly Type activationType;
private readonly Type stateObjectType;
public GenericGrainTypeData(Type activationType, Type stateObjectType) :
base(activationType, stateObjectType)
{
if (!activationType.IsGenericTypeDefinition)
throw new ArgumentException("Activation type is not generic: " + activationType.Name);
this.activationType = activationType;
this.stateObjectType = stateObjectType;
}
public GrainTypeData MakeGenericType(Type[] typeArgs)
{
// Need to make a non-generic instance of the class to access the static data field. The field itself is independent of the instantiated type.
var concreteActivationType = activationType.MakeGenericType(typeArgs);
var concreteStateObjectType = (stateObjectType != null && stateObjectType.IsGenericType) ? stateObjectType.GetGenericTypeDefinition().MakeGenericType(typeArgs) : stateObjectType;
return new GrainTypeData(concreteActivationType, concreteStateObjectType);
}
}
}
| /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Orleans.Runtime
{
[Serializable]
internal class GenericGrainTypeData : GrainTypeData
{
private readonly Type activationType;
private readonly Type stateObjectType;
public GenericGrainTypeData(Type activationType, Type stateObjectType) :
base(activationType, stateObjectType)
{
if (!activationType.IsGenericTypeDefinition)
throw new ArgumentException("Activation type is not generic: " + activationType.Name);
this.activationType = activationType;
this.stateObjectType = stateObjectType;
}
public GrainTypeData MakeGenericType(Type[] typeArgs)
{
// Need to make a non-generic instance of the class to access the static data field. The field itself is independent of the instantiated type.
var concreteActivationType = activationType.MakeGenericType(typeArgs);
var concreteStateObjectType = (stateObjectType != null && stateObjectType.IsGenericType) ? stateObjectType.MakeGenericType(typeArgs) : stateObjectType;
return new GrainTypeData(concreteActivationType, concreteStateObjectType);
}
}
}
| mit | C# |
c61547ba1c1fecaad0b99c6035a8f9088ed6f036 | Remove period from response JSON property name (#7) | wealth-farm/SparkPost.Net | src/WealthFarm.SparkPost/Transmission/TransmissionResult.cs | src/WealthFarm.SparkPost/Transmission/TransmissionResult.cs | using Newtonsoft.Json;
namespace WealthFarm.SparkPost
{
/// <summary>
/// The result from sending a transmission.
/// </summary>
public class TransmissionResult
{
/// <summary>
/// Gets or sets the transmission ID.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the number of rejected recipients.
/// </summary>
[JsonProperty("total_rejected_recipients")]
public int TotalRejectedRecipients { get; set; }
/// <summary>
/// Gets or sets the number of accepted recipients.
/// </summary>
[JsonProperty("total_accepted_recipients")]
public int TotalAcceptedRecipients { get; set; }
}
}
| using Newtonsoft.Json;
namespace WealthFarm.SparkPost
{
/// <summary>
/// The result from sending a transmission.
/// </summary>
public class TransmissionResult
{
/// <summary>
/// Gets or sets the transmission ID.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the number of rejected recipients.
/// </summary>
[JsonProperty("total_rejected_recipients")]
public int TotalRejectedRecipients { get; set; }
/// <summary>
/// Gets or sets the number of accepted recipients.
/// </summary>
[JsonProperty("total_accepted_recipients.")]
public int TotalAcceptedRecipients { get; set; }
}
} | mit | C# |
2b18c031f71de71498bdce65ed83b1e08d8905a5 | Fix commit | michael-reichenauer/GitMind | GitMind/Utils/Git/Private/GitCmd.cs | GitMind/Utils/Git/Private/GitCmd.cs | using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GitMind.ApplicationHandling;
using GitMind.Common.Tracking;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitCmd : IGitCmd
{
// git config --list --show-origin
private static readonly string CredentialsConfig = @"-c credential.helper=!GitMind.exe";
private readonly ICmd2 cmd;
private readonly IGitEnvironmentService gitEnvironmentService;
private readonly WorkingFolderPath workingFolder;
public GitCmd(
ICmd2 cmd,
IGitEnvironmentService gitEnvironmentService,
WorkingFolderPath workingFolder)
{
this.cmd = cmd;
this.gitEnvironmentService = gitEnvironmentService;
this.workingFolder = workingFolder;
}
private string GitCmdPath => gitEnvironmentService.GetGitCmdPath();
public async Task<CmdResult2> RunAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
return await CmdAsync(gitArgs, options, ct);
}
public async Task<CmdResult2> RunAsync(string gitArgs, CancellationToken ct)
{
return await CmdAsync(gitArgs, new CmdOptions(), ct);
}
public async Task<CmdResult2> RunAsync(
string gitArgs, Action<string> outputLines, CancellationToken ct)
{
CmdOptions options = new CmdOptions
{
OutputLines = outputLines,
IsOutputDisabled = true,
};
return await CmdAsync(gitArgs, options, ct);
}
private async Task<CmdResult2> CmdAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
AdjustOptions(options);
// Enable credentials handling
gitArgs = $"{CredentialsConfig} {gitArgs}";
Timing t = Timing.StartNew();
Log.Debug($"Run: {GitCmdPath} {gitArgs}");
CmdResult2 result = await cmd.RunAsync(GitCmdPath, gitArgs, options, ct);
Log.Debug($"{t.ElapsedMs}ms: {result}");
Track.Event("gitCmd", $"{t.ElapsedMs}ms: {result.ToStringShort()}");
if (result.ExitCode != 0)
{
Log.Warn($"Exit: {result.ExitCode}, Error: {result.Error}");
}
return result;
}
private void AdjustOptions(CmdOptions options)
{
options.WorkingDirectory = options.WorkingDirectory ?? workingFolder;
// Used to enable credentials handling
options.EnvironmentVariables = environment =>
{
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
environment["Path"] = $"{dir};{environment["Path"]}";
environment["GIT_ASKPASS"] = "no-gitmind-pswd-prompt";
};
}
}
} | using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GitMind.ApplicationHandling;
using GitMind.Common.Tracking;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitCmd : IGitCmd
{
// git config --list --show-origin
private static readonly string CredentialsConfig =
@"-c credential.helper=!GitMind.exe";
//'!f() { sleep 1; echo "username=${GIT_USER}\npassword=${GIT_PASSWORD}"; }; f'
//private static readonly string CredentialsConfig =
// @"-c credential.helper='!echo ""username=michael.reichenauer@gmail.com\npassword=pass""'";
private readonly ICmd2 cmd;
private readonly IGitEnvironmentService gitEnvironmentService;
private readonly WorkingFolderPath workingFolder;
public GitCmd(
ICmd2 cmd,
IGitEnvironmentService gitEnvironmentService,
WorkingFolderPath workingFolder)
{
this.cmd = cmd;
this.gitEnvironmentService = gitEnvironmentService;
this.workingFolder = workingFolder;
}
private string GitCmdPath => gitEnvironmentService.GetGitCmdPath();
public async Task<CmdResult2> RunAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
return await CmdAsync(gitArgs, options, ct);
}
public async Task<CmdResult2> RunAsync(string gitArgs, CancellationToken ct)
{
return await CmdAsync(gitArgs, new CmdOptions(), ct);
}
public async Task<CmdResult2> RunAsync(
string gitArgs, Action<string> outputLines, CancellationToken ct)
{
CmdOptions options = new CmdOptions
{
OutputLines = outputLines,
IsOutputDisabled = true,
};
return await CmdAsync(gitArgs, options, ct);
}
private async Task<CmdResult2> CmdAsync(
string gitArgs, CmdOptions options, CancellationToken ct)
{
AdjustOptions(options);
// Enable credentials handling
gitArgs = $"{CredentialsConfig} {gitArgs}";
Timing t = Timing.StartNew();
Log.Debug($"Run: {GitCmdPath} {gitArgs}");
CmdResult2 result = await cmd.RunAsync(GitCmdPath, gitArgs, options, ct);
Log.Debug($"{t.ElapsedMs}ms: {result}");
Track.Event("gitCmd", $"{t.ElapsedMs}ms: {result.ToStringShort()}");
if (result.ExitCode != 0)
{
Log.Warn($"Exit: {result.ExitCode}, Error: {result.Error}");
}
return result;
}
private void AdjustOptions(CmdOptions options)
{
options.WorkingDirectory = options.WorkingDirectory ?? workingFolder;
// Used to enable credentials handling
options.EnvironmentVariables = environment =>
{
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
environment["Path"] = $"{dir};{environment["Path"]}";
environment["GIT_ASKPASS"] = "no-gitmind-pswd-prompt";
};
}
}
} | mit | C# |
1efa09e3d3b2f74d5d5fcfb2a847410f6bacaaf1 | Fix parameter order in ArgumentException constructor | ForNeVeR/wpf-math | src/WpfMath/Utils/Result.cs | src/WpfMath/Utils/Result.cs | using System;
namespace WpfMath.Utils
{
internal static class Result
{
public static Result<TValue> Ok<TValue>(TValue value) => new Result<TValue>(value, null);
public static Result<TValue> Error<TValue>(Exception error) => new Result<TValue>(default, error);
}
internal readonly struct Result<TValue>
{
private readonly TValue value;
public TValue Value => this.Error == null ? this.value : throw this.Error;
public Exception Error { get; }
public bool IsSuccess => this.Error == null;
public Result(TValue value, Exception error)
{
if (!Equals(value, default) && error != null)
{
throw new ArgumentException($"Invalid {nameof(Result)} constructor call", nameof(error));
}
this.value = value;
this.Error = error;
}
public Result<TProduct> Map<TProduct>(Func<TValue, TProduct> mapper) => this.IsSuccess
? Result.Ok(mapper(this.Value))
: Result.Error<TProduct>(this.Error);
}
}
| using System;
namespace WpfMath.Utils
{
internal static class Result
{
public static Result<TValue> Ok<TValue>(TValue value) => new Result<TValue>(value, null);
public static Result<TValue> Error<TValue>(Exception error) => new Result<TValue>(default, error);
}
internal readonly struct Result<TValue>
{
private readonly TValue value;
public TValue Value => this.Error == null ? this.value : throw this.Error;
public Exception Error { get; }
public bool IsSuccess => this.Error == null;
public Result(TValue value, Exception error)
{
if (!Equals(value, default) && error != null)
{
throw new ArgumentException(nameof(error), $"Invalid {nameof(Result)} constructor call");
}
this.value = value;
this.Error = error;
}
public Result<TProduct> Map<TProduct>(Func<TValue, TProduct> mapper) => this.IsSuccess
? Result.Ok(mapper(this.Value))
: Result.Error<TProduct>(this.Error);
}
}
| mit | C# |
0901333ef3d1cda32dca3fe26e8513679ed01147 | add pinned property in comment | NeoAdonis/osu,peppy/osu-new,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu | osu.Game/Online/API/Requests/Responses/Comment.cs | osu.Game/Online/API/Requests/Responses/Comment.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Newtonsoft.Json;
using osu.Game.Users;
using System;
namespace osu.Game.Online.API.Requests.Responses
{
public class Comment
{
[JsonProperty(@"id")]
public long Id { get; set; }
[JsonProperty(@"parent_id")]
public long? ParentId { get; set; }
public Comment ParentComment { get; set; }
[JsonProperty(@"user_id")]
public long? UserId { get; set; }
public User User { get; set; }
[JsonProperty(@"message")]
public string Message { get; set; }
[JsonProperty(@"message_html")]
public string MessageHtml { get; set; }
[JsonProperty(@"replies_count")]
public int RepliesCount { get; set; }
[JsonProperty(@"votes_count")]
public int VotesCount { get; set; }
[JsonProperty(@"commenatble_type")]
public string CommentableType { get; set; }
[JsonProperty(@"commentable_id")]
public int CommentableId { get; set; }
[JsonProperty(@"legacy_name")]
public string LegacyName { get; set; }
[JsonProperty(@"created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty(@"updated_at")]
public DateTimeOffset? UpdatedAt { get; set; }
[JsonProperty(@"deleted_at")]
public DateTimeOffset? DeletedAt { get; set; }
[JsonProperty(@"edited_at")]
public DateTimeOffset? EditedAt { get; set; }
[JsonProperty(@"edited_by_id")]
public long? EditedById { get; set; }
[JsonProperty(@"pinned")]
public bool Pinned { get; set; }
public User EditedUser { get; set; }
public bool IsTopLevel => !ParentId.HasValue;
public bool IsDeleted => DeletedAt.HasValue;
public bool HasMessage => !string.IsNullOrEmpty(Message);
public bool IsVoted { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Newtonsoft.Json;
using osu.Game.Users;
using System;
namespace osu.Game.Online.API.Requests.Responses
{
public class Comment
{
[JsonProperty(@"id")]
public long Id { get; set; }
[JsonProperty(@"parent_id")]
public long? ParentId { get; set; }
public Comment ParentComment { get; set; }
[JsonProperty(@"user_id")]
public long? UserId { get; set; }
public User User { get; set; }
[JsonProperty(@"message")]
public string Message { get; set; }
[JsonProperty(@"message_html")]
public string MessageHtml { get; set; }
[JsonProperty(@"replies_count")]
public int RepliesCount { get; set; }
[JsonProperty(@"votes_count")]
public int VotesCount { get; set; }
[JsonProperty(@"commenatble_type")]
public string CommentableType { get; set; }
[JsonProperty(@"commentable_id")]
public int CommentableId { get; set; }
[JsonProperty(@"legacy_name")]
public string LegacyName { get; set; }
[JsonProperty(@"created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty(@"updated_at")]
public DateTimeOffset? UpdatedAt { get; set; }
[JsonProperty(@"deleted_at")]
public DateTimeOffset? DeletedAt { get; set; }
[JsonProperty(@"edited_at")]
public DateTimeOffset? EditedAt { get; set; }
[JsonProperty(@"edited_by_id")]
public long? EditedById { get; set; }
public User EditedUser { get; set; }
public bool IsTopLevel => !ParentId.HasValue;
public bool IsDeleted => DeletedAt.HasValue;
public bool HasMessage => !string.IsNullOrEmpty(Message);
public bool IsVoted { get; set; }
}
}
| mit | C# |
a6a03df344eafe79b155e77fd4870c5845d4ee97 | Add test for QueryOne method | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University.Tests/Data/DataRepositoryTests.cs | R7.University.Tests/Data/DataRepositoryTests.cs | //
// DataRepositoryTests.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq;
using R7.University.Tests.Models;
using Xunit;
namespace R7.University.Tests.Data
{
public class DataRepositoryTests
{
[Fact]
public void DataRepositoryTest ()
{
var repository = new TestDataRepository ();
repository.Query<TestEntity> ().ToList ();
repository.Dispose ();
// repository call after dispose should throw exception
Assert.Throws (typeof (InvalidOperationException), () => repository.Query<TestEntity> ().ToList ());
}
[Fact]
public void QueryOneTest ()
{
using (var repository = new TestDataRepository ()) {
repository.Add<TestEntity> (new TestEntity { Id = 1, Title = "Hello, world!" });
repository.Add<TestEntity> (new TestEntity { Id = 2, Title = "Hello again!" });
Assert.Equal (2, repository.QueryOne<TestEntity> (e => e.Id == 2).Single ().Id);
}
}
}
}
| //
// DataRepositoryTests.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq;
using R7.University.Tests.Models;
using Xunit;
namespace R7.University.Tests.Data
{
public class DataRepositoryTests
{
[Fact]
public void DataRepositoryTest ()
{
var repository = new TestDataRepository ();
repository.Query<TestEntity> ().ToList ();
repository.Dispose ();
// repository call after dispose should throw exception
Assert.Throws (typeof (InvalidOperationException), () => repository.Query<TestEntity> ().ToList ());
}
}
}
| agpl-3.0 | C# |
76e0c984c7df771244b0479bc2f49d35efd87fc0 | Remove whitespace | appharbor/appharbor-cli | src/AppHarbor.Tests/CommandDispatcherTest.cs | src/AppHarbor.Tests/CommandDispatcherTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory]
[PropertyData("FooArguments")]
public void ShouldParseAndExecuteCommandWithArguments(string[] commands)
{
var kernelMock = new Mock<IKernel>();
var fooCommandType = typeof(FooCommand);
var commandDispatcher = new CommandDispatcher(new TypeNameMatcher<ICommand>(new Type[] { fooCommandType }), kernelMock.Object);
var commandMock = new Mock<FooCommand>();
kernelMock.Setup(x => x.Resolve(It.Is<Type>(y => y == fooCommandType))).Returns(commandMock.Object);
commandDispatcher.Dispatch(commands);
commandMock.Verify(x => x.Execute(
It.Is<string[]>(y => ArraysEqual(y, commands.Skip(1).ToArray()))), Times.Once());
}
[Theory]
[InlineAutoCommandData("bar")]
[InlineAutoCommandData("foobar")]
public void ShouldNotMatchCommandThatDoesntExist(string commandName)
{
var kernelMock = new Mock<IKernel>();
var fooCommandType = typeof(FooCommand);
var commandDispatcher = new CommandDispatcher(new TypeNameMatcher<ICommand>(new Type[] { fooCommandType }), kernelMock.Object);
var exception = Assert.Throws<ArgumentException>(() => commandDispatcher.Dispatch(new string[] { commandName }));
}
public static IEnumerable<object[]> FooArguments
{
get
{
yield return new object[] { new string[] { "foo" } };
yield return new object[] { new string[] { "Foo" } };
yield return new object[] { new string[] { "foo", "bar" } };
}
}
private static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1, a2))
{
return true;
}
if (a1 == null || a2 == null)
{
return false;
}
if (a1.Length != a2.Length)
{
return false;
}
var comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i]))
{
return false;
}
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel;
using Moq;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory]
[PropertyData("FooArguments")]
public void ShouldParseAndExecuteCommandWithArguments(string[] commands)
{
var kernelMock = new Mock<IKernel>();
var fooCommandType = typeof(FooCommand);
var commandDispatcher = new CommandDispatcher(new TypeNameMatcher<ICommand>(new Type[] { fooCommandType }), kernelMock.Object);
var commandMock = new Mock<FooCommand>();
kernelMock.Setup(x => x.Resolve(It.Is<Type>(y => y == fooCommandType))).Returns(commandMock.Object);
commandDispatcher.Dispatch(commands);
commandMock.Verify(x => x.Execute(
It.Is<string[]>(y => ArraysEqual(y, commands.Skip(1).ToArray()))), Times.Once());
}
[Theory]
[InlineAutoCommandData("bar")]
[InlineAutoCommandData("foobar")]
public void ShouldNotMatchCommandThatDoesntExist(string commandName)
{
var kernelMock = new Mock<IKernel>();
var fooCommandType = typeof(FooCommand);
var commandDispatcher = new CommandDispatcher(new TypeNameMatcher<ICommand>(new Type[] { fooCommandType }), kernelMock.Object);
var exception = Assert.Throws<ArgumentException>(() => commandDispatcher.Dispatch(new string[] { commandName }));
}
public static IEnumerable<object[]> FooArguments
{
get
{
yield return new object[] { new string[] { "foo" } };
yield return new object[] { new string[] { "Foo" } };
yield return new object[] { new string[] { "foo", "bar" } };
}
}
private static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1, a2))
{
return true;
}
if (a1 == null || a2 == null)
{
return false;
}
if (a1.Length != a2.Length)
{
return false;
}
var comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i]))
{
return false;
}
}
return true;
}
}
}
| mit | C# |
eb53a73011b503a2552dceeaa8a10bfda8d11330 | implement new .loadAllEventsSince() | Pondidum/Ledger.Stores.Fs,Pondidum/Ledger.Stores.Fs | Ledger.Stores.Fs/FileStoreReader.cs | Ledger.Stores.Fs/FileStoreReader.cs | using System.Collections.Generic;
using System.Linq;
using Ledger.Infrastructure;
namespace Ledger.Stores.Fs
{
public class FileStoreReader<TKey> : FileStore, IStoreReader<TKey>
{
private readonly string _eventPath;
private readonly string _snapshotPath;
public FileStoreReader(IFileSystem fileSystem, string eventPath, string snapshotPath)
: base(fileSystem)
{
_eventPath = eventPath;
_snapshotPath = snapshotPath;
}
public IEnumerable<DomainEvent<TKey>> LoadEvents(TKey aggregateID)
{
return LoadEvents(_eventPath, aggregateID);
}
public IEnumerable<DomainEvent<TKey>> LoadEventsSince(TKey aggregateID, Sequence? sequence)
{
var events = LoadEvents(aggregateID);
return sequence.HasValue
? events.Where(e => e.Sequence > sequence)
: events;
}
public Snapshot<TKey> LoadLatestSnapshotFor(TKey aggregateID)
{
return LoadLatestSnapshotFor(_snapshotPath, aggregateID);
}
public IEnumerable<TKey> LoadAllKeys()
{
return ReadFrom<EventDto<TKey>>(_eventPath)
.Select(dto => dto.ID)
.Distinct();
}
public IEnumerable<DomainEvent<TKey>> LoadAllEvents()
{
return ReadFrom<EventDto<TKey>>(_eventPath)
.Apply((dto, i) => dto.Event.StreamSequence = new StreamSequence(i))
.Select(dto => dto.Event);
}
public IEnumerable<DomainEvent<TKey>> LoadAllEventsSince(StreamSequence streamSequence)
{
return LoadAllEvents()
.Where(e => e.StreamSequence > streamSequence);
}
public virtual void Dispose()
{
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Ledger.Infrastructure;
namespace Ledger.Stores.Fs
{
public class FileStoreReader<TKey> : FileStore, IStoreReader<TKey>
{
private readonly string _eventPath;
private readonly string _snapshotPath;
public FileStoreReader(IFileSystem fileSystem, string eventPath, string snapshotPath)
: base(fileSystem)
{
_eventPath = eventPath;
_snapshotPath = snapshotPath;
}
public IEnumerable<DomainEvent<TKey>> LoadEvents(TKey aggregateID)
{
return LoadEvents(_eventPath, aggregateID);
}
public IEnumerable<DomainEvent<TKey>> LoadEventsSince(TKey aggregateID, Sequence? sequence)
{
var events = LoadEvents(aggregateID);
return sequence.HasValue
? events.Where(e => e.Sequence > sequence)
: events;
}
public Snapshot<TKey> LoadLatestSnapshotFor(TKey aggregateID)
{
return LoadLatestSnapshotFor(_snapshotPath, aggregateID);
}
public IEnumerable<TKey> LoadAllKeys()
{
return ReadFrom<EventDto<TKey>>(_eventPath)
.Select(dto => dto.ID)
.Distinct();
}
public IEnumerable<DomainEvent<TKey>> LoadAllEvents()
{
return ReadFrom<EventDto<TKey>>(_eventPath)
.Apply((dto, i) => dto.Event.StreamSequence = new StreamSequence(i))
.Select(dto => dto.Event);
}
public virtual void Dispose()
{
}
}
}
| lgpl-2.1 | C# |
c6e0061711b7bc99c87a64f96a3b0ec687aad3a8 | Fix code analysis warnings in EntityFramework component | endian675/ignite,shroman/ignite,xtern/ignite,andrey-kuznetsov/ignite,endian675/ignite,ascherbakoff/ignite,ntikhonov/ignite,WilliamDo/ignite,voipp/ignite,StalkXT/ignite,sk0x50/ignite,NSAmelchev/ignite,BiryukovVA/ignite,ntikhonov/ignite,vldpyatkov/ignite,leveyj/ignite,amirakhmedov/ignite,ntikhonov/ignite,SomeFire/ignite,sk0x50/ignite,ilantukh/ignite,shroman/ignite,vldpyatkov/ignite,apache/ignite,samaitra/ignite,leveyj/ignite,apache/ignite,SharplEr/ignite,StalkXT/ignite,rfqu/ignite,SomeFire/ignite,daradurvs/ignite,vldpyatkov/ignite,samaitra/ignite,voipp/ignite,amirakhmedov/ignite,rfqu/ignite,ptupitsyn/ignite,ilantukh/ignite,afinka77/ignite,WilliamDo/ignite,ascherbakoff/ignite,endian675/ignite,apache/ignite,ptupitsyn/ignite,StalkXT/ignite,amirakhmedov/ignite,daradurvs/ignite,sk0x50/ignite,vladisav/ignite,irudyak/ignite,andrey-kuznetsov/ignite,apache/ignite,StalkXT/ignite,nizhikov/ignite,ntikhonov/ignite,SomeFire/ignite,vladisav/ignite,mcherkasov/ignite,nizhikov/ignite,alexzaitzev/ignite,a1vanov/ignite,wmz7year/ignite,nivanov/ignite,a1vanov/ignite,shroman/ignite,afinka77/ignite,vladisav/ignite,sk0x50/ignite,nivanov/ignite,ilantukh/ignite,ptupitsyn/ignite,amirakhmedov/ignite,samaitra/ignite,samaitra/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,psadusumilli/ignite,BiryukovVA/ignite,amirakhmedov/ignite,vldpyatkov/ignite,NSAmelchev/ignite,pperalta/ignite,SharplEr/ignite,mcherkasov/ignite,psadusumilli/ignite,a1vanov/ignite,afinka77/ignite,wmz7year/ignite,SharplEr/ignite,shroman/ignite,pperalta/ignite,SharplEr/ignite,alexzaitzev/ignite,StalkXT/ignite,afinka77/ignite,a1vanov/ignite,psadusumilli/ignite,alexzaitzev/ignite,chandresh-pancholi/ignite,xtern/ignite,sk0x50/ignite,ntikhonov/ignite,chandresh-pancholi/ignite,vladisav/ignite,apache/ignite,nizhikov/ignite,ilantukh/ignite,ascherbakoff/ignite,dream-x/ignite,StalkXT/ignite,NSAmelchev/ignite,apache/ignite,dream-x/ignite,dream-x/ignite,irudyak/ignite,vladisav/ignite,samaitra/ignite,NSAmelchev/ignite,ptupitsyn/ignite,BiryukovVA/ignite,ptupitsyn/ignite,xtern/ignite,shroman/ignite,endian675/ignite,apache/ignite,pperalta/ignite,afinka77/ignite,xtern/ignite,samaitra/ignite,mcherkasov/ignite,BiryukovVA/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,mcherkasov/ignite,leveyj/ignite,irudyak/ignite,amirakhmedov/ignite,endian675/ignite,endian675/ignite,ptupitsyn/ignite,ptupitsyn/ignite,voipp/ignite,wmz7year/ignite,BiryukovVA/ignite,wmz7year/ignite,ascherbakoff/ignite,vadopolski/ignite,ptupitsyn/ignite,ascherbakoff/ignite,nizhikov/ignite,mcherkasov/ignite,vldpyatkov/ignite,NSAmelchev/ignite,vadopolski/ignite,daradurvs/ignite,NSAmelchev/ignite,leveyj/ignite,ilantukh/ignite,mcherkasov/ignite,WilliamDo/ignite,BiryukovVA/ignite,rfqu/ignite,SharplEr/ignite,vladisav/ignite,nizhikov/ignite,alexzaitzev/ignite,andrey-kuznetsov/ignite,ntikhonov/ignite,ilantukh/ignite,wmz7year/ignite,ilantukh/ignite,SomeFire/ignite,shroman/ignite,voipp/ignite,chandresh-pancholi/ignite,a1vanov/ignite,SomeFire/ignite,daradurvs/ignite,alexzaitzev/ignite,rfqu/ignite,irudyak/ignite,daradurvs/ignite,a1vanov/ignite,vadopolski/ignite,xtern/ignite,SharplEr/ignite,afinka77/ignite,nivanov/ignite,voipp/ignite,irudyak/ignite,chandresh-pancholi/ignite,rfqu/ignite,wmz7year/ignite,sk0x50/ignite,irudyak/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,psadusumilli/ignite,NSAmelchev/ignite,leveyj/ignite,andrey-kuznetsov/ignite,psadusumilli/ignite,pperalta/ignite,nizhikov/ignite,ascherbakoff/ignite,StalkXT/ignite,SomeFire/ignite,mcherkasov/ignite,alexzaitzev/ignite,dream-x/ignite,nivanov/ignite,shroman/ignite,nivanov/ignite,dream-x/ignite,nivanov/ignite,ntikhonov/ignite,WilliamDo/ignite,BiryukovVA/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,rfqu/ignite,NSAmelchev/ignite,SharplEr/ignite,psadusumilli/ignite,ilantukh/ignite,ntikhonov/ignite,afinka77/ignite,vladisav/ignite,vadopolski/ignite,samaitra/ignite,nivanov/ignite,voipp/ignite,SomeFire/ignite,vadopolski/ignite,amirakhmedov/ignite,pperalta/ignite,samaitra/ignite,leveyj/ignite,sk0x50/ignite,nizhikov/ignite,rfqu/ignite,irudyak/ignite,irudyak/ignite,daradurvs/ignite,endian675/ignite,WilliamDo/ignite,WilliamDo/ignite,WilliamDo/ignite,StalkXT/ignite,daradurvs/ignite,xtern/ignite,SomeFire/ignite,alexzaitzev/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,dream-x/ignite,alexzaitzev/ignite,ascherbakoff/ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,leveyj/ignite,rfqu/ignite,voipp/ignite,samaitra/ignite,SharplEr/ignite,andrey-kuznetsov/ignite,vladisav/ignite,alexzaitzev/ignite,ascherbakoff/ignite,WilliamDo/ignite,vadopolski/ignite,daradurvs/ignite,voipp/ignite,amirakhmedov/ignite,apache/ignite,BiryukovVA/ignite,pperalta/ignite,amirakhmedov/ignite,daradurvs/ignite,nizhikov/ignite,StalkXT/ignite,vadopolski/ignite,nivanov/ignite,ilantukh/ignite,SharplEr/ignite,a1vanov/ignite,vldpyatkov/ignite,ilantukh/ignite,shroman/ignite,voipp/ignite,SomeFire/ignite,vadopolski/ignite,chandresh-pancholi/ignite,afinka77/ignite,apache/ignite,dream-x/ignite,xtern/ignite,samaitra/ignite,mcherkasov/ignite,xtern/ignite,daradurvs/ignite,wmz7year/ignite,endian675/ignite,vldpyatkov/ignite,sk0x50/ignite,ptupitsyn/ignite,SomeFire/ignite,vldpyatkov/ignite,ptupitsyn/ignite,dream-x/ignite,a1vanov/ignite,pperalta/ignite,chandresh-pancholi/ignite,xtern/ignite,pperalta/ignite,BiryukovVA/ignite,shroman/ignite,nizhikov/ignite,leveyj/ignite,wmz7year/ignite,shroman/ignite,BiryukovVA/ignite,irudyak/ignite | modules/platforms/dotnet/Apache.Ignite.EntityFramework/DbCachingPolicy.cs | modules/platforms/dotnet/Apache.Ignite.EntityFramework/DbCachingPolicy.cs | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.EntityFramework
{
using System;
/// <summary>
/// Default caching policy implementation: everything is cached with <see cref="DbCachingMode.ReadWrite"/>,
/// no expiration.
/// </summary>
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class DbCachingPolicy : IDbCachingPolicy
{
/// <summary>
/// Determines whether the specified query can be cached.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <returns>
/// <c>true</c> if the specified query can be cached; otherwise, <c>false</c>.
/// </returns>
public virtual bool CanBeCached(DbQueryInfo queryInfo)
{
return true;
}
/// <summary>
/// Determines whether specified number of rows should be cached.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <param name="rowCount">The count of fetched rows.</param>
/// <returns></returns>
public virtual bool CanBeCached(DbQueryInfo queryInfo, int rowCount)
{
return true;
}
/// <summary>
/// Gets the absolute expiration timeout for a given query.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <returns>Expiration timeout. <see cref="TimeSpan.MaxValue"/> for no expiration.</returns>
public virtual TimeSpan GetExpirationTimeout(DbQueryInfo queryInfo)
{
return TimeSpan.MaxValue;
}
/// <summary>
/// Gets the caching strategy for a give query.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <returns>Caching strategy for the query.</returns>
public virtual DbCachingMode GetCachingMode(DbQueryInfo queryInfo)
{
return DbCachingMode.ReadWrite;
}
}
} | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.EntityFramework
{
using System;
/// <summary>
/// Default caching policy implementation: everything is cached with <see cref="DbCachingMode.ReadWrite"/>,
/// no expiration.
/// </summary>
public class DbCachingPolicy : IDbCachingPolicy
{
/// <summary>
/// Determines whether the specified query can be cached.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <returns>
/// <c>true</c> if the specified query can be cached; otherwise, <c>false</c>.
/// </returns>
public virtual bool CanBeCached(DbQueryInfo queryInfo)
{
return true;
}
/// <summary>
/// Determines whether specified number of rows should be cached.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <param name="rowCount">The count of fetched rows.</param>
/// <returns></returns>
public virtual bool CanBeCached(DbQueryInfo queryInfo, int rowCount)
{
return true;
}
/// <summary>
/// Gets the absolute expiration timeout for a given query.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <returns>Expiration timeout. <see cref="TimeSpan.MaxValue"/> for no expiration.</returns>
public virtual TimeSpan GetExpirationTimeout(DbQueryInfo queryInfo)
{
return TimeSpan.MaxValue;
}
/// <summary>
/// Gets the caching strategy for a give query.
/// </summary>
/// <param name="queryInfo">The query information.</param>
/// <returns>Caching strategy for the query.</returns>
public virtual DbCachingMode GetCachingMode(DbQueryInfo queryInfo)
{
return DbCachingMode.ReadWrite;
}
}
} | apache-2.0 | C# |
da6ee05dd689646d5c4831d9c1d7cc149754d184 | Fix not being able to drag non-snaked sliders | UselessToucan/osu,peppy/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,johnneijzen/osu,2yangk23/osu,EVAST9919/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu | osu.Game.Rulesets.Osu/Edit/Blueprints/Sliders/SliderSelectionBlueprint.cs | osu.Game.Rulesets.Osu/Edit/Blueprints/Sliders/SliderSelectionBlueprint.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders
{
public class SliderSelectionBlueprint : OsuSelectionBlueprint<Slider>
{
protected readonly SliderBodyPiece BodyPiece;
protected readonly SliderCircleSelectionBlueprint HeadBlueprint;
protected readonly SliderCircleSelectionBlueprint TailBlueprint;
public SliderSelectionBlueprint(DrawableSlider slider)
: base(slider)
{
var sliderObject = (Slider)slider.HitObject;
InternalChildren = new Drawable[]
{
BodyPiece = new SliderBodyPiece(),
HeadBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.Start),
TailBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.End),
new PathControlPointVisualiser(sliderObject),
};
}
protected override void Update()
{
base.Update();
BodyPiece.UpdateFrom(HitObject);
}
public override Vector2 SelectionPoint => HeadBlueprint.SelectionPoint;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => BodyPiece.ReceivePositionalInputAt(screenSpacePos);
protected virtual SliderCircleSelectionBlueprint CreateCircleSelectionBlueprint(DrawableSlider slider, SliderPosition position) => new SliderCircleSelectionBlueprint(slider, position);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders
{
public class SliderSelectionBlueprint : OsuSelectionBlueprint<Slider>
{
protected readonly SliderBodyPiece BodyPiece;
protected readonly SliderCircleSelectionBlueprint HeadBlueprint;
protected readonly SliderCircleSelectionBlueprint TailBlueprint;
public SliderSelectionBlueprint(DrawableSlider slider)
: base(slider)
{
var sliderObject = (Slider)slider.HitObject;
InternalChildren = new Drawable[]
{
BodyPiece = new SliderBodyPiece(),
HeadBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.Start),
TailBlueprint = CreateCircleSelectionBlueprint(slider, SliderPosition.End),
new PathControlPointVisualiser(sliderObject),
};
}
protected override void Update()
{
base.Update();
BodyPiece.UpdateFrom(HitObject);
}
public override Vector2 SelectionPoint => HeadBlueprint.SelectionPoint;
protected virtual SliderCircleSelectionBlueprint CreateCircleSelectionBlueprint(DrawableSlider slider, SliderPosition position) => new SliderCircleSelectionBlueprint(slider, position);
}
}
| mit | C# |
77ab4f24365c1b4eb563ea9995204e4071d9571b | remove blank spaces | pthivierge/web-service-reader-for-pi-system,pthivierge/web-service-reader-for-pi-system,pthivierge/data-collection-service-for-pi-system,pthivierge/data-collection-service-for-pi-system,pthivierge/web-service-reader-for-pi-system,pthivierge/data-collection-service-for-pi-system | Service/Program.cs | Service/Program.cs | using System;
using System.Configuration.Install;
using System.Reflection;
using System.ServiceProcess;
using log4net;
namespace FDS.Service
{
internal static class Program
{
private static readonly ILog _logger = LogManager.GetLogger(typeof (Program));
/// <summary>
/// Service Main Entry Point
/// </summary>
private static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
if (Environment.UserInteractive)
{
_logger.Info("Starting service interractively");
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase[] ServicesToRun =
{
new Service()
};
ServiceBase.Run(ServicesToRun);
}
}
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_logger.Error(e.ExceptionObject);
}
}
}
| using System;
using System.Configuration.Install;
using System.Reflection;
using System.ServiceProcess;
using log4net;
namespace FDS.Service
{
internal static class Program
{
private static readonly ILog _logger = LogManager.GetLogger(typeof (Program));
/// <summary>
/// Service Main Entry Point
/// </summary>
private static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
if (Environment.UserInteractive)
{
_logger.Info("Starting service interractively");
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase[] ServicesToRun =
{
new Service()
};
ServiceBase.Run(ServicesToRun);
}
}
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_logger.Error(e.ExceptionObject);
}
}
}
| apache-2.0 | C# |
01829f3a614964bef76476aff4355f3b3e595378 | Update ShapeRenderer.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.Core/Renderers/ShapeRenderer.cs | src/Draw2D.Core/Renderers/ShapeRenderer.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Draw2D.Core.Style;
namespace Draw2D.Core.Renderers
{
public abstract class ShapeRenderer : ObservableObject
{
public abstract ISet<ShapeObject> Selected { get; set; }
public abstract void InvalidateCache(DrawStyle style);
public abstract void InvalidateCache(MatrixObject matrix);
public abstract void InvalidateCache(ShapeObject shape, DrawStyle style, double dx, double dy);
public abstract object PushMatrix(object dc, MatrixObject matrix);
public abstract void PopMatrix(object dc, object state);
public abstract void DrawLine(object dc, IPoint start, IPoint point, DrawStyle style, double dx, double dy);
public abstract void DrawCubicBezier(object dc, IPoint start, IPoint point1, IPoint point2, IPoint point3, DrawStyle style, double dx, double dy);
public abstract void DrawQuadraticBezier(object dc, IPoint start, IPoint point1, IPoint point2, DrawStyle style, double dx, double dy);
public abstract void DrawPath(object dc, IPath path, DrawStyle style, double dx, double dy);
public abstract void DrawRectangle(object dc, IPoint tl, IPoint br, DrawStyle style, double dx, double dy);
public abstract void DrawEllipse(object dc, IPoint tl, IPoint br, DrawStyle style, double dx, double dy);
public abstract void DrawText(object dc, IPoint tl, IPoint br, string text, DrawStyle style, double dx, double dy);
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Draw2D.Core.Shapes;
using Draw2D.Core.Style;
namespace Draw2D.Core.Renderers
{
public abstract class ShapeRenderer : ObservableObject
{
public abstract ISet<ShapeObject> Selected { get; set; }
public abstract void InvalidateCache(DrawStyle style);
public abstract void InvalidateCache(MatrixObject matrix);
public abstract void InvalidateCache(ShapeObject shape, DrawStyle style, double dx, double dy);
public abstract object PushMatrix(object dc, MatrixObject matrix);
public abstract void PopMatrix(object dc, object state);
public abstract void DrawLine(object dc, IPoint start, IPoint point, DrawStyle style, double dx, double dy);
public abstract void DrawCubicBezier(object dc, IPoint start, IPoint point1, IPoint point2, IPoint point3, DrawStyle style, double dx, double dy);
public abstract void DrawQuadraticBezier(object dc, IPoint start, IPoint point1, IPoint point2, DrawStyle style, double dx, double dy);
public abstract void DrawPath(object dc, IPath path, DrawStyle style, double dx, double dy);
public abstract void DrawRectangle(object dc, IPoint tl, IPoint br, DrawStyle style, double dx, double dy);
public abstract void DrawEllipse(object dc, IPoint tl, IPoint br, DrawStyle style, double dx, double dy);
public abstract void DrawText(object dc, IPoint tl, IPoint br, string text, DrawStyle style, double dx, double dy);
}
}
| mit | C# |
393b566966c5cd8d6be9b765ebd79e8e9280f1fd | Make PercentageCounter use FormatAccuracy | EVAST9919/osu,NeoAdonis/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,smoogipooo/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu | osu.Game/Graphics/UserInterface/PercentageCounter.cs | osu.Game/Graphics/UserInterface/PercentageCounter.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Game.Utils;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Used as an accuracy counter. Represented visually as a percentage.
/// </summary>
public class PercentageCounter : RollingCounter<double>
{
protected override double RollingDuration => 750;
private float epsilon => 1e-10f;
public void SetFraction(float numerator, float denominator)
{
Current.Value = Math.Abs(denominator) < epsilon ? 1.0f : numerator / denominator;
}
public PercentageCounter()
{
DisplayedCountSpriteText.Font = DisplayedCountSpriteText.Font.With(fixedWidth: true);
Current.Value = DisplayedCount = 1.0f;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours) => AccentColour = colours.BlueLighter;
protected override string FormatCount(double count) => count.FormatAccuracy();
protected override double GetProportionalDuration(double currentValue, double newValue)
{
return Math.Abs(currentValue - newValue) * RollingDuration * 100.0f;
}
public override void Increment(double amount)
{
Current.Value += amount;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Used as an accuracy counter. Represented visually as a percentage.
/// </summary>
public class PercentageCounter : RollingCounter<double>
{
protected override double RollingDuration => 750;
private float epsilon => 1e-10f;
public void SetFraction(float numerator, float denominator)
{
Current.Value = Math.Abs(denominator) < epsilon ? 1.0f : numerator / denominator;
}
public PercentageCounter()
{
DisplayedCountSpriteText.Font = DisplayedCountSpriteText.Font.With(fixedWidth: true);
Current.Value = DisplayedCount = 1.0f;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours) => AccentColour = colours.BlueLighter;
protected override string FormatCount(double count)
{
return $@"{count:P2}";
}
protected override double GetProportionalDuration(double currentValue, double newValue)
{
return Math.Abs(currentValue - newValue) * RollingDuration * 100.0f;
}
public override void Increment(double amount)
{
Current.Value += amount;
}
}
}
| mit | C# |
cfc28164d660eaaffac600543586180175da540a | Document code editor | lambdacasserole/sulfide | Sulfide/CodeDocument.cs | Sulfide/CodeDocument.cs | using System.IO;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media;
using ICSharpCode.AvalonEdit;
using WeifenLuo.WinFormsUI.Docking;
namespace Sulfide
{
/// <summary>
/// Represents a document open in a code editor tab.
/// </summary>
public class CodeDocument : DockContent, IDocument
{
private string _openFilePath;
/// <summary>
/// Gets the text editor containing the document.
/// </summary>
public TextEditor Editor { get; }
public string OpenFilePath
{
get { return _openFilePath; }
set
{
_openFilePath = value;
Text = Path.GetFileName(_openFilePath);
}
}
public ISaveStrategy SaveStrategy { get; }
public IClipboardStrategy ClipboardStrategy { get; }
public IPrintingStrategy PrintingStrategy { get; }
/// <summary>
/// Initializes a new instance of a code document.
/// </summary>
public CodeDocument()
{
// The code editor is a WPF control that needs hosting.
var host = new ElementHost {Dock = DockStyle.Fill};
// Initialize WPF code editor control.
Editor = new TextEditor
{
ShowLineNumbers = true,
FontFamily = new FontFamily("Consolas"),
FontSize = 12.75f,
SyntaxHighlighting = SyntaxHighlightingLoader.LoadBooHighlightingDefinition()
};
// Add to host and add host to control.
host.Child = Editor;
Controls.Add(host);
// Initialize strategies.
SaveStrategy = new CodeDocumentSaveStrategy(this);
ClipboardStrategy = new CodeDocumentClipboardStrategy(this);
PrintingStrategy = new CodeDocumentPrintingStrategy(this);
}
}
}
| using System.IO;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media;
using ICSharpCode.AvalonEdit;
using WeifenLuo.WinFormsUI.Docking;
namespace Sulfide
{
public class CodeDocument : DockContent, IDocument
{
private string _openFilePath;
public TextEditor Editor { get; }
public string OpenFilePath
{
get { return _openFilePath; }
set
{
_openFilePath = value;
Text = Path.GetFileName(_openFilePath);
}
}
public CodeDocument()
{
var host = new ElementHost {Dock = DockStyle.Fill};
Editor = new TextEditor
{
ShowLineNumbers = true,
FontFamily = new FontFamily("Consolas"),
FontSize = 12.75f,
SyntaxHighlighting = SyntaxHighlightingLoader.LoadBooHighlightingDefinition()
};
host.Child = Editor;
Controls.Add(host);
SaveStrategy = new CodeDocumentSaveStrategy(this);
ClipboardStrategy = new CodeDocumentClipboardStrategy(this);
PrintingStrategy = new CodeDocumentPrintingStrategy(this);
}
public ISaveStrategy SaveStrategy { get; }
public IClipboardStrategy ClipboardStrategy { get; }
public IPrintingStrategy PrintingStrategy { get; }
}
}
| mit | C# |
380859e06e11137716ec7b2748214a58a213b0b4 | Set clock on video directly; ignore long frames | UselessToucan/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,smoogipooo/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,2yangk23/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new | osu.Game.Tournament/Components/TourneyVideo.cs | osu.Game.Tournament/Components/TourneyVideo.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Video;
using osu.Framework.Timing;
using osu.Game.Graphics;
namespace osu.Game.Tournament.Components
{
public class TourneyVideo : CompositeDrawable
{
private readonly VideoSprite video;
private readonly ManualClock manualClock;
public TourneyVideo(Stream stream)
{
if (stream == null)
{
InternalChild = new Box
{
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)),
RelativeSizeAxes = Axes.Both,
};
}
else
InternalChild = video = new VideoSprite(stream)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
Clock = new FramedClock(manualClock = new ManualClock())
};
}
public bool Loop
{
set
{
if (video != null)
video.Loop = value;
}
}
protected override void Update()
{
base.Update();
if (manualClock != null && Clock.ElapsedFrameTime < 100)
{
// we want to avoid seeking as much as possible, because we care about performance, not sync.
// to avoid seeking completely, we only increment out local clock when in an updating state.
manualClock.CurrentTime += Clock.ElapsedFrameTime;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.IO;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Video;
using osu.Framework.Timing;
using osu.Game.Graphics;
namespace osu.Game.Tournament.Components
{
public class TourneyVideo : CompositeDrawable
{
private readonly VideoSprite video;
private ManualClock manualClock;
private IFrameBasedClock sourceClock;
public TourneyVideo(Stream stream)
{
if (stream == null)
{
InternalChild = new Box
{
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)),
RelativeSizeAxes = Axes.Both,
};
}
else
InternalChild = video = new VideoSprite(stream)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
};
}
public bool Loop
{
set
{
if (video != null)
video.Loop = value;
}
}
protected override void LoadComplete()
{
base.LoadComplete();
sourceClock = Clock;
Clock = new FramedClock(manualClock = new ManualClock());
}
protected override void Update()
{
base.Update();
// we want to avoid seeking as much as possible, because we care about performance, not sync.
// to avoid seeking completely, we only increment out local clock when in an updating state.
manualClock.CurrentTime += sourceClock.ElapsedFrameTime;
}
}
}
| mit | C# |
c7ae06a8c2c192d26aa2b9ce7c6e7719f3e2ca7d | Fix occasional grey text in textboxes | lytico/xwt,hwthomas/xwt,cra0zy/xwt,akrisiun/xwt,residuum/xwt,antmicro/xwt,mminns/xwt,hamekoz/xwt,mminns/xwt,directhex/xwt,iainx/xwt,TheBrainTech/xwt,steffenWi/xwt,mono/xwt,sevoku/xwt | Xwt.WPF/Xwt.WPFBackend/ExTextBox.cs | Xwt.WPF/Xwt.WPFBackend/ExTextBox.cs | //
// ExTextBox.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Xwt.WPFBackend.Utilities
{
public class ExTextBox
: System.Windows.Controls.TextBox, IWpfWidget
{
public WidgetBackend Backend { get; set; }
protected override System.Windows.Size MeasureOverride (System.Windows.Size constraint)
{
var s = base.MeasureOverride (constraint);
return Backend.MeasureOverride (constraint, s);
}
public string PlaceholderText
{
get { return this.placeholderText; }
set
{
if (this.placeholderText == value)
return;
UpdatePlaceholder (value);
}
}
private bool showFrame = true;
public bool ShowFrame
{
get { return this.showFrame; }
set
{
if (this.showFrame == value)
return;
if (value)
ClearValue (Control.BorderBrushProperty);
else
BorderBrush = null;
this.showFrame = value;
}
}
private string placeholderText;
private void UpdatePlaceholder (string newPlaceholder)
{
if (Text == this.placeholderText)
Text = newPlaceholder;
this.placeholderText = newPlaceholder;
if (IsFocused && Text == (PlaceholderText ?? String.Empty))
{
Text = null;
ClearValue (Control.ForegroundProperty);
}
else if (!IsFocused && String.IsNullOrEmpty (Text))
{
Text = PlaceholderText;
Foreground = Brushes.LightGray;
}
}
protected override void OnGotFocus (RoutedEventArgs e)
{
base.OnGotFocus (e);
UpdatePlaceholder (this.placeholderText);
}
protected override void OnLostFocus (RoutedEventArgs e)
{
base.OnLostFocus (e);
UpdatePlaceholder (this.placeholderText);
}
}
}
| //
// ExTextBox.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Xwt.WPFBackend.Utilities
{
public class ExTextBox
: System.Windows.Controls.TextBox, IWpfWidget
{
public WidgetBackend Backend { get; set; }
protected override System.Windows.Size MeasureOverride (System.Windows.Size constraint)
{
var s = base.MeasureOverride (constraint);
return Backend.MeasureOverride (constraint, s);
}
public string PlaceholderText
{
get { return this.placeholderText; }
set
{
if (this.placeholderText == value)
return;
UpdatePlaceholder (value);
}
}
private bool showFrame = true;
public bool ShowFrame
{
get { return this.showFrame; }
set
{
if (this.showFrame == value)
return;
if (value)
ClearValue (Control.BorderBrushProperty);
else
BorderBrush = null;
this.showFrame = value;
}
}
private string placeholderText;
private void UpdatePlaceholder (string newPlaceholder)
{
if (Text == this.placeholderText)
Text = newPlaceholder;
this.placeholderText = newPlaceholder;
if (IsFocused && Text == PlaceholderText)
{
Text = null;
ClearValue (Control.ForegroundProperty);
}
else if (!IsFocused && String.IsNullOrEmpty (Text))
{
Text = PlaceholderText;
Foreground = Brushes.LightGray;
}
}
protected override void OnGotFocus (RoutedEventArgs e)
{
base.OnGotFocus (e);
UpdatePlaceholder (this.placeholderText);
}
protected override void OnLostFocus (RoutedEventArgs e)
{
base.OnLostFocus (e);
UpdatePlaceholder (this.placeholderText);
}
}
}
| mit | C# |
aca47936c8b750b30663298a1adfbc4406a3a645 | Add Research Category. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Data/ProjectCategory/ProjectCategoriesRepository.cs | src/CompetitionPlatform/Data/ProjectCategory/ProjectCategoriesRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompetitionPlatform.Data.ProjectCategory;
namespace CompetitionPlatform.Data.ProjectCategory
{
public class ProjectCategoriesRepository : IProjectCategoriesRepository
{
public List<string> GetCategories()
{
return new List<string>
{
"Blockchain",
"Development",
"Design",
"Testing",
"Finance",
"Technology",
"Bitcoin",
"Communications and media",
"Research"
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompetitionPlatform.Data.ProjectCategory;
namespace CompetitionPlatform.Data.ProjectCategory
{
public class ProjectCategoriesRepository : IProjectCategoriesRepository
{
public List<string> GetCategories()
{
return new List<string>
{
"Blockchain",
"Development",
"Design",
"Testing",
"Finance",
"Technology",
"Bitcoin",
"Communications and media"
};
}
}
}
| mit | C# |
d207646599e45c78d3f46ff17aecf1d4dafbf2b7 | test csharp 7 | tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,DingpingZhang/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,tipunch74/MaterialDesignInXamlToolkit,ButchersBoy/MaterialDesignInXamlToolkit | MaterialDesignThemes.Wpf/Converters/MathMultipleConverter.cs | MaterialDesignThemes.Wpf/Converters/MathMultipleConverter.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace MaterialDesignThemes.Wpf.Converters
{
public sealed class MathMultipleConverter : IMultiValueConverter
{
public MathOperation Operation { get; set; }
public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.Length < 2 || value[0] == null || value[1] == null) return Binding.DoNothing;
if (!double.TryParse(value[0].ToString(), out double value1) || !double.TryParse(value[1].ToString(), out double value2))
return 0;
switch (Operation)
{
default:
// (case MathOperation.Add:)
return value1 + value2;
case MathOperation.Divide:
return value1 / value2;
case MathOperation.Multiply:
return value1 * value2;
case MathOperation.Subtract:
return value1 - value2;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace MaterialDesignThemes.Wpf.Converters
{
public sealed class MathMultipleConverter : IMultiValueConverter
{
public MathOperation Operation { get; set; }
public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.Length < 2 || value[0] == null || value[1] == null) return Binding.DoNothing;
double value1, value2;
if (!double.TryParse(value[0].ToString(), out value1) || !double.TryParse(value[1].ToString(), out value2))
return 0;
switch (Operation)
{
default:
// (case MathOperation.Add:)
return value1 + value2;
case MathOperation.Divide:
return value1 / value2;
case MathOperation.Multiply:
return value1 * value2;
case MathOperation.Subtract:
return value1 - value2;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | mit | C# |
0d13eaef34542d17ccec21f88019e5a1c1199c17 | Adjust window width to ensure popout window -> Edit is targeted | jlewin/MatterControl,rytz/MatterControl,mmoening/MatterControl,rytz/MatterControl,tellingmachine/MatterControl,jlewin/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,rytz/MatterControl,larsbrubaker/MatterControl,tellingmachine/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl | Tests/MatterControl.AutomationTests/SqLiteLibraryProvider.cs | Tests/MatterControl.AutomationTests/SqLiteLibraryProvider.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.UI.Tests;
using MatterHackers.GuiAutomation;
using MatterHackers.MatterControl.PartPreviewWindow;
using NUnit.Framework;
namespace MatterHackers.MatterControl.Tests.Automation
{
[TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain]
public class SqLiteLibraryProviderTests
{
[Test, Apartment(ApartmentState.STA)]
public async Task LibraryQueueViewRefreshesOnAddItem()
{
AutomationTest testToRun = (testRunner) =>
{
testRunner.CloseSignInAndPrinterSelect();
testRunner.ClickByName("Library Tab", 5);
testRunner.NavigateToFolder("Local Library Row Item Collection");
testRunner.Wait(1);
testRunner.ClickByName("Row Item Calibration - Box");
testRunner.ClickByName("Row Item Calibration - Box View Button");
testRunner.Wait(1);
SystemWindow systemWindow;
GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
View3DWidget view3D = partPreview as View3DWidget;
testRunner.ClickByName("3D View Edit", 3);
testRunner.ClickByName("3D View Copy", 3);
// wait for the copy to finish
testRunner.Wait(.1);
testRunner.ClickByName("3D View Remove", 3);
testRunner.ClickByName("Save As Menu", 3);
testRunner.ClickByName("Save As Menu Item", 3);
testRunner.Wait(1);
testRunner.Type("0Test Part");
testRunner.NavigateToFolder("Local Library Row Item Collection");
testRunner.ClickByName("Save As Save Button", 1);
view3D.CloseOnIdle();
testRunner.Wait(.5);
// ensure that it is now in the library folder (that the folder updated)
Assert.IsTrue(testRunner.WaitForName("Row Item 0Test Part", 5), "The part we added should be in the library");
testRunner.Wait(.5);
return Task.FromResult(0);
};
await MatterControlUtilities.RunTest(testToRun, queueItemFolderToAdd: QueueTemplate.Three_Queue_Items, overrideWidth: 600);
}
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.UI.Tests;
using MatterHackers.GuiAutomation;
using MatterHackers.MatterControl.PartPreviewWindow;
using NUnit.Framework;
namespace MatterHackers.MatterControl.Tests.Automation
{
[TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain]
public class SqLiteLibraryProviderTests
{
[Test, Apartment(ApartmentState.STA)]
public async Task LibraryQueueViewRefreshesOnAddItem()
{
AutomationTest testToRun = (testRunner) =>
{
testRunner.CloseSignInAndPrinterSelect();
testRunner.ClickByName("Library Tab", 5);
testRunner.NavigateToFolder("Local Library Row Item Collection");
testRunner.Wait(1);
testRunner.ClickByName("Row Item Calibration - Box");
testRunner.ClickByName("Row Item Calibration - Box View Button");
testRunner.Wait(1);
SystemWindow systemWindow;
GuiWidget partPreview = testRunner.GetWidgetByName("View3DWidget", out systemWindow, 3);
View3DWidget view3D = partPreview as View3DWidget;
testRunner.ClickByName("3D View Edit", 3);
testRunner.ClickByName("3D View Copy", 3);
// wait for the copy to finish
testRunner.Wait(.1);
testRunner.ClickByName("3D View Remove", 3);
testRunner.ClickByName("Save As Menu", 3);
testRunner.ClickByName("Save As Menu Item", 3);
testRunner.Wait(1);
testRunner.Type("0Test Part");
testRunner.NavigateToFolder("Local Library Row Item Collection");
testRunner.ClickByName("Save As Save Button", 1);
view3D.CloseOnIdle();
testRunner.Wait(.5);
// ensure that it is now in the library folder (that the folder updated)
Assert.IsTrue(testRunner.WaitForName("Row Item 0Test Part", 5), "The part we added should be in the library");
testRunner.Wait(.5);
return Task.FromResult(0);
};
await MatterControlUtilities.RunTest(testToRun, queueItemFolderToAdd: QueueTemplate.Three_Queue_Items);
}
}
} | bsd-2-clause | C# |
be4e52cfc4785711915e3106c323cde6cba5f4a9 | Use discards to fix CI complaints | ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework | osu.Framework.Tests/Containers/TestSceneEnumeratorVersion.cs | osu.Framework.Tests/Containers/TestSceneEnumeratorVersion.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.Containers
{
public class TestSceneEnumeratorVersion : FrameworkTestScene
{
private Container parent;
[SetUp]
public void SetUp() => Schedule(() =>
{
Child = parent = new Container
{
Child = new Container()
};
});
[Test]
public void TestEnumeratingNormally()
{
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var _ in parent)
{
}
}));
}
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var _ in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
[Test]
public void TestClearDuringEnumerationFails()
{
AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var _ in parent)
{
parent.Clear();
}
}));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.Containers
{
public class TestSceneEnumeratorVersion : FrameworkTestScene
{
private Container parent;
[SetUp]
public void SetUp() => Schedule(() =>
{
Child = parent = new Container
{
Child = new Container()
};
});
[Test]
public void TestEnumeratingNormally()
{
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
}
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
[Test]
public void TestClearDuringEnumerationFails()
{
AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Clear();
}
}));
}
}
}
| mit | C# |
977e635db0c5b27145db7025f20cc60b2ceaf426 | add usage example | fredatgithub/AtlasReloaded | UsageConsole/Program.cs | UsageConsole/Program.cs | using System;
using Ritter.Atlas;
namespace UsageConsole
{
class Program
{
static void Main()
{
Action<string> Display = s => Console.WriteLine(s);
var zipcode = new ZipCode { Id = "17011" };
var zipcode2 = new ZipCode { Id = "90210" };
var zipcode3 = new ZipCode { Id = "75017" };
var zipcode4 = new ZipCode { Id = "75020" };
var zipcode5 = new ZipCode { Id = "12345" };
var zipcode6 = new ZipCode { Id = "12345" };
Console.ReadKey();
}
}
} | using System;
using Ritter.Atlas;
namespace UsageConsole
{
class Program
{
static void Main()
{
Action<string> Display = s => Console.WriteLine(s);
var zipcode = new ZipCode { Id = "17011" };
var zipcode2 = new ZipCode { Id = "90210" };
var zipcode3 = new ZipCode { Id = "75017" };
var zipcode4 = new ZipCode { Id = "75020" };
var zipcode5 = new ZipCode { Id = "12345" };
Console.ReadKey();
}
}
} | mit | C# |
c80b6417aa363ee38a3869ad78119ac3fae8e3b9 | Remove *Modifier directives | SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia | src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/IgnoredDirectivesTransformer.cs | src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/Transformers/IgnoredDirectivesTransformer.cs | using System.Linq;
using XamlX;
using XamlX.Ast;
using XamlX.Transform;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
class IgnoredDirectivesTransformer : IXamlAstTransformer
{
public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
if (node is XamlAstObjectNode no)
{
foreach (var d in no.Children.OfType<XamlAstXmlDirective>().ToList())
{
if (d.Namespace == XamlNamespaces.Xaml2006)
{
if (d.Name == "Precompile" ||
d.Name == "Class" ||
d.Name == "FieldModifier" ||
d.Name == "ClassModifier")
no.Children.Remove(d);
}
}
}
return node;
}
}
}
| using System.Linq;
using XamlX;
using XamlX.Ast;
using XamlX.Transform;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
class IgnoredDirectivesTransformer : IXamlAstTransformer
{
public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
if (node is XamlAstObjectNode no)
{
foreach (var d in no.Children.OfType<XamlAstXmlDirective>().ToList())
{
if (d.Namespace == XamlNamespaces.Xaml2006)
{
if (d.Name == "Precompile" || d.Name == "Class")
no.Children.Remove(d);
}
}
}
return node;
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.