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 |
|---|---|---|---|---|---|---|---|---|
d1bc91e44e94d047c455804dcecdc80ceae2e6e6 | Fix NullReferenceException | luberda-molinet/FFImageLoading,molinch/FFImageLoading,petlack/FFImageLoading,AndreiMisiukevich/FFImageLoading,kalarepa/FFImageLoading,daniel-luberda/FFImageLoading | source/FFImageLoading.Touch/Work/DataResolver/FilePathDataResolver.cs | source/FFImageLoading.Touch/Work/DataResolver/FilePathDataResolver.cs | using System;
using FFImageLoading.Work;
using System.IO;
using FFImageLoading.IO;
using System.Threading.Tasks;
using System.Threading;
using UIKit;
namespace FFImageLoading.Work.DataResolver
{
public class FilePathDataResolver : IDataResolver
{
private static int _screenScale;
private readonly ImageSource _source;
static FilePathDataResolver()
{
UIScreen.MainScreen.InvokeOnMainThread(() =>
{
_screenScale = (int)UIScreen.MainScreen.Scale;
});
}
public FilePathDataResolver(ImageSource source)
{
_source = source;
}
public Task<UIImageData> GetData(string identifier, CancellationToken token)
{
int scale = _screenScale;
if (scale > 1)
{
var filename = Path.GetFileNameWithoutExtension(identifier);
var extension = Path.GetExtension(identifier);
const string pattern = "{0}@{1}x{2}";
while (scale > 1)
{
var file = String.Format(pattern, filename, scale, extension);
if (FileStore.Exists(file))
{
return GetDataInternal(file, token);
}
scale--;
}
}
if (FileStore.Exists(identifier))
{
return GetDataInternal(identifier, token);
}
return Task.FromResult((UIImageData)null);
}
public void Dispose() {
}
private async Task<UIImageData> GetDataInternal(string identifier, CancellationToken token)
{
var bytes = await FileStore.ReadBytesAsync(identifier).ConfigureAwait(false);
var result = (LoadingResult)(int)_source; // Some values of ImageSource and LoadingResult are shared
return new UIImageData() { Data = bytes, Result = result, ResultIdentifier = identifier };
}
}
}
| using System;
using FFImageLoading.Work;
using System.IO;
using FFImageLoading.IO;
using System.Threading.Tasks;
using System.Threading;
using UIKit;
namespace FFImageLoading.Work.DataResolver
{
public class FilePathDataResolver : IDataResolver
{
private static int _screenScale;
private readonly ImageSource _source;
static FilePathDataResolver()
{
UIScreen.MainScreen.InvokeOnMainThread(() =>
{
_screenScale = (int)UIScreen.MainScreen.Scale;
});
}
public FilePathDataResolver(ImageSource source)
{
_source = source;
}
public Task<UIImageData> GetData(string identifier, CancellationToken token)
{
int scale = _screenScale;
if (scale > 1)
{
var filename = Path.GetFileNameWithoutExtension(identifier);
var extension = Path.GetExtension(identifier);
const string pattern = "{0}@{1}x{2}";
while (scale > 1)
{
var file = String.Format(pattern, filename, scale, extension);
if (FileStore.Exists(file))
{
return GetDataInternal(file, token);
}
scale--;
}
}
if (FileStore.Exists(identifier))
{
return GetDataInternal(identifier, token);
}
return null;
}
public void Dispose() {
}
private async Task<UIImageData> GetDataInternal(string identifier, CancellationToken token)
{
var bytes = await FileStore.ReadBytesAsync(identifier).ConfigureAwait(false);
var result = (LoadingResult)(int)_source; // Some values of ImageSource and LoadingResult are shared
return new UIImageData() { Data = bytes, Result = result, ResultIdentifier = identifier };
}
}
}
| mit | C# |
45239fc737423f05f63c93b05e72ef20a33ef267 | Update `TrueGameplayRate` accessing | ppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu | osu.Game/Screens/Play/HUD/ClicksPerSecond/ClicksPerSecondCalculator.cs | osu.Game/Screens/Play/HUD/ClicksPerSecond/ClicksPerSecondCalculator.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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
namespace osu.Game.Screens.Play.HUD.ClicksPerSecond
{
public class ClicksPerSecondCalculator : Component
{
private readonly List<double> timestamps = new List<double>();
[Resolved]
private IGameplayClock gameplayClock { get; set; } = null!;
[Resolved(canBeNull: true)]
private DrawableRuleset? drawableRuleset { get; set; }
public int Value { get; private set; }
// Even though `FrameStabilityContainer` caches as a `GameplayClock`, we need to check it directly via `drawableRuleset`
// as this calculator is not contained within the `FrameStabilityContainer` and won't see the dependency.
private IGameplayClock clock => drawableRuleset?.FrameStableClock ?? gameplayClock;
public ClicksPerSecondCalculator()
{
RelativeSizeAxes = Axes.Both;
}
public void AddInputTimestamp() => timestamps.Add(clock.CurrentTime);
protected override void Update()
{
base.Update();
double latestValidTime = clock.CurrentTime;
double earliestTimeValid = latestValidTime - 1000 * gameplayClock.GetTrueGameplayRate();
int count = 0;
for (int i = timestamps.Count - 1; i >= 0; i--)
{
// handle rewinding by removing future timestamps as we go
if (timestamps[i] > latestValidTime)
{
timestamps.RemoveAt(i);
continue;
}
if (timestamps[i] >= earliestTimeValid)
count++;
}
Value = count;
}
}
}
| // 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.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
namespace osu.Game.Screens.Play.HUD.ClicksPerSecond
{
public class ClicksPerSecondCalculator : Component
{
private readonly List<double> timestamps = new List<double>();
[Resolved]
private IGameplayClock gameplayClock { get; set; } = null!;
[Resolved(canBeNull: true)]
private DrawableRuleset? drawableRuleset { get; set; }
public int Value { get; private set; }
// Even though `FrameStabilityContainer` caches as a `GameplayClock`, we need to check it directly via `drawableRuleset`
// as this calculator is not contained within the `FrameStabilityContainer` and won't see the dependency.
private IGameplayClock clock => drawableRuleset?.FrameStableClock ?? gameplayClock;
public ClicksPerSecondCalculator()
{
RelativeSizeAxes = Axes.Both;
}
public void AddInputTimestamp() => timestamps.Add(clock.CurrentTime);
protected override void Update()
{
base.Update();
double latestValidTime = clock.CurrentTime;
double earliestTimeValid = latestValidTime - 1000 * gameplayClock.TrueGameplayRate;
int count = 0;
for (int i = timestamps.Count - 1; i >= 0; i--)
{
// handle rewinding by removing future timestamps as we go
if (timestamps[i] > latestValidTime)
{
timestamps.RemoveAt(i);
continue;
}
if (timestamps[i] >= earliestTimeValid)
count++;
}
Value = count;
}
}
}
| mit | C# |
1eff5128f4a9aa1741ee92eb34b7f05ed2c4cade | fix test to remove spaces when matching thread name in ThreadNameConverterTests.cs | Cayan-LLC/syslog4net,akramsaleh/syslog4net,jbeats/syslog4net,merchantwarehouse/syslog4net | src/test/unit/syslog4net.Tests/Converters/ThreadNameConverterTests.cs | src/test/unit/syslog4net.Tests/Converters/ThreadNameConverterTests.cs | using System.IO;
using System.Threading;
using log4net.Core;
using syslog4net.Converters;
using NUnit.Framework;
namespace syslog4net.Tests.Converters
{
[TestFixture]
public class ThreadNameConverterTests
{
[Test]
public void ConvertTest()
{
var writer = new StreamWriter(new MemoryStream());
var converter = new ThreadNameConverter();
converter.Format(writer, new LoggingEvent(new LoggingEventData()));
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
//converter will sanitize string and remove spaces so we need to match
Assert.AreEqual(Thread.CurrentThread.Name.Replace(" ", ""), result);
}
}
} | using System.IO;
using System.Threading;
using log4net.Core;
using syslog4net.Converters;
using NUnit.Framework;
namespace syslog4net.Tests.Converters
{
[TestFixture]
public class ThreadNameConverterTests
{
[Test]
public void ConvertTest()
{
var writer = new StreamWriter(new MemoryStream());
var converter = new ThreadNameConverter();
converter.Format(writer, new LoggingEvent(new LoggingEventData()));
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.AreEqual(Thread.CurrentThread.Name, result);
}
}
} | apache-2.0 | C# |
3b91a07942353a71bfa225cec7d6c98693500a98 | Tweak the latest news view. | bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes | Orchard.Source.1.8.1/src/Orchard.Web/Themes/LccNetwork.Bootstrap/Views/ProjectionWidgetLatestNews.cshtml | Orchard.Source.1.8.1/src/Orchard.Web/Themes/LccNetwork.Bootstrap/Views/ProjectionWidgetLatestNews.cshtml | @using System.Dynamic;
@using System.Linq;
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions;
@functions
{
dynamic GetMainPartFromContentItem(ContentItem item)
{
// get the ContentPart that has the same name as the item's ContentType
// so that we can access the item fields.
var contentType = item.TypeDefinition.Name;
var parts = item.Parts as List<ContentPart>;
return parts.First(p => p.PartDefinition.Name.Equals(contentType)); return mainPart;
}
dynamic GetMediaPartFromMediaLibraryPickerField(dynamic field, int index = 0)
{
// get the mediaPart at index in the media library picker field
return field != null &&
field.MediaParts != null &&
field.MediaParts.Count >= index ?
field.MediaParts[index] : null;
}
}
@helper CreateImgFromMediaPart(dynamic mediaPart)
{
var imgSrc = mediaPart != null ? mediaPart.MediaUrl : string.Empty;
var imgAlt = mediaPart != null ? mediaPart.AlternateText : string.Empty;
<img src="@Display.ResizeMediaUrl(Width: 116, Height: 65, Mode: "crop", Alignment: "middlecenter", Path: imgSrc)">
}
@{
var items = (Model.ContentItems as IEnumerable<ContentItem>);
var cssClass = items.First().TypeDefinition.Name.HtmlClassify();
<div class="@cssClass">
<div class="row">
@foreach (ContentItem item in items)
{
var itemDisplayUrl = Url.ItemDisplayUrl(item);
// get the mainPart, so we can access the item's fields
dynamic mainPart = GetMainPartFromContentItem(item);
var mediaPart = GetMediaPartFromMediaLibraryPickerField(mainPart.Image, 0);
var shortTitle = mainPart.ShortTitle.Value;
var summary = mainPart.Summary.Value;
// keep in mind that our theme has a grid with 36 columns
<div class="col-md-6">
@CreateImgFromMediaPart(mediaPart)
<h6>@shortTitle</h6>
<p>@summary</p>
<a href="@itemDisplayUrl">View</a>
</div>
}
</div>
</div>
} | @using System.Dynamic;
@using System.Linq;
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions;
@functions
{
dynamic GetMainPartFromContentItem(ContentItem item)
{
// get the ContentPart that has the same name as the item's ContentType
// so that we can access the item fields.
var contentType = item.TypeDefinition.Name;
var parts = item.Parts as List<ContentPart>;
return parts.First(p => p.PartDefinition.Name.Equals(contentType)); return mainPart;
}
dynamic GetMediaPartFromMediaLibraryPickerField(dynamic field, int index = 0)
{
return field != null &&
field.MediaParts != null &&
field.MediaParts.Count >= index ?
field.MediaParts[index] : null;
}
}
@helper CreateImgFromMediaPart(dynamic mediaPart)
{
var imgSrc = mediaPart != null ? mediaPart.MediaUrl : string.Empty;
var imgAlt = mediaPart != null ? mediaPart.AlternateText : string.Empty;
<img src="@Display.ResizeMediaUrl(Width: 116, Height: 65, Mode: "crop", Alignment: "middlecenter", Path: imgSrc)">
}
@{
var items = (Model.ContentItems as IEnumerable<ContentItem>);
var cssClass = items.First().TypeDefinition.Name.HtmlClassify();
<div class="@cssClass">
<div class="row">
@foreach (ContentItem item in items)
{
var itemDisplayUrl = Url.ItemDisplayUrl(item);
// get the mainPart, so we can access the item's fields
dynamic mainPart = GetMainPartFromContentItem(item);
var mediaPart = GetMediaPartFromMediaLibraryPickerField(mainPart.Image, 0);
var shortTitle = mainPart.ShortTitle.Value;
var summary = mainPart.Summary.Value;
// keep in mind that our theme has a grid with 36 columns
<div class="col-md-6">
@CreateImgFromMediaPart(mediaPart)
<h6>@shortTitle</h6>
<p>@summary</p>
<a href="@itemDisplayUrl">View</a>
</div>
}
</div>
</div>
} | bsd-3-clause | C# |
1e71681916b3fe6473da6f3fda1e2fb35f9dc7fd | Fix osu!catch catcher not scaling down correctly | NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,johnneijzen/osu,ppy/osu,peppy/osu,UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,peppy/osu-new,2yangk23/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu | osu.Game.Rulesets.Catch/UI/CatcherSprite.cs | osu.Game.Rulesets.Catch/UI/CatcherSprite.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.Framework.Graphics.Containers;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherSprite : CompositeDrawable
{
public CatcherSprite()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(-0.02f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new SkinnableSprite("Gameplay/catch/fruit-catcher-idle", confineMode: ConfineMode.ScaleDownToFit)
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
};
}
}
}
| // 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.Framework.Graphics.Containers;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherSprite : CompositeDrawable
{
public CatcherSprite()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(-0.02f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new SkinnableSprite("Gameplay/catch/fruit-catcher-idle")
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
};
}
}
}
| mit | C# |
0e3b001b133e310064065be3c98f3f13f320321d | Make maps with storyboards decode correctly with OsuJsonDecoder | naoey/osu,NeoAdonis/osu,EVAST9919/osu,UselessToucan/osu,ZLima12/osu,Nabile-Rahmani/osu,naoey/osu,DrabWeb/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,peppy/osu-new,peppy/osu,DrabWeb/osu,UselessToucan/osu,2yangk23/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,naoey/osu,ZLima12/osu,Frontear/osuKyzer,EVAST9919/osu,peppy/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,DrabWeb/osu | osu.Game/Beatmaps/Formats/OsuJsonDecoder.cs | osu.Game/Beatmaps/Formats/OsuJsonDecoder.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.IO;
using osu.Game.IO.Serialization;
namespace osu.Game.Beatmaps.Formats
{
public class OsuJsonDecoder : BeatmapDecoder
{
public static void Register()
{
AddDecoder<OsuJsonDecoder>("{");
}
protected override void ParseFile(StreamReader stream, Beatmap beatmap)
{
stream.BaseStream.Position = 0;
stream.DiscardBufferedData();
try
{
string fullText = stream.ReadToEnd();
fullText.DeserializeInto(beatmap);
}
catch
{
// Temporary because storyboards are deserialized into beatmaps at the moment
// This try-catch shouldn't exist in the future
}
foreach (var hitObject in beatmap.HitObjects)
hitObject.ApplyDefaults(beatmap.ControlPointInfo, beatmap.BeatmapInfo.BaseDifficulty);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.IO;
using osu.Game.IO.Serialization;
namespace osu.Game.Beatmaps.Formats
{
public class OsuJsonDecoder : BeatmapDecoder
{
public static void Register()
{
AddDecoder<OsuJsonDecoder>("{");
}
protected override void ParseFile(StreamReader stream, Beatmap beatmap)
{
stream.BaseStream.Position = 0;
stream.DiscardBufferedData();
string fullText = stream.ReadToEnd();
fullText.DeserializeInto(beatmap);
foreach (var hitObject in beatmap.HitObjects)
hitObject.ApplyDefaults(beatmap.ControlPointInfo, beatmap.BeatmapInfo.BaseDifficulty);
}
}
}
| mit | C# |
3c11055ee063395b3fa647e213235dfa030fd695 | Add "x-delayed-message" as valid exchange type | EasyNetQ/EasyNetQ.Management.Client,EasyNetQ/EasyNetQ.Management.Client,chinaboard/EasyNetQ.Management.Client,micdenny/EasyNetQ.Management.Client,alexwiese/EasyNetQ.Management.Client,Pliner/EasyNetQ.Management.Client,micdenny/EasyNetQ.Management.Client,Pliner/EasyNetQ.Management.Client | Source/EasyNetQ.Management.Client/Model/ExchangeInfo.cs | Source/EasyNetQ.Management.Client/Model/ExchangeInfo.cs | using System;
using System.Collections.Generic;
namespace EasyNetQ.Management.Client.Model
{
public class ExchangeInfo
{
public string Type { get; private set; }
public bool AutoDelete { get; private set; }
public bool Durable { get; private set; }
public bool Internal { get; private set; }
public Arguments Arguments { get; private set; }
private readonly string name;
private readonly ISet<string> exchangeTypes = new HashSet<string>
{
"direct", "topic", "fanout", "headers", "x-delayed-message"
};
public ExchangeInfo(string name, string type) : this(name, type, false, true, false, new Arguments())
{
}
public ExchangeInfo(string name, string type, bool autoDelete, bool durable, bool @internal, Arguments arguments)
{
if(string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
if (!exchangeTypes.Contains(type))
{
throw new EasyNetQManagementException("Unknown exchange type '{0}', expected one of {1}",
type,
string.Join(", ", exchangeTypes));
}
this.name = name;
Type = type;
AutoDelete = autoDelete;
Durable = durable;
Internal = @internal;
Arguments = arguments;
}
public string GetName()
{
return name;
}
}
}
| using System;
using System.Collections.Generic;
namespace EasyNetQ.Management.Client.Model
{
public class ExchangeInfo
{
public string Type { get; private set; }
public bool AutoDelete { get; private set; }
public bool Durable { get; private set; }
public bool Internal { get; private set; }
public Arguments Arguments { get; private set; }
private readonly string name;
private readonly ISet<string> exchangeTypes = new HashSet<string>
{
"direct", "topic", "fanout", "headers"
};
public ExchangeInfo(string name, string type) : this(name, type, false, true, false, new Arguments())
{
}
public ExchangeInfo(string name, string type, bool autoDelete, bool durable, bool @internal, Arguments arguments)
{
if(string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if(type == null)
{
throw new ArgumentNullException("type");
}
if (!exchangeTypes.Contains(type))
{
throw new EasyNetQManagementException("Unknown exchange type '{0}', expected one of {1}",
type,
string.Join(", ", exchangeTypes));
}
this.name = name;
Type = type;
AutoDelete = autoDelete;
Durable = durable;
Internal = @internal;
Arguments = arguments;
}
public string GetName()
{
return name;
}
}
} | mit | C# |
997d8ee315f8d0203392a71df0b7ae98d92d97a4 | Update PersonMap.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Test/AdventureWorksFunctionalModel/Mapping/PersonMap.cs | Test/AdventureWorksFunctionalModel/Mapping/PersonMap.cs | using System.Data.Entity.ModelConfiguration;
using AW.Types;
namespace AW.Mapping
{
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
// Primary Key
HasKey(t => t.BusinessEntityID);
Property(t => t.Title)
.HasMaxLength(8);
Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(50);
Property(t => t.MiddleName)
.HasMaxLength(50);
Property(t => t.LastName)
.IsRequired()
.HasMaxLength(50);
Property(t => t.Suffix)
.HasMaxLength(10);
// Table & Column Mappings
ToTable("Person", "Person");
Property(t => t.BusinessEntityID).HasColumnName("BusinessEntityID");
Property(t => t.PersonType).HasColumnName("PersonType");
Property(t => t.NameStyle).HasColumnName("NameStyle");
Property(t => t.Title).HasColumnName("Title");
Property(t => t.FirstName).HasColumnName("FirstName");
Property(t => t.MiddleName).HasColumnName("MiddleName");
Property(t => t.LastName).HasColumnName("LastName");
Property(t => t.Suffix).HasColumnName("Suffix");
Property(t => t.EmailPromotion).HasColumnName("EmailPromotion");
Property(t => t.AdditionalContactInfo).HasColumnName("AdditionalContactInfo");
Property(t => t.rowguid).HasColumnName("rowguid");
Property(t => t.ModifiedDate).HasColumnName("ModifiedDate");
HasOptional(t => t.Employee).WithRequired(t => t.PersonDetails);
HasOptional(t => t.Password);
}
}
}
| using System.Data.Entity.ModelConfiguration;
using AW.Types;
namespace AW.Mapping
{
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
// Primary Key
HasKey(t => t.BusinessEntityID);
Property(t => t.Title)
.HasMaxLength(8);
Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(50);
Property(t => t.MiddleName)
.HasMaxLength(50);
Property(t => t.LastName)
.IsRequired()
.HasMaxLength(50);
Property(t => t.Suffix)
.HasMaxLength(10);
// Table & Column Mappings
ToTable("Person", "Person");
Property(t => t.BusinessEntityID).HasColumnName("BusinessEntityID");
Property(t => t.PersonType).HasColumnName("PersonType");
Property(t => t.NameStyle).HasColumnName("NameStyle");
Property(t => t.Title).HasColumnName("Title");
Property(t => t.FirstName).HasColumnName("FirstName");
Property(t => t.MiddleName).HasColumnName("MiddleName");
Property(t => t.LastName).HasColumnName("LastName");
Property(t => t.Suffix).HasColumnName("Suffix");
Property(t => t.EmailPromotion).HasColumnName("EmailPromotion");
Property(t => t.AdditionalContactInfo).HasColumnName("AdditionalContactInfo");
Property(t => t.rowguid).HasColumnName("rowguid");
Property(t => t.ModifiedDate).HasColumnName("ModifiedDate");
HasOptional(t => t.Employee).WithRequired(t => t.PersonDetails);
}
}
}
| apache-2.0 | C# |
9b5674b2273ff9cbca3ac035db92da6847a83808 | Bump version | o11c/WebMConverter,nixxquality/WebMConverter,Yuisbean/WebMConverter | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// 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("2.7.3")]
| 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// 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("2.7.2")]
| mit | C# |
48e14ec4d0e08d3d835c44040d3f88fc4358c770 | Fix build | serilog/serilog-sinks-azuretablestorage | src/Serilog.Sinks.AzureTableStorage/Sinks/AzureTableStorageWithProperties/AzurePropertyFormatter.cs | src/Serilog.Sinks.AzureTableStorage/Sinks/AzureTableStorageWithProperties/AzurePropertyFormatter.cs | // Copyright 2014 Serilog Contributors
//
// 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.WindowsAzure.Storage.Table;
using Serilog.Debugging;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serilog.Sinks.AzureTableStorage
{
/// <summary>
/// Converts <see cref="LogEventProperty"/> values into simple scalars,
/// dictionaries and lists so that they can be persisted in Azure Table Storage.
/// </summary>
public static class AzurePropertyFormatter
{
/// <summary>
/// Simplify the object so as to make handling the serialized
/// representation easier.
/// </summary>
/// <param name="value">The value to simplify (possibly null).</param>
/// <param name="format">A format string applied to the value, or null.</param>
/// <param name="formatProvider">A format provider to apply to the value, or null to use the default.</param>
/// <returns>An Azure Storage entity EntityProperty</returns>
public static EntityProperty ToEntityProperty(LogEventPropertyValue value, string format = null, IFormatProvider formatProvider = null)
{
var scalar = value as ScalarValue;
if (scalar != null)
return SimplifyScalar(scalar.Value);
var dict = value as DictionaryValue;
if (dict != null)
{
return new EntityProperty(dict.ToString(format, formatProvider));
}
var seq = value as SequenceValue;
if (seq != null)
{
return new EntityProperty(seq.ToString(format, formatProvider));
}
var str = value as StructureValue;
if (str != null)
{
return new EntityProperty(str.ToString(format, formatProvider));
}
return null;
}
private static EntityProperty SimplifyScalar(object value)
{
if (value == null) return new EntityProperty((byte[])null);
var valueType = value.GetType();
if (valueType == typeof(byte[])) return new EntityProperty((byte[])value);
if (valueType == typeof(bool)) return new EntityProperty((bool)value);
if (valueType == typeof(DateTimeOffset)) return new EntityProperty((DateTimeOffset)value);
if (valueType == typeof(DateTime)) return new EntityProperty((DateTime)value);
if (valueType == typeof(double)) return new EntityProperty((double)value);
if (valueType == typeof(Guid)) return new EntityProperty((Guid)value);
if (valueType == typeof(int)) return new EntityProperty((int)value);
if (valueType == typeof(long)) return new EntityProperty((long)value);
if (valueType == typeof(string)) return new EntityProperty((string)value);
return new EntityProperty(value.ToString());
}
}
}
| // Copyright 2014 Serilog Contributors
//
// 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.WindowsAzure.Storage.Table;
using Serilog.Debugging;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serilog.Sinks.AzureTableStorage
{
/// <summary>
/// Converts <see cref="LogEventProperty"/> values into simple scalars,
/// dictionaries and lists so that they can be persisted in Azure Table Storage.
/// </summary>
public static class AzurePropertyFormatter
{
/// <summary>
/// Simplify the object so as to make handling the serialized
/// representation easier.
/// </summary>
/// <param name="value">The value to simplify (possibly null).</param>
/// <param name="format">A format string applied to the value, or null.</param>
/// <param name="formatProvider">A format provider to apply to the value, or null to use the default.</param>
/// <returns>An Azure Storage entity EntityProperty</returns>
public static EntityProperty ToEntityProperty(LogEventPropertyValue value, string format = null, IFormatProvider formatProvider = null)
{
var scalar = value as ScalarValue;
if (scalar != null)
return SimplifyScalar(scalar.Value);
var dict = value as DictionaryValue;
if (dict != null)
{
return new EntityProperty(dict.ToString(format, formatProvider));
}
var seq = value as SequenceValue;
if (seq != null)
{
return new EntityProperty(seq.ToString(format, formatProvider));
}
var str = value as StructureValue;
if (str != null)
{
return new EntityProperty(str.ToString(format, formatProvider));
}
return null;
}
private static EntityProperty SimplifyScalar(object value)
{
if (value == null) return new EntityProperty(null);
var valueType = value.GetType();
if (valueType == typeof(byte[])) return new EntityProperty((byte[])value);
if (valueType == typeof(bool)) return new EntityProperty((bool)value);
if (valueType == typeof(DateTimeOffset)) return new EntityProperty((DateTimeOffset)value);
if (valueType == typeof(DateTime)) return new EntityProperty((DateTime)value);
if (valueType == typeof(double)) return new EntityProperty((double)value);
if (valueType == typeof(Guid)) return new EntityProperty((Guid)value);
if (valueType == typeof(int)) return new EntityProperty((int)value);
if (valueType == typeof(long)) return new EntityProperty((long)value);
if (valueType == typeof(string)) return new EntityProperty((string)value);
return new EntityProperty(value.ToString());
}
}
}
| apache-2.0 | C# |
3dc875915c799a3c366090bc17e74e9a49eaf4ec | fix typo | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Gui.Tabs;
using WalletWasabi.Gui.Tabs.WalletManager;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
public Global Global { get; }
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var walletManagerCommand = ReactiveCommand.Create(OnWalletManager);
var settingsCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel(Global)));
var transactionBroadcasterCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel(Global)));
#if DEBUG
var devToolsCommand = ReactiveCommand.Create(() =>
{
DevToolsExtensions.OpenDevTools((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow);
});
#endif
Observable
.Merge(walletManagerCommand.ThrownExceptions)
.Merge(settingsCommand.ThrownExceptions)
#if DEBUG
.Merge(devToolsCommand.ThrownExceptions)
#endif
.Subscribe(OnException);
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
walletManagerCommand);
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
settingsCommand);
TransactionBroadcasterCommand = new CommandDefinition(
"Broadcast Transaction",
commandIconService.GetCompletionKindImage("BroadcastTransaction"),
transationBroadcasterCommand);
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
devToolsCommand);
#endif
}
private void OnWalletManager()
{
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
private void OnException(Exception ex)
{
Logger.LogError(ex);
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
[ExportCommandDefinition("Tools.BroadcastTransaction")]
public CommandDefinition TransactionBroadcasterCommand { get; }
#if DEBUG
[ExportCommandDefinition("Tools.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Gui.Tabs;
using WalletWasabi.Gui.Tabs.WalletManager;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
public Global Global { get; }
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var walletManagerCommand = ReactiveCommand.Create(OnWalletManager);
var settingsCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel(Global)));
var transationBroadcasterCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel(Global)));
#if DEBUG
var devToolsCommand = ReactiveCommand.Create(() =>
{
DevToolsExtensions.OpenDevTools((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow);
});
#endif
Observable
.Merge(walletManagerCommand.ThrownExceptions)
.Merge(settingsCommand.ThrownExceptions)
#if DEBUG
.Merge(devToolsCommand.ThrownExceptions)
#endif
.Subscribe(OnException);
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
walletManagerCommand);
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
settingsCommand);
TransactionBroadcasterCommand = new CommandDefinition(
"Broadcast Transaction",
commandIconService.GetCompletionKindImage("BroadcastTransaction"),
transationBroadcasterCommand);
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
devToolsCommand);
#endif
}
private void OnWalletManager()
{
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
private void OnException(Exception ex)
{
Logger.LogError(ex);
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
[ExportCommandDefinition("Tools.BroadcastTransaction")]
public CommandDefinition TransactionBroadcasterCommand { get; }
#if DEBUG
[ExportCommandDefinition("Tools.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| mit | C# |
4b84564f474e1369817815a7bfa8dcb90d99f0c4 | Switch casing comparison mode to ordinal | peppy/osu-new,UselessToucan/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu | osu.Game/IO/Archives/ZipArchiveReader.cs | osu.Game/IO/Archives/ZipArchiveReader.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 System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Archives.Zip;
using SharpCompress.Common;
namespace osu.Game.IO.Archives
{
public sealed class ZipArchiveReader : ArchiveReader
{
/// <summary>
/// List of substrings that indicate a file should be ignored during the import process
/// (usually due to representing no useful data and being autogenerated by the OS).
/// </summary>
private static readonly string[] filename_ignore_list =
{
// Mac-specific
"__MACOSX",
".DS_Store",
// Windows-specific
"Thumbs.db"
};
private readonly Stream archiveStream;
private readonly ZipArchive archive;
public ZipArchiveReader(Stream archiveStream, string name = null)
: base(name)
{
this.archiveStream = archiveStream;
archive = ZipArchive.Open(archiveStream);
}
public override Stream GetStream(string name)
{
ZipArchiveEntry entry = archive.Entries.SingleOrDefault(e => e.Key == name);
if (entry == null)
throw new FileNotFoundException();
// allow seeking
MemoryStream copy = new MemoryStream();
using (Stream s = entry.OpenEntryStream())
s.CopyTo(copy);
copy.Position = 0;
return copy;
}
public override void Dispose()
{
archive.Dispose();
archiveStream.Dispose();
}
private static bool canBeIgnored(IEntry entry) => filename_ignore_list.Any(ignoredName => entry.Key.IndexOf(ignoredName, StringComparison.OrdinalIgnoreCase) >= 0);
public override IEnumerable<string> Filenames => archive.Entries.Where(e => !canBeIgnored(e)).Select(e => e.Key).ToArray();
public override Stream GetUnderlyingStream() => archiveStream;
}
}
| // 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 System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Archives.Zip;
using SharpCompress.Common;
namespace osu.Game.IO.Archives
{
public sealed class ZipArchiveReader : ArchiveReader
{
/// <summary>
/// List of substrings that indicate a file should be ignored during the import process
/// (usually due to representing no useful data and being autogenerated by the OS).
/// </summary>
private static readonly string[] filename_ignore_list =
{
// Mac-specific
"__MACOSX",
".DS_Store",
// Windows-specific
"Thumbs.db"
};
private readonly Stream archiveStream;
private readonly ZipArchive archive;
public ZipArchiveReader(Stream archiveStream, string name = null)
: base(name)
{
this.archiveStream = archiveStream;
archive = ZipArchive.Open(archiveStream);
}
public override Stream GetStream(string name)
{
ZipArchiveEntry entry = archive.Entries.SingleOrDefault(e => e.Key == name);
if (entry == null)
throw new FileNotFoundException();
// allow seeking
MemoryStream copy = new MemoryStream();
using (Stream s = entry.OpenEntryStream())
s.CopyTo(copy);
copy.Position = 0;
return copy;
}
public override void Dispose()
{
archive.Dispose();
archiveStream.Dispose();
}
private static bool canBeIgnored(IEntry entry) => filename_ignore_list.Any(ignoredName => entry.Key.IndexOf(ignoredName, StringComparison.InvariantCultureIgnoreCase) >= 0);
public override IEnumerable<string> Filenames => archive.Entries.Where(e => !canBeIgnored(e)).Select(e => e.Key).ToArray();
public override Stream GetUnderlyingStream() => archiveStream;
}
}
| mit | C# |
464650a94a43a4c7eade3781c03afdb1fff1e243 | Reorganize DiscordOAuthValidator | tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools | src/Tgstation.Server.Host/Security/OAuth/DiscordOAuthValidator.cs | src/Tgstation.Server.Host/Security/OAuth/DiscordOAuthValidator.cs | using System;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Host.Configuration;
using Tgstation.Server.Host.System;
namespace Tgstation.Server.Host.Security.OAuth
{
/// <summary>
/// OAuth validator for Discord.
/// </summary>
sealed class DiscordOAuthValidator : GenericOAuthValidator
{
/// <inheritdoc />
public override OAuthProvider Provider => OAuthProvider.Discord;
/// <inheritdoc />
protected override Uri TokenUrl => new Uri("https://discord.com/api/oauth2/token");
/// <inheritdoc />
protected override Uri UserInformationUrl => new Uri("https://discord.com/api/users/@me");
/// <summary>
/// Initializes a new instance of the <see cref="DiscordOAuthValidator"/> class.
/// </summary>
/// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/> for the <see cref="GenericOAuthValidator"/>.</param>
/// <param name="assemblyInformationProvider">The <see cref="IAssemblyInformationProvider"/> for the <see cref="GenericOAuthValidator"/>.</param>
/// <param name="logger">The <see cref="ILogger"/> for the <see cref="GenericOAuthValidator"/>.</param>
/// <param name="oAuthConfiguration">The <see cref="OAuthConfiguration"/> for the <see cref="GenericOAuthValidator"/>.</param>
public DiscordOAuthValidator(
IHttpClientFactory httpClientFactory,
IAssemblyInformationProvider assemblyInformationProvider,
ILogger<DiscordOAuthValidator> logger,
OAuthConfiguration oAuthConfiguration)
: base(httpClientFactory, assemblyInformationProvider, logger, oAuthConfiguration)
{
}
/// <inheritdoc />
protected override OAuthTokenRequest CreateTokenRequest(string code) => new OAuthTokenRequest(OAuthConfiguration, code, "identify");
/// <inheritdoc />
protected override string DecodeTokenPayload(dynamic responseJson) => responseJson.access_token;
/// <inheritdoc />
protected override string DecodeUserInformationPayload(dynamic responseJson) => responseJson.id;
}
}
| using System;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Host.Configuration;
using Tgstation.Server.Host.System;
namespace Tgstation.Server.Host.Security.OAuth
{
/// <summary>
/// OAuth validator for Discord.
/// </summary>
sealed class DiscordOAuthValidator : GenericOAuthValidator
{
/// <summary>
/// Initializes a new instance of the <see cref="DiscordOAuthValidator"/> class.
/// </summary>
/// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/> for the <see cref="GenericOAuthValidator"/>.</param>
/// <param name="assemblyInformationProvider">The <see cref="IAssemblyInformationProvider"/> for the <see cref="GenericOAuthValidator"/>.</param>
/// <param name="logger">The <see cref="ILogger"/> for the <see cref="GenericOAuthValidator"/>.</param>
/// <param name="oAuthConfiguration">The <see cref="OAuthConfiguration"/> for the <see cref="GenericOAuthValidator"/>.</param>
public DiscordOAuthValidator(
IHttpClientFactory httpClientFactory,
IAssemblyInformationProvider assemblyInformationProvider,
ILogger<DiscordOAuthValidator> logger,
OAuthConfiguration oAuthConfiguration)
: base(httpClientFactory, assemblyInformationProvider, logger, oAuthConfiguration)
{
}
/// <inheritdoc />
public override OAuthProvider Provider => OAuthProvider.Discord;
/// <inheritdoc />
protected override Uri TokenUrl => new Uri("https://discord.com/api/oauth2/token");
/// <inheritdoc />
protected override Uri UserInformationUrl => new Uri("https://discord.com/api/users/@me");
/// <inheritdoc />
protected override OAuthTokenRequest CreateTokenRequest(string code) => new OAuthTokenRequest(OAuthConfiguration, code, "identify");
/// <inheritdoc />
protected override string DecodeTokenPayload(dynamic responseJson) => responseJson.access_token;
/// <inheritdoc />
protected override string DecodeUserInformationPayload(dynamic responseJson) => responseJson.id;
}
}
| agpl-3.0 | C# |
7314dd3a5d7dbd79d77d6e06f24160365e0332e5 | Add an area for errors | github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity | src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishWindow.cs | src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishWindow.cs | using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private int selectedOrg = 0;
private bool togglePrivate = false;
// TODO: Replace me since this is just to test rendering errors
private bool error = true;
private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);
GUILayout.Space(5);
if (error)
GUILayout.Label("There was an error", Styles.ErrorLabel);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Create"))
{
Debug.Log("CREATING A REPO HAPPENS HERE!");
this.Close();
}
}
GUILayout.EndHorizontal();
}
}
}
| using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private int selectedOrg = 0;
private bool togglePrivate = false;
private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Create"))
{
Debug.Log("CREATING A REPO HAPPENS HERE!");
this.Close();
}
}
GUILayout.EndHorizontal();
}
}
}
| mit | C# |
a684be92bb82d369a7fc91b5b335993fbee4efb8 | Fix #3325 Add support for zero_terms_query to match_phrase query (#3363) | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/QueryDsl/FullText/MatchPhrasePrefix/MatchPhrasePrefixQuery.cs | src/Nest/QueryDsl/FullText/MatchPhrasePrefix/MatchPhrasePrefixQuery.cs | using Newtonsoft.Json;
using System;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(FieldNameQueryJsonConverter<MatchPhrasePrefixQuery>))]
public interface IMatchPhrasePrefixQuery : IFieldNameQuery
{
[JsonProperty("query")]
string Query { get; set; }
[JsonProperty("analyzer")]
string Analyzer { get; set; }
[JsonProperty("max_expansions")]
int? MaxExpansions { get; set; }
[JsonProperty("slop")]
int? Slop { get; set; }
/// <summary>
/// If the analyzer used removes all tokens in a query like a stop filter does, the default behavior is
/// to match no documents at all. In order to change that, <see cref="ZeroTermsQuery"/> can be used,
/// which accepts <see cref="ZeroTermsQuery.None"/> (default) and <see cref="ZeroTermsQuery.All"/>
/// which corresponds to a match_all query.
/// </summary>
[JsonProperty("zero_terms_query")]
ZeroTermsQuery? ZeroTermsQuery { get; set; }
}
public class MatchPhrasePrefixQuery : FieldNameQueryBase, IMatchPhrasePrefixQuery
{
protected override bool Conditionless => IsConditionless(this);
public string Analyzer { get; set; }
public int? MaxExpansions { get; set; }
public string Query { get; set; }
public int? Slop { get; set; }
/// <inheritdoc />
public ZeroTermsQuery? ZeroTermsQuery { get; set; }
internal override void InternalWrapInContainer(IQueryContainer c) => c.MatchPhrasePrefix = this;
internal static bool IsConditionless(IMatchPhrasePrefixQuery q) => q.Field.IsConditionless() || q.Query.IsNullOrEmpty();
}
public class MatchPhrasePrefixQueryDescriptor<T>
: FieldNameQueryDescriptorBase<MatchPhrasePrefixQueryDescriptor<T>, IMatchPhrasePrefixQuery, T>, IMatchPhrasePrefixQuery
where T : class
{
protected override bool Conditionless => MatchPhrasePrefixQuery.IsConditionless(this);
string IMatchPhrasePrefixQuery.Query { get; set; }
string IMatchPhrasePrefixQuery.Analyzer { get; set; }
int? IMatchPhrasePrefixQuery.MaxExpansions { get; set; }
int? IMatchPhrasePrefixQuery.Slop { get; set; }
ZeroTermsQuery? IMatchPhrasePrefixQuery.ZeroTermsQuery { get; set; }
public MatchPhrasePrefixQueryDescriptor<T> Query(string query) => Assign(a => a.Query = query);
public MatchPhrasePrefixQueryDescriptor<T> Analyzer(string analyzer) => Assign(a => a.Analyzer = analyzer);
public MatchPhrasePrefixQueryDescriptor<T> MaxExpansions(int? maxExpansions) => Assign(a => a.MaxExpansions = maxExpansions);
public MatchPhrasePrefixQueryDescriptor<T> Slop(int? slop) => Assign(a => a.Slop = slop);
/// <inheritdoc cref="IMatchQuery.ZeroTermsQuery" />
public MatchPhrasePrefixQueryDescriptor<T> ZeroTermsQuery(ZeroTermsQuery? zeroTermsQuery) => Assign(a => a.ZeroTermsQuery = zeroTermsQuery);
}
}
| using Newtonsoft.Json;
using System;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(FieldNameQueryJsonConverter<MatchPhrasePrefixQuery>))]
public interface IMatchPhrasePrefixQuery : IFieldNameQuery
{
[JsonProperty("query")]
string Query { get; set; }
[JsonProperty("analyzer")]
string Analyzer { get; set; }
[JsonProperty("max_expansions")]
int? MaxExpansions { get; set; }
[JsonProperty("slop")]
int? Slop { get; set; }
}
public class MatchPhrasePrefixQuery : FieldNameQueryBase, IMatchPhrasePrefixQuery
{
protected override bool Conditionless => IsConditionless(this);
public string Analyzer { get; set; }
public int? MaxExpansions { get; set; }
public string Query { get; set; }
public int? Slop { get; set; }
internal override void InternalWrapInContainer(IQueryContainer c) => c.MatchPhrasePrefix = this;
internal static bool IsConditionless(IMatchPhrasePrefixQuery q) => q.Field.IsConditionless() || q.Query.IsNullOrEmpty();
}
public class MatchPhrasePrefixQueryDescriptor<T>
: FieldNameQueryDescriptorBase<MatchPhrasePrefixQueryDescriptor<T>, IMatchPhrasePrefixQuery, T>, IMatchPhrasePrefixQuery
where T : class
{
protected override bool Conditionless => MatchPhrasePrefixQuery.IsConditionless(this);
string IMatchPhrasePrefixQuery.Query { get; set; }
string IMatchPhrasePrefixQuery.Analyzer { get; set; }
int? IMatchPhrasePrefixQuery.MaxExpansions { get; set; }
int? IMatchPhrasePrefixQuery.Slop { get; set; }
public MatchPhrasePrefixQueryDescriptor<T> Query(string query) => Assign(a => a.Query = query);
public MatchPhrasePrefixQueryDescriptor<T> Analyzer(string analyzer) => Assign(a => a.Analyzer = analyzer);
public MatchPhrasePrefixQueryDescriptor<T> MaxExpansions(int? maxExpansions) => Assign(a => a.MaxExpansions = maxExpansions);
public MatchPhrasePrefixQueryDescriptor<T> Slop(int? slop) => Assign(a => a.Slop = slop);
}
}
| apache-2.0 | C# |
571d3edf6c416ae13bf91f5210ca67793ad4b8e4 | Bump up new version for assemblyinfor file | shahabhijeet/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,stankovski/azure-sdk-for-net,pilor/azure-sdk-for-net,stankovski/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jamestao/azure-sdk-for-net,hyonholee/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,pilor/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,pilor/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jamestao/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jamestao/azure-sdk-for-net,markcowl/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jamestao/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net | src/SDKs/Consumption/Management.Consumption/Properties/AssemblyInfo.cs | src/SDKs/Consumption/Management.Consumption/Properties/AssemblyInfo.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Consumption Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Consumption.")]
[assembly: AssemblyVersion("3.0.1.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")] | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Consumption Management Library")]
[assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Consumption.")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")] | mit | C# |
518b902214aa4f0fa2dad2d246f9888c7cdbf53a | Improve assertion message. | yfakariya/msgpack-rpc-cli,yonglehou/msgpack-rpc-cli | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Protocols/_SetUpFixture.cs | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Protocols/_SetUpFixture.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using NUnit.Framework;
namespace MsgPack.Rpc.Server.Protocols
{
[CLSCompliant( false )]
[SetUpFixture]
public sealed class _SetUpFixture
{
[SetUp]
public void SetupCurrentNamespaceTests()
{
Contract.ContractFailed +=
( sender, e ) =>
{
Console.WriteLine( "{0} {1}", e.Message, e.Condition );
Console.WriteLine( new StackTrace( 0, true ) );
e.SetUnwind();
};
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Diagnostics.Contracts;
using NUnit.Framework;
namespace MsgPack.Rpc.Server.Protocols
{
[CLSCompliant( false )]
[SetUpFixture]
public sealed class _SetUpFixture
{
[SetUp]
public void SetupCurrentNamespaceTests()
{
Contract.ContractFailed += ( sender, e ) => e.SetUnwind();
}
}
}
| apache-2.0 | C# |
af8232392d5355df67d4f2a19ea3d11658412aa3 | Adjust delete alias test to specify the index (#5737) (#5738) | elastic/elasticsearch-net,elastic/elasticsearch-net | tests/Tests/Indices/AliasManagement/DeleteAlias/AliasDeleteApiTests.cs | tests/Tests/Indices/AliasManagement/DeleteAlias/AliasDeleteApiTests.cs | // Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using Elastic.Transport;
using Nest;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Framework.EndpointTests;
using Tests.Framework.EndpointTests.TestState;
namespace Tests.Indices.AliasManagement.DeleteAlias
{
public class DeleteAliasApiTests
: ApiIntegrationTestBase<WritableCluster, DeleteAliasResponse, IDeleteAliasRequest, DeleteAliasDescriptor, DeleteAliasRequest>
{
public DeleteAliasApiTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override Func<DeleteAliasDescriptor, IDeleteAliasRequest> Fluent => null;
protected override HttpMethod HttpMethod => HttpMethod.DELETE;
protected override DeleteAliasRequest Initializer => new(CallIsolatedValue, Names);
protected override bool SupportsDeserialization => false;
protected override string UrlPath => $"/{CallIsolatedValue}/_alias/{CallIsolatedValue + "-alias"}";
private Names Names => Infer.Names(CallIsolatedValue + "-alias");
protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values)
{
foreach (var index in values.Values)
client.Indices.Create(index, c => c.Aliases(aa => aa.Alias(index + "-alias")));
}
protected override LazyResponses ClientUsage() => Calls(
(client, f) => client.Indices.DeleteAlias(CallIsolatedValue, Names),
(client, f) => client.Indices.DeleteAliasAsync(CallIsolatedValue, Names),
(client, r) => client.Indices.DeleteAlias(r),
(client, r) => client.Indices.DeleteAliasAsync(r)
);
}
}
| // Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using Elastic.Transport;
using Nest;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Framework.EndpointTests;
using Tests.Framework.EndpointTests.TestState;
namespace Tests.Indices.AliasManagement.DeleteAlias
{
public class DeleteAliasApiTests
: ApiIntegrationTestBase<WritableCluster, DeleteAliasResponse, IDeleteAliasRequest, DeleteAliasDescriptor, DeleteAliasRequest>
{
public DeleteAliasApiTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override Func<DeleteAliasDescriptor, IDeleteAliasRequest> Fluent => null;
protected override HttpMethod HttpMethod => HttpMethod.DELETE;
protected override DeleteAliasRequest Initializer => new DeleteAliasRequest(Infer.AllIndices, Names);
protected override bool SupportsDeserialization => false;
protected override string UrlPath => $"/_all/_alias/{CallIsolatedValue + "-alias"}";
private Names Names => Infer.Names(CallIsolatedValue + "-alias");
protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values)
{
foreach (var index in values.Values)
client.Indices.Create(index, c => c
.Aliases(aa => aa.Alias(index + "-alias"))
);
}
protected override LazyResponses ClientUsage() => Calls(
(client, f) => client.Indices.DeleteAlias(Infer.AllIndices, Names),
(client, f) => client.Indices.DeleteAliasAsync(Infer.AllIndices, Names),
(client, r) => client.Indices.DeleteAlias(r),
(client, r) => client.Indices.DeleteAliasAsync(r)
);
}
}
| apache-2.0 | C# |
38bcf06f9967519146b8ace0de4d618cd9c95f55 | Disable JanusGraph integration tests. | ExRam/ExRam.Gremlinq | ExRam.Gremlinq.Providers.JanusGraph.Tests/JanusGraphIntegrationTests.cs | ExRam.Gremlinq.Providers.JanusGraph.Tests/JanusGraphIntegrationTests.cs | #if RELEASE && NETCOREAPP3_1
//Id generation on the JanusGraph docker image is too nondeterministic.
/*using ExRam.Gremlinq.Core;
using ExRam.Gremlinq.Core.Tests;
using ExRam.Gremlinq.Providers.WebSocket;
using Xunit.Abstractions;
using static ExRam.Gremlinq.Core.GremlinQuerySource;
namespace ExRam.Gremlinq.Providers.JanusGraph.Tests
{
public class JanusGraphIntegrationTests : QueryExecutionTest
{
public JanusGraphIntegrationTests(ITestOutputHelper testOutputHelper) : base(
g
.ConfigureEnvironment(env => env
.UseJanusGraph(builder => builder
.AtLocalhost())),
testOutputHelper)
{
}
}
}*/
#endif
| #if RELEASE && NETCOREAPP3_1
using ExRam.Gremlinq.Core;
using ExRam.Gremlinq.Core.Tests;
using ExRam.Gremlinq.Providers.WebSocket;
using Xunit.Abstractions;
using static ExRam.Gremlinq.Core.GremlinQuerySource;
namespace ExRam.Gremlinq.Providers.JanusGraph.Tests
{
public class JanusGraphIntegrationTests : QueryExecutionTest
{
public JanusGraphIntegrationTests(ITestOutputHelper testOutputHelper) : base(
g
.ConfigureEnvironment(env => env
.UseJanusGraph(builder => builder
.AtLocalhost())),
testOutputHelper)
{
}
}
}
#endif
| mit | C# |
af34a03ebc0a9fca829fa3d47ad8c575cb6fd8fc | Optimize ice cream | CaitSith2/KtaneTwitchPlays,samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/IceCreamConfirm.cs | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/IceCreamConfirm.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Newtonsoft.Json;
public class IceCreamConfirm : ComponentSolver
{
public IceCreamConfirm(BombCommander bombCommander, BombComponent bombComponent) :
base(bombCommander, bombComponent)
{
_component = bombComponent.GetComponent(_componentType);
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType());
KMModSettings modSettings = bombComponent.GetComponent<KMModSettings>();
try
{
settings = JsonConvert.DeserializeObject<Settings>(modSettings.Settings);
}
catch (Exception ex)
{
DebugHelper.LogException(ex, "Could not deserialize ice cream settings:");
TwitchPlaySettings.data.ShowHours = false;
TwitchPlaySettings.WriteDataToFile();
}
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
if (inputCommand.ToLowerInvariant().Equals("hours"))
{
yield return null;
if (!TwitchPlaySettings.data.ShowHours)
{
yield return $"sendtochat Sorry, hours are currently unavailable. Enjoy your ice cream!";
yield break;
}
string hours = settings.openingTimeEnabled ? "We are open every other hour today." : "We're open all day today!";
yield return $"sendtochat {hours}";
}
else
{
IEnumerator command = (IEnumerator)_ProcessCommandMethod.Invoke(_component, new object[] { inputCommand });
if (command == null) yield break;
while (command.MoveNext())
{
yield return command.Current;
}
}
}
static IceCreamConfirm()
{
_componentType = ReflectionHelper.FindType("IceCreamModule");
_ProcessCommandMethod = _componentType.GetMethod("ProcessTwitchCommand", BindingFlags.Public | BindingFlags.Instance);
}
class Settings
{
public bool openingTimeEnabled;
}
private static Type _componentType = null;
private static MethodInfo _ProcessCommandMethod = null;
private object _component = null;
private Settings settings;
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Newtonsoft.Json;
public class IceCreamConfirm : ComponentSolver
{
public IceCreamConfirm(BombCommander bombCommander, BombComponent bombComponent) :
base(bombCommander, bombComponent)
{
_component = bombComponent.GetComponent(_componentType);
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType());
KMModSettings modSettings = bombComponent.GetComponent<KMModSettings>();
try
{
settings = JsonConvert.DeserializeObject<Settings>(modSettings.Settings);
}
catch (Exception ex)
{
DebugHelper.LogException(ex, "Could not deserialize ice cream settings:");
TwitchPlaySettings.data.ShowHours = false;
TwitchPlaySettings.WriteDataToFile();
}
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
if (inputCommand.ToLowerInvariant().Equals("hours"))
{
string hours;
yield return null;
if (!TwitchPlaySettings.data.ShowHours)
{
yield return $"sendtochat Sorry, hours are currently unavailable. Enjoy your ice cream!";
yield break;
}
if (settings.openingTimeEnabled)
{
hours = "We are open every other hour today.";
}
else
{
hours = "We're open all day today!";
}
yield return $"sendtochat {hours}";
}
else
{
IEnumerator command = (IEnumerator)_ProcessCommandMethod.Invoke(_component, new object[] { inputCommand });
if (command == null) yield break;
while (command.MoveNext())
{
yield return command.Current;
}
}
}
static IceCreamConfirm()
{
_componentType = ReflectionHelper.FindType("IceCreamModule");
_ProcessCommandMethod = _componentType.GetMethod("ProcessTwitchCommand", BindingFlags.Public | BindingFlags.Instance);
}
class Settings
{
public bool openingTimeEnabled;
}
private static Type _componentType = null;
private static MethodInfo _ProcessCommandMethod = null;
private object _component = null;
private Settings settings;
} | mit | C# |
fa144579b55df33a5159cdb453a33e3249bb2b48 | Add RecordDeclaration to IsNamedTypeDeclarationBlock | mavasani/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,dotnet/roslyn-analyzers | src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs | src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MetaAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpDiagnosticAnalyzerApiUsageAnalyzer : DiagnosticAnalyzerApiUsageAnalyzer<TypeSyntax>
{
protected override bool IsNamedTypeDeclarationBlock(SyntaxNode syntax)
{
switch (syntax.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
return true;
default:
return false;
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MetaAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpDiagnosticAnalyzerApiUsageAnalyzer : DiagnosticAnalyzerApiUsageAnalyzer<TypeSyntax>
{
protected override bool IsNamedTypeDeclarationBlock(SyntaxNode syntax)
{
switch (syntax.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
return true;
default:
return false;
}
}
}
}
| mit | C# |
ca7773eb68f8b95ca9b830a7278932e588d00c76 | Make it exportable | davidebbo/PublishSettingsToPfx | PublishSettingsToPfx/Program.cs | PublishSettingsToPfx/Program.cs | using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;
namespace PublishSettingsToPfx
{
class Program
{
static void Main(string[] args)
{
string publishSettingsFile = args[0];
string pfxPassword = args[1];
string certString = GetCertStringFromPublishSettings(publishSettingsFile);
var cert = new X509Certificate2(
Convert.FromBase64String(certString), String.Empty, X509KeyStorageFlags.Exportable);
byte[] certData = cert.Export(X509ContentType.Pfx, pfxPassword);
File.WriteAllBytes(Path.ChangeExtension(publishSettingsFile, ".pfx"), certData);
}
static string GetCertStringFromPublishSettings(string path)
{
var document = XDocument.Load(path);
var profile = document.Descendants("PublishProfile").First();
return profile.Attribute("ManagementCertificate").Value;
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;
namespace PublishSettingsToPfx
{
class Program
{
static void Main(string[] args)
{
string publishSettingsFile = args[0];
string pfxPassword = args[1];
string certString = GetCertStringFromPublishSettings(publishSettingsFile);
var cert = new X509Certificate2(Convert.FromBase64String(certString));
byte[] certData = cert.Export(X509ContentType.Pfx, pfxPassword);
File.WriteAllBytes(Path.ChangeExtension(publishSettingsFile, ".pfx"), certData);
}
static string GetCertStringFromPublishSettings(string path)
{
var document = XDocument.Load(path);
var profile = document.Descendants("PublishProfile").First();
return profile.Attribute("ManagementCertificate").Value;
}
}
}
| apache-2.0 | C# |
18a843307269b4e631f744bd65cdfcf0e85c023e | Remove FormattableAttribute | yufeih/Nine.Storage,studio-nine/Nine.Storage | src/Portable/IEntity.cs | src/Portable/IEntity.cs | namespace Nine.Storage
{
using System;
/// <summary>
/// Represents a storage object that can be saved
/// </summary>
public interface IKeyed
{
/// <summary>
/// Gets or sets a key that identifies this object.
/// </summary>
string GetKey();
}
/// <summary>
/// Represents a storage object that can be saved
/// </summary>
public interface ITimestamped
{
/// <summary>
/// Gets or sets the last updated time of this storage object.
/// </summary>
DateTime Time { get; set; }
}
/// <summary>
/// Indicates that this object is owned by a particular user
/// </summary>
public interface IOwned
{
string UserId { get; set; }
}
}
| namespace Nine.Storage
{
using System;
/// <summary>
/// Marks an object as formattable to be used as a polymophic type with IFormatter.
/// </summary>
public class FormattableAttribute : Attribute
{
public uint TypeId { get; private set; }
public FormattableAttribute(uint typeId = 0)
{
this.TypeId = TypeId;
}
}
/// <summary>
/// Represents a storage object that can be saved
/// </summary>
[Formattable]
public interface IKeyed
{
/// <summary>
/// Gets or sets a key that identifies this object.
/// </summary>
string GetKey();
}
/// <summary>
/// Represents a storage object that can be saved
/// </summary>
public interface ITimestamped
{
/// <summary>
/// Gets or sets the last updated time of this storage object.
/// </summary>
DateTime Time { get; set; }
}
/// <summary>
/// Indicates that this object is owned by a particular user
/// </summary>
public interface IOwned
{
string UserId { get; set; }
}
}
| mit | C# |
b63d9c96784658537534a583fd2e965c53fc3fbe | Save card after giving point | pleonex/deblocus,pleonex/deblocus | Deblocus/Controllers/CardViewController.cs | Deblocus/Controllers/CardViewController.cs | //
// CardViewerController.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// 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 Deblocus.Views;
namespace Deblocus.Controllers
{
public class CardViewController
{
public CardViewController(MainWindow window, Deblocus.Entities.Card card)
{
Card = card;
View = new CardView(card);
View.ButtonReturnClicked += ButtonReturnClicked;
View.ButtonFailClicked += ButtonReturnClicked;
View.ButtonPassClicked += ButtonPassClicked;
Window = window;
Window.ChangeContent(View);
}
public Deblocus.Entities.Card Card { get; private set; }
public CardView View { get; private set; }
public MainWindow Window { get; private set; }
private void ButtonPassClicked(object sender, EventArgs e)
{
Card.GivePoint();
DatabaseManager.Instance.SaveOrUpdate(Card);
Window.RestoreContent();
}
private void ButtonReturnClicked(object sender, EventArgs e)
{
Window.RestoreContent();
}
}
}
| //
// CardViewerController.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// 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 Deblocus.Views;
namespace Deblocus.Controllers
{
public class CardViewController
{
public CardViewController(MainWindow window, Deblocus.Entities.Card card)
{
Card = card;
View = new CardView(card);
View.ButtonReturnClicked += ButtonReturnClicked;
View.ButtonFailClicked += ButtonReturnClicked;
View.ButtonPassClicked += ButtonPassClicked;
Window = window;
Window.ChangeContent(View);
}
public Deblocus.Entities.Card Card { get; private set; }
public CardView View { get; private set; }
public MainWindow Window { get; private set; }
private void ButtonPassClicked(object sender, EventArgs e)
{
Card.GivePoint();
Window.RestoreContent();
}
private void ButtonReturnClicked(object sender, EventArgs e)
{
Window.RestoreContent();
}
}
}
| agpl-3.0 | C# |
26c511b5397e3514c671fe9bb516c05963ab8d97 | disable ExtendedViewCellRenderer for now | flagbug/UnofficialGitterApp | Gitter.Android/ExtendedViewCellRenderer.cs | Gitter.Android/ExtendedViewCellRenderer.cs | using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Content;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;
//Disabled for now, because it doesn't really works, the ListView Divider is always shown
//Maybe it is working in a later Xamarin.Forms release...
//[assembly: ExportRenderer(typeof(ViewCell), typeof(Gitter.Android.Renderers.ExtendedViewCellRenderer))]
namespace Gitter.Android.Renderers
{
public class ExtendedViewCellRenderer : ViewCellRenderer
{
protected override global::Android.Views.View GetCellCore(Cell item, global::Android.Views.View convertView, ViewGroup parent, Context context)
{
//Get Android's ListView
var thisCellsListView = (global::Android.Widget.ListView)parent;
//The Xamarin.Forms.ListView
//var tableParent = (ListView)base.ParentView;
var colors = new int[] { Color.White.ToAndroid().ToArgb() , Color.Gray.ToAndroid().ToArgb(), Color.White.ToAndroid().ToArgb() };
thisCellsListView.Divider = new GradientDrawable(GradientDrawable.Orientation.LeftRight, colors);
thisCellsListView.DividerHeight = 1;
var cell = base.GetCellCore(item, convertView, parent, context);
return cell;
}
}
} | using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Content;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;
[assembly: ExportRenderer(typeof(ViewCell), typeof(Gitter.Android.Renderers.ExtendedViewCellRenderer))]
namespace Gitter.Android.Renderers
{
public class ExtendedViewCellRenderer : ViewCellRenderer
{
protected override global::Android.Views.View GetCellCore(Cell item, global::Android.Views.View convertView, ViewGroup parent, Context context)
{
//Get Android's ListView
var thisCellsListView = (global::Android.Widget.ListView)parent;
//The Xamarin.Forms.ListView
//var tableParent = (ListView)base.ParentView;
var colors = new int[] { Color.White.ToAndroid().ToArgb() , Color.Gray.ToAndroid().ToArgb(), Color.White.ToAndroid().ToArgb() };
thisCellsListView.Divider = new GradientDrawable(GradientDrawable.Orientation.LeftRight, colors);
thisCellsListView.DividerHeight = 1;
var cell = base.GetCellCore(item, convertView, parent, context);
return cell;
}
}
} | mit | C# |
efdbefa7c62f5ea2475844e505464a9406874ba1 | test stub | tonnyeremin/knet,tonnyeremin/knet | Knet/Knet.Test.Unit/ParseConfigFromFile.cs | Knet/Knet.Test.Unit/ParseConfigFromFile.cs | using System;
using Knet.Core.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Knet.Test.Unit
{
[TestClass]
public class ParseConfigFromFile
{
[TestMethod]
public void Parse()
{
//CConfigurationParser parser = new CConfigurationParser();
//var config = parser.ParseForCurrentUser();
//Assert.IsNotNull(config, "Reading config from current user directory");
}
}
}
| using System;
using Knet.Core.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Knet.Test.Unit
{
[TestClass]
public class ParseConfigFromFile
{
[TestMethod]
public void Parse()
{
CConfigurationParser parser = new CConfigurationParser();
var config = parser.ParseForCurrentUser();
Assert.IsNotNull(config, "Reading config from current user directory");
}
}
}
| mit | C# |
c507049e7339d508d1a4fef923230ad9c439bfca | Make sure time related test works fine on appveyor | bronumski/HealthNet,bronumski/HealthNet,bronumski/HealthNet | src/Tests/HealthNet.Tests/HealthCheckServiceFixtures/When_getting_the_status_and_a_system_check_overruns.cs | src/Tests/HealthNet.Tests/HealthCheckServiceFixtures/When_getting_the_status_and_a_system_check_overruns.cs | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using NUnit.Framework;
namespace HealthNet.HealthCheckServiceFixtures
{
class When_getting_the_status_and_a_system_check_overruns
{
private HealthResult result;
[OneTimeSetUp]
public void SetUp()
{
var hangingChecker = Substitute.For<ISystemChecker>();
hangingChecker.SystemName.Returns("Hanging checker");
hangingChecker.CheckSystem().Returns(x =>
{
Thread.Sleep(TimeSpan.FromSeconds(2));
return (SystemCheckResult) null;
});
var healthyChecker = Substitute.For<ISystemChecker>();
healthyChecker.CheckSystem()
.Returns(x => new SystemCheckResult {SystemName = "Healthy checker", Health = HealthState.Good});
var healthNetConfiguration = Substitute.For<IHealthNetConfiguration>();
healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(1));
var service = new HealthCheckService(healthNetConfiguration, Substitute.For<IVersionProvider>(),
new[] {hangingChecker, healthyChecker});
var task = Task<HealthResult>.Factory.StartNew(() => service.CheckHealth());
if (Task.WaitAll(new Task[] {task}, TimeSpan.FromSeconds(20)))
{
result = task.Result;
}
else
{
throw new TimeoutException();
}
}
[Test]
public void Overall_health_is_Serious()
{
result.Health.Should().Be(HealthState.Serious);
}
[Test]
public void Healthy_system_checker_result_is_returned()
{
result.SystemStates.Single(x => x.SystemName == "Healthy checker").Health.Should().Be(HealthState.Good);
}
[Test]
public void Hanging_system_checker_result_is_returned()
{
result.SystemStates.Single(x => x.SystemName == "Hanging checker").Health.Should().Be(HealthState.Serious);
}
}
} | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using NUnit.Framework;
namespace HealthNet.HealthCheckServiceFixtures
{
class When_getting_the_status_and_a_system_check_overruns
{
private HealthResult result;
[OneTimeSetUp]
public void SetUp()
{
var hangingChecker = Substitute.For<ISystemChecker>();
hangingChecker.SystemName.Returns("Hanging checker");
hangingChecker.CheckSystem().Returns(x =>
{
Thread.Sleep(TimeSpan.FromSeconds(20));
return (SystemCheckResult) null;
});
var healthyChecker = Substitute.For<ISystemChecker>();
healthyChecker.CheckSystem()
.Returns(x => new SystemCheckResult {SystemName = "Healthy checker", Health = HealthState.Good});
var healthNetConfiguration = Substitute.For<IHealthNetConfiguration>();
healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(1));
var service = new HealthCheckService(healthNetConfiguration, Substitute.For<IVersionProvider>(),
new[] {hangingChecker, healthyChecker});
var task = Task<HealthResult>.Factory.StartNew(() => service.CheckHealth());
if (Task.WaitAll(new Task[] {task}, TimeSpan.FromSeconds(10)))
{
result = task.Result;
}
else
{
throw new TimeoutException();
}
}
[Test]
public void Overall_health_is_Serious()
{
result.Health.Should().Be(HealthState.Serious);
}
[Test]
public void Healthy_system_checker_result_is_returned()
{
result.SystemStates.Single(x => x.SystemName == "Healthy checker").Health.Should().Be(HealthState.Good);
}
[Test]
public void Hanging_system_checker_result_is_returned()
{
result.SystemStates.Single(x => x.SystemName == "Hanging checker").Health.Should().Be(HealthState.Serious);
}
}
} | apache-2.0 | C# |
0d9c792575aa7c5239021600eb2f46b7ca4ec1ad | Set key in constructor [GREEN] | mattherman/MbDotNet,SuperDrew/MbDotNet,mattherman/MbDotNet | MbDotNet/Models/Imposters/HttpsImposter.cs | MbDotNet/Models/Imposters/HttpsImposter.cs | using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
[JsonProperty("key")]
public string Key { get; private set; }
public HttpsImposter(int port, string name) : this(port, name, null)
{
}
public HttpsImposter(int port, string name, string key) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Key = key;
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
| using MbDotNet.Models.Stubs;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MbDotNet.Models.Imposters
{
public class HttpsImposter : Imposter
{
[JsonProperty("stubs")]
public ICollection<HttpStub> Stubs { get; private set; }
public HttpsImposter(int port, string name) : base(port, MbDotNet.Enums.Protocol.Https, name)
{
Stubs = new List<HttpStub>();
}
public HttpStub AddStub()
{
var stub = new HttpStub();
Stubs.Add(stub);
return stub;
}
}
}
| mit | C# |
17de9972ba03f6bcca237d5930f7da5d8be41412 | remove dummy value | albertoms/monotouch-samples,nervevau2/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,kingyond/monotouch-samples,xamarin/monotouch-samples,a9upam/monotouch-samples,hongnguyenpro/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,davidrynn/monotouch-samples,markradacz/monotouch-samples,andypaul/monotouch-samples,davidrynn/monotouch-samples,peteryule/monotouch-samples,xamarin/monotouch-samples,W3SS/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,labdogg1003/monotouch-samples,peteryule/monotouch-samples,haithemaraissia/monotouch-samples,nelzomal/monotouch-samples,sakthivelnagarajan/monotouch-samples,nelzomal/monotouch-samples,nelzomal/monotouch-samples,labdogg1003/monotouch-samples,YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,kingyond/monotouch-samples,hongnguyenpro/monotouch-samples,andypaul/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,nervevau2/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,haithemaraissia/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,haithemaraissia/monotouch-samples,albertoms/monotouch-samples,albertoms/monotouch-samples,hongnguyenpro/monotouch-samples,andypaul/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,hongnguyenpro/monotouch-samples,W3SS/monotouch-samples,davidrynn/monotouch-samples,peteryule/monotouch-samples,a9upam/monotouch-samples,YOTOV-LIMITED/monotouch-samples,xamarin/monotouch-samples,iFreedive/monotouch-samples,a9upam/monotouch-samples,robinlaide/monotouch-samples | ios8/UICatalog/UICatalog/ViewControllers/Search/SearchControllers/SearchShowResultsInSourceViewController.cs | ios8/UICatalog/UICatalog/ViewControllers/Search/SearchControllers/SearchShowResultsInSourceViewController.cs | // This file has been autogenerated from a class added in the UI designer.
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace UICatalog
{
public partial class SearchShowResultsInSourceViewController : SearchResultsViewController
{
private UISearchController _searchController;
public SearchShowResultsInSourceViewController (IntPtr handle)
: base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Create the search controller, but we'll make sure that this SearchShowResultsInSourceViewController
// performs the results updating.
_searchController = new UISearchController ((UIViewController)null);
_searchController.SetSearchResultsUpdater (UpdateSearchResultsForSearchController);
_searchController.DimsBackgroundDuringPresentation = false;
// Make sure the that the search bar is visible within the navigation bar.
_searchController.SearchBar.SizeToFit ();
// Include the search controller's search bar within the table's header view.
TableView.TableHeaderView = _searchController.SearchBar;
DefinesPresentationContext = true;
}
}
}
| // This file has been autogenerated from a class added in the UI designer.
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace UICatalog
{
public partial class SearchShowResultsInSourceViewController : SearchResultsViewController
{
private UISearchController _searchController;
public SearchShowResultsInSourceViewController (IntPtr handle)
: base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Create the search controller, but we'll make sure that this AAPLSearchShowResultsInSourceViewController
// performs the results updating.
// TODO: parameter must be null https://trello.com/c/SibgrTuB
_searchController = new UISearchController (new UIViewController());
_searchController.SetSearchResultsUpdater (UpdateSearchResultsForSearchController);
_searchController.DimsBackgroundDuringPresentation = false;
// Make sure the that the search bar is visible within the navigation bar.
_searchController.SearchBar.SizeToFit ();
// Include the search controller's search bar within the table's header view.
TableView.TableHeaderView = _searchController.SearchBar;
DefinesPresentationContext = true;
}
}
}
| mit | C# |
b7a3106d0e4173b8aa73edb5f0adba50332a2b22 | Fix exception when saving asmdef file template | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/CSharp/Feature/Services/LiveTemplates/Scope/MustBeInProjectWithUnityVersion.cs | resharper/resharper-unity/src/CSharp/Feature/Services/LiveTemplates/Scope/MustBeInProjectWithUnityVersion.cs | using System;
using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.LiveTemplates.Scope
{
// If the scope point declares itself mandatory, then a template is unavailable unless the mandatory scope point is
// valid for the current context. E.g. a file template declares it is available for an InUnityProjectVersion(2017.3)
// scope point. If this mandatory scope point is not in the current context, the template is unavailable
public class MustBeInProjectWithUnityVersion : InAnyFile, IMandatoryScopePoint
{
// Serialised name, so don't use nameof
public const string TypeName = "MustBeInProjectWithUnityVersion";
public const string VersionProperty = "version";
private static readonly Guid ourDefaultUID = new Guid("7FB2BDA8-3264-4E6A-B319-4343C6F8A1F4");
private readonly Version myActualVersion;
public MustBeInProjectWithUnityVersion(Version minimumVersion)
{
myActualVersion = minimumVersion;
}
public override Guid GetDefaultUID() => ourDefaultUID;
public override string PresentableShortName => $"Unity {myActualVersion} and later projects";
// The real scope point is called, and passed in the allowed scope point from the template definition
public override bool IsSubsetOf(ITemplateScopePoint allowed)
{
if (!base.IsSubsetOf(allowed))
return false;
if (allowed is MustBeInProjectWithUnityVersion allowedScopePoint)
{
var allowedVersion = allowedScopePoint.myActualVersion;
return allowedVersion <= myActualVersion;
}
return true;
}
public override IEnumerable<Pair<string, string>> EnumerateCustomProperties()
{
yield return new Pair<string, string>(VersionProperty, myActualVersion.ToString());
}
public override string ToString()
{
return $"Unity minimum version: {myActualVersion}";
}
}
} | using System;
using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.LiveTemplates.Scope
{
// If the scope point declares itself mandatory, then a template is unavailable unless the mandatory scope point is
// valid for the current context. E.g. a file template declares it is available for an InUnityProjectVersion(2017.3)
// scope point. If this mandatory scope point is not in the current context, the template is unavailable
public class MustBeInProjectWithUnityVersion : InAnyFile, IMandatoryScopePoint
{
// Serialised name, so don't use nameof
public const string TypeName = "MustBeInProjectWithUnityVersion";
public const string VersionProperty = "version";
private static readonly Guid ourDefaultUID = new Guid("7FB2BDA8-3264-4E6A-B319-4343C6F8A1F4");
private readonly Version myActualVersion;
public MustBeInProjectWithUnityVersion(Version minimumVersion)
{
myActualVersion = minimumVersion;
}
public override Guid GetDefaultUID() => ourDefaultUID;
public override string PresentableShortName => $"Unity {myActualVersion} and later projects";
// The real scope point is called, and passed in the allowed scope point from the template definition
public override bool IsSubsetOf(ITemplateScopePoint allowed)
{
if (!base.IsSubsetOf(allowed))
return false;
if (allowed is MustBeInProjectWithUnityVersion allowedScopePoint)
{
var allowedVersion = allowedScopePoint.myActualVersion;
return allowedVersion <= myActualVersion;
}
return true;
}
public override IEnumerable<Pair<string, string>> EnumerateCustomProperties()
{
yield return new Pair<string, string>(VersionProperty, myActualVersion.ToString(3));
}
public override string ToString()
{
return $"Unity minimum version: {myActualVersion}";
}
}
} | apache-2.0 | C# |
da7c82f404fdb8ee658b5bef3ae827c62882f778 | Fix incorrect version number displayed when deployed | danielchalmers/DesktopWidgets | DesktopWidgets/Classes/AssemblyInfo.cs | DesktopWidgets/Classes/AssemblyInfo.cs | #region
using System;
using System.Deployment.Application;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
namespace DesktopWidgets.Classes
{
internal static class AssemblyInfo
{
public static Version Version { get; } = (ApplicationDeployment.IsNetworkDeployed
? ApplicationDeployment.CurrentDeployment.CurrentVersion
: Assembly.GetExecutingAssembly().GetName().Version);
public static string Copyright { get; } = GetAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright);
public static string Title { get; } = GetAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title);
public static string Description { get; } =
GetAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description);
public static string Guid { get; } = GetAssemblyAttribute<GuidAttribute>(a => a.Value);
private static string GetAssemblyAttribute<T>(Func<T, string> value)
where T : Attribute
{
var attribute = (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof (T));
return value.Invoke(attribute);
}
}
} | #region
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
namespace DesktopWidgets.Classes
{
internal static class AssemblyInfo
{
public static Version Version { get; } = Assembly.GetExecutingAssembly().GetName().Version;
public static string Copyright { get; } = GetAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright);
public static string Title { get; } = GetAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title);
public static string Description { get; } =
GetAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description);
public static string Guid { get; } = GetAssemblyAttribute<GuidAttribute>(a => a.Value);
private static string GetAssemblyAttribute<T>(Func<T, string> value)
where T : Attribute
{
var attribute = (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof (T));
return value.Invoke(attribute);
}
}
} | apache-2.0 | C# |
26c11d914616d10db871b77a18a255f59106bd68 | improve senpai experience | RPCS3/discord-bot | CompatBot/Commands/Attributes/RequiresDm.cs | CompatBot/Commands/Attributes/RequiresDm.cs | using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
namespace CompatBot.Commands.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
internal class RequiresDm: CheckBaseAttribute
{
private const string Source = "https://cdn.discordapp.com/attachments/417347469521715210/534798232858001418/24qx11.jpg";
private static readonly Lazy<byte[]> Poster = new Lazy<byte[]>(() =>
{
using (var client = HttpClientFactory.Create())
return client.GetByteArrayAsync(Source).ConfigureAwait(true).GetAwaiter().GetResult();
});
public override async Task<bool> ExecuteCheckAsync(CommandContext ctx, bool help)
{
if (ctx.Channel.IsPrivate || help)
return true;
using (var stream = new MemoryStream(Poster.Value))
await ctx.RespondWithFileAsync("senpai_plz.jpg", stream).ConfigureAwait(false);
return false;
}
}
} | using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
namespace CompatBot.Commands.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
internal class RequiresDm: CheckBaseAttribute
{
public override async Task<bool> ExecuteCheckAsync(CommandContext ctx, bool help)
{
if (ctx.Channel.IsPrivate || help)
return true;
await ctx.RespondAsync($"{ctx.Message.Author.Mention} https://cdn.discordapp.com/attachments/417347469521715210/534798232858001418/24qx11.jpg").ConfigureAwait(false);
return false;
}
}
} | lgpl-2.1 | C# |
ab043dcff8ac265af1205b03463e578af9556df0 | Bump version | EDDiscovery/EDDiscovery,EDDiscovery/EDDiscovery,EDDiscovery/EDDiscovery | EDDiscovery/Properties/AssemblyInfo.cs | EDDiscovery/Properties/AssemblyInfo.cs | /*
* Copyright © 2015 - 2021 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
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("EDDiscovery")]
[assembly: AssemblyDescription("Captains Log and more for Elite Dangerous")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EDDiscovery Team")]
[assembly: AssemblyProduct("EDDiscovery")]
[assembly: AssemblyCopyright("Copyright © EDD Team 2015-2021")]
[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("1ad84dc2-298f-4d18-8902-7948bccbdc72")]
// 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("12.1.500.0")]
| /*
* Copyright © 2015 - 2021 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
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("EDDiscovery")]
[assembly: AssemblyDescription("Captains Log and more for Elite Dangerous")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EDDiscovery Team")]
[assembly: AssemblyProduct("EDDiscovery")]
[assembly: AssemblyCopyright("Copyright © EDD Team 2015-2021")]
[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("1ad84dc2-298f-4d18-8902-7948bccbdc72")]
// 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("12.1.4.0")]
| apache-2.0 | C# |
84861374f430be8a4ce34431a0abc8b2368176e9 | Update PolyQuadraticBezierSegmentTests.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | tests/Core2D.UnitTests/Path/Segments/PolyQuadraticBezierSegmentTests.cs | tests/Core2D.UnitTests/Path/Segments/PolyQuadraticBezierSegmentTests.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 Core2D.Path.Segments;
using Core2D.Shapes;
using System.Linq;
using Xunit;
namespace Core2D.UnitTests
{
public class PolyQuadraticBezierSegmentTests
{
[Fact]
[Trait("Core2D.Path", "Segments")]
public void Points_Not_Null()
{
var target = new PolyQuadraticBezierSegment();
Assert.False(target.Points.IsDefault);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void GetPoints_Should_Return_All_Segment_Points()
{
var segment = new PolyQuadraticBezierSegment();
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
var target = segment.GetPoints();
var count = target.Count();
Assert.Equal(5, count);
Assert.Equal(segment.Points, target);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void ToString_Should_Return_Path_Markup()
{
var target = new PolyQuadraticBezierSegment();
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
var actual = target.ToString();
Assert.Equal("Q0,0 0,0 0,0 0,0 0,0", actual);
}
}
}
| // 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 Core2D.Path.Segments;
using Core2D.Shapes;
using System.Linq;
using Xunit;
namespace Core2D.UnitTests
{
public class PolyQuadraticBezierSegmentTests
{
[Fact]
[Trait("Core2D.Path", "Segments")]
public void Points_Not_Null()
{
var target = new PolyQuadraticBezierSegment();
Assert.NotNull(target.Points);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void GetPoints_Should_Return_All_Segment_Points()
{
var segment = new PolyQuadraticBezierSegment();
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
var target = segment.GetPoints();
Assert.Equal(5, target.Count());
Assert.Equal(segment.Points, target);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void ToString_Should_Return_Path_Markup()
{
var target = new PolyQuadraticBezierSegment();
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
var actual = target.ToString();
Assert.Equal("Q0,0 0,0 0,0 0,0 0,0", actual);
}
}
}
| mit | C# |
42a9e8e917cf93dde896fad4bd2597d2dbb1764e | Update GeoffreyHuntley.cs | beraybentesen/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,stvansolano/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,MabroukENG/planetxamarin,beraybentesen/planetxamarin,beraybentesen/planetxamarin,stvansolano/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/GeoffreyHuntley.cs | src/Firehose.Web/Authors/GeoffreyHuntley.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GeoffreyHuntley : IAmAMicrosoftMVP
{
public string FirstName => "Geoffrey";
public string LastName => "Huntley";
public string Title => "software engineer who likes both promite and vegemite";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "ghuntley@ghuntley.com";
public string TwitterHandle => "geoffreyhuntley";
public Uri WebSite => new Uri("https://ghuntley.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ghuntley.com/atom.xml"); } }
public DateTime FirstAwarded => new DateTime(2017, 1, 1);
public string GravatarHash => "";
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GeoffreyHuntley : IAmAMicrosoftMVP
{
public string FirstName => "Geoffrey";
public string LastName => "Huntley";
public string Title => "aussie who likes both promite and vegemite";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "ghuntley@ghuntley.com";
public string TwitterHandle => "geoffreyhuntley";
public Uri WebSite => new Uri("https://ghuntley.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ghuntley.com/atom.xml"); } }
public DateTime FirstAwarded => new DateTime(2017, 1, 1);
public string GravatarHash => "";
}
}
| mit | C# |
a3c3b5c74c3329bf0180eb3700627679a09b0a14 | Update 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();
}
}
}
| 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# |
e87061a407d993f80fb27372012e8690a45a1244 | Add Rest stuff to RestUser | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Rest/Entities/Users/RestUser.cs | src/NTwitch.Rest/Entities/Users/RestUser.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class RestUser : IUser
{
[JsonIgnore]
public TwitchRestClient Client { get; internal set; }
[JsonProperty("created_at")]
public DateTime CreatedAt { get; internal set; }
[JsonProperty("updated_at")]
public DateTime UpdatedAt { get; internal set; }
[JsonProperty("_id")]
public uint Id { get; internal set; }
[JsonProperty("name")]
public string Name { get; internal set; }
[JsonProperty("display_name")]
public string DisplayName { get; internal set; }
[JsonProperty("staff")]
public bool IsStaff { get; internal set; }
[JsonProperty("logo")]
public string LogoUrl { get; internal set; }
[JsonProperty("_links")]
public TwitchLinks Links { get; internal set; }
public Task<IChannelFollow> GetFollowAsync(string channel)
{
throw new NotImplementedException();
}
public Task<IChannelFollow> GetFollowAsync(IChannel channel)
{
throw new NotImplementedException();
}
public Task<IEnumerable<IChannel>> GetFollowsAsync(SortMode sort = SortMode.CreatedAt, SortDirection direction = SortDirection.Ascending, int limit = 10, int page = 1)
{
throw new NotImplementedException();
}
public override string ToString()
=> DisplayName;
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class RestUser : IUser
{
public TwitchRestClient Client { get; }
public DateTime CreatedAt { get; }
public DateTime UpdatedAt { get; }
public uint Id { get; }
public string Name { get; }
public string DisplayName { get; }
public string Bio { get; }
public string LogoUrl { get; }
public TwitchLinks Links { get; }
public Task<IChannelFollow> GetFollowAsync(string channel)
{
throw new NotImplementedException();
}
public Task<IChannelFollow> GetFollowAsync(IChannel channel)
{
throw new NotImplementedException();
}
public Task<IEnumerable<IChannel>> GetFollowsAsync(SortMode sort = SortMode.CreatedAt, SortDirection direction = SortDirection.Ascending, int limit = 10, int page = 1)
{
throw new NotImplementedException();
}
public override string ToString()
=> DisplayName;
}
}
| mit | C# |
d2775a6100f5e60952e734b198c98613bcf42640 | Improve funds display | jefftimlin/BetterLoadSaveGame | src/SaveGameInfo.cs | src/SaveGameInfo.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace BetterLoadSaveGame
{
public class SaveGameInfo
{
public FileInfo SaveFile { get; private set; }
public Dictionary<string, string> MetaData { get; private set; }
public SaveGameInfo(string saveFile)
{
SaveFile = new FileInfo(saveFile);
MetaData = new Dictionary<string, string>();
var metaFile = Path.ChangeExtension(saveFile, "loadmeta");
if (File.Exists(metaFile))
{
var content = File.ReadAllLines(metaFile);
foreach(var line in content)
{
var idx = line.IndexOf("=");
var key = line.Substring(0, idx).Trim();
var value = line.Substring(idx + 1).Trim();
MetaData.Add(key, value);
}
}
string funds = "";
if (MetaData.TryGetValue("funds", out funds))
{
double fundsAmount = int.Parse(funds) / 1000.0;
string suffix = "k";
if (fundsAmount > 1000)
{
fundsAmount /= 1000.0;
suffix = "m";
}
if (fundsAmount > 1000)
{
fundsAmount /= 1000.0;
suffix = "b";
}
funds = Math.Round(fundsAmount, 1).ToString() + suffix;
}
ButtonText = String.Format(" {0}\n {1}\n {2} funds", SaveFile.LastWriteTime, Path.GetFileNameWithoutExtension(SaveFile.Name), funds);
}
public string ButtonText { get; private set; }
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace BetterLoadSaveGame
{
public class SaveGameInfo
{
public FileInfo SaveFile { get; private set; }
public Dictionary<string, string> MetaData { get; private set; }
public SaveGameInfo(string saveFile)
{
SaveFile = new FileInfo(saveFile);
MetaData = new Dictionary<string, string>();
var metaFile = Path.ChangeExtension(saveFile, "loadmeta");
if (File.Exists(metaFile))
{
var content = File.ReadAllLines(metaFile);
foreach(var line in content)
{
var idx = line.IndexOf("=");
var key = line.Substring(0, idx).Trim();
var value = line.Substring(idx + 1).Trim();
MetaData.Add(key, value);
}
}
ButtonText = String.Format(" {0}\n {1}\n {2} funds", SaveFile.LastWriteTime, Path.GetFileNameWithoutExtension(SaveFile.Name), MetaData["funds"]);
}
public string ButtonText { get; private set; }
}
}
| mit | C# |
eaf754304f9d269501689d174b34de2bc0afc96c | Bump version to 0.8.3 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.8.3")]
[assembly: AssemblyInformationalVersionAttribute("0.8.3")]
[assembly: AssemblyFileVersionAttribute("0.8.3")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.8.3";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.8.2")]
[assembly: AssemblyInformationalVersionAttribute("0.8.2")]
[assembly: AssemblyFileVersionAttribute("0.8.2")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.8.2";
}
}
| apache-2.0 | C# |
b9cb3ca9a3bdc513f521d0ee7c61bcb569617d66 | bump 1.1.3 | GangZhuo/kcptun-gui-windows | kcptun-gui/Controller/MainController.cs | kcptun-gui/Controller/MainController.cs | using System;
using kcptun_gui.Model;
namespace kcptun_gui.Controller
{
public class MainController
{
public const string Version = "1.1.3";
public ConfigurationController ConfigController { get; private set; }
public KCPTunnelController KCPTunnelController { get; private set; }
public bool IsKcptunRunning
{
get { return KCPTunnelController.IsRunning; }
}
public MainController()
{
ConfigController = new ConfigurationController(this);
ConfigController.ConfigChanged += OnConfigChanged;
KCPTunnelController = new KCPTunnelController(this);
}
public void Start()
{
Reload();
}
public void Stop()
{
try
{
KCPTunnelController.Stop();
}
catch(Exception e)
{
Logging.LogUsefulException(e);
}
}
public void Reload()
{
try
{
if (KCPTunnelController.IsRunning)
KCPTunnelController.Stop();
Configuration config = ConfigController.GetCurrentConfiguration();
if (config.enabled)
{
KCPTunnelController.Server = config.GetCurrentServer();
KCPTunnelController.Start();
}
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}
}
private void OnConfigChanged(object sender, EventArgs e)
{
Reload();
}
}
}
| using System;
using kcptun_gui.Model;
namespace kcptun_gui.Controller
{
public class MainController
{
public const string Version = "1.1.2";
public ConfigurationController ConfigController { get; private set; }
public KCPTunnelController KCPTunnelController { get; private set; }
public bool IsKcptunRunning
{
get { return KCPTunnelController.IsRunning; }
}
public MainController()
{
ConfigController = new ConfigurationController(this);
ConfigController.ConfigChanged += OnConfigChanged;
KCPTunnelController = new KCPTunnelController(this);
}
public void Start()
{
Reload();
}
public void Stop()
{
try
{
KCPTunnelController.Stop();
}
catch(Exception e)
{
Logging.LogUsefulException(e);
}
}
public void Reload()
{
try
{
if (KCPTunnelController.IsRunning)
KCPTunnelController.Stop();
Configuration config = ConfigController.GetCurrentConfiguration();
if (config.enabled)
{
KCPTunnelController.Server = config.GetCurrentServer();
KCPTunnelController.Start();
}
}
catch (Exception e)
{
Logging.LogUsefulException(e);
}
}
private void OnConfigChanged(object sender, EventArgs e)
{
Reload();
}
}
}
| mit | C# |
6be8b42a30a15a81bd2fd60c5a15437e641fd8de | add getallergylist | EhrgoHealth/CS6440,EhrgoHealth/CS6440 | src/EhrgoHealth.Web/AddAllergyData.cs | src/EhrgoHealth.Web/AddAllergyData.cs | using Microsoft.Owin.Security;
using Owin.Security.Providers.Fitbit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EhrgoHealth.Web
{
public class AddAllergyData
{
private ApplicationUserManager userManager;
private IAuthenticationManager authManager;
public AddAllergyData()
{
}
public AddAllergyData(ApplicationUserManager userManager, IAuthenticationManager authManager)
{
this.userManager = userManager;
this.authManager = authManager;
}
public void AddAllergyToMedication(string fhirPatientId, string medicationName)
{
}
public void RemoveAllergyToMedication(string fhirPatientId, string medicationName)
{
}
public IEnumerable<string> GetAllergyList()
{
return Enumerable.Empty<string>();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EhrgoHealth.Web
{
public class AddAllergyData
{
public void AddAllergyToMedication(string fhirPatientId, string medicationName)
{
}
public void RemoveAllergyToMedication(string fhirPatientId, string medicationName)
{
}
}
} | mit | C# |
734968ca2f1306e20462eb0795345b365052d274 | fix minor build issue | spring-projects/spring-net-amqp | examples/Spring.RabbitQuickStart.2008/src/Spring/Spring.RabbitQuickStart.Client/Gateways/RabbitStockServiceGateway.cs | examples/Spring.RabbitQuickStart.2008/src/Spring/Spring.RabbitQuickStart.Client/Gateways/RabbitStockServiceGateway.cs |
using System;
using Spring.Messaging.Amqp.Core;
using Spring.Messaging.Amqp.Rabbit.Core.Support;
using Spring.RabbitQuickStart.Client.Gateways;
using Spring.RabbitQuickStart.Common.Data;
namespace Spring.RabbitQuickStart.Client.Gateways
{
public class RabbitStockServiceGateway : RabbitGatewaySupport, IStockService
{
private string defaultReplyToQueue;
public string DefaultReplyToQueue
{
set { defaultReplyToQueue = value; }
}
public void Send(TradeRequest tradeRequest)
{
RabbitTemplate.ConvertAndSend(tradeRequest, delegate(Message message)
{
message.MessageProperties.ReplyTo = defaultReplyToQueue;
message.MessageProperties.CorrelationId =
new Guid().ToByteArray();
return message;
});
}
}
} |
using System;
using Spring.Messaging.Amqp.Core;
using Spring.Messaging.Amqp.Rabbit.Core.Support;
using Spring.RabbitQuickStart.Client.Gateways;
using Spring.RabbitQuickStart.Common.Data;
namespace Spring.RabbitQuickStart.Client.Gateways
{
public class RabbitStockServiceGateway : RabbitGatewaySupport, IStockService
{
private string defaultReplyToQueue;
public string DefaultReplyToQueue
{
set { defaultReplyToQueue = value; }
}
public void Send(TradeRequest tradeRequest)
{
RabbitTemplate.ConvertAndSend(tradeRequest, delegate(Message message)
{
message.MessageProperties.ReplyTo = defaultReplyToQueue;
message.MessageProperties.CorrelationId =
new Guid().ToString();
return message;
});
}
}
} | apache-2.0 | C# |
c3e6f5fec89ddd72751c3da9536d434fbdea94a0 | Update RemoveAzureVirtualNetworkGatewayDefaultSiteCommand.cs | AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell | src/ResourceManager/Network/Commands.Network/VirtualNetworkGateway/RemoveAzureVirtualNetworkGatewayDefaultSiteCommand.cs | src/ResourceManager/Network/Commands.Network/VirtualNetworkGateway/RemoveAzureVirtualNetworkGatewayDefaultSiteCommand.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 AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.Remove, "AzureRmVirtualNetworkGatewayDefaultSite"), OutputType(typeof(PSVirtualNetworkGateway))]
public class RemoveAzureVirtualNetworkGatewayDefaultSiteCommand : VirtualNetworkGatewayBaseCmdlet
{
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
HelpMessage = "The VirtualNetworkGateway")]
[ValidateNotNull]
public PSVirtualNetworkGateway VirtualNetworkGateway { get; set; }
public override void Execute()
{
base.Execute();
if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
{
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound, this.VirtualNetworkGateway.Name));
}
this.VirtualNetworkGateway.GatewayDefaultSite = null;
// Map to the sdk object
var virtualnetGatewayModel = NetworkResourceManagerProfile.Mapper.Map<MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);
virtualnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);
this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name, virtualnetGatewayModel);
var getvirtualnetGateway = this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);
WriteObject(getvirtualnetGateway);
}
}
}
| // ----------------------------------------------------------------------------------
//
// 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 AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.Remove, "AzureRmVirtualNetworkGatewayDefaultSite"), OutputType(typeof(PSVirtualNetworkGateway))]
public class RemoveAzureVirtualNetworkGatewayDefaultSiteCommand : VirtualNetworkGatewayBaseCmdlet
{
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
HelpMessage = "The VirtualNetworkGateway")]
[ValidateNotNull]
public PSVirtualNetworkGateway VirtualNetworkGateway { get; set; }
public override void Execute()
{
base.Execute();
if (!this.IsVirtualNetworkGatewayPresent(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name))
{
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.ResourceNotFound, this.VirtualNetworkGateway.Name);
}
this.VirtualNetworkGateway.GatewayDefaultSite = null;
// Map to the sdk object
var virtualnetGatewayModel = NetworkResourceManagerProfile.Mapper.Map<MNM.VirtualNetworkGateway>(this.VirtualNetworkGateway);
virtualnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.VirtualNetworkGateway.Tag, validate: true);
this.VirtualNetworkGatewayClient.CreateOrUpdate(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name, virtualnetGatewayModel);
var getvirtualnetGateway = this.GetVirtualNetworkGateway(this.VirtualNetworkGateway.ResourceGroupName, this.VirtualNetworkGateway.Name);
WriteObject(getvirtualnetGateway);
}
}
}
| apache-2.0 | C# |
418bbcd4203274ad20df900ab03eff5c988ac853 | Fix spelling of "executable" | freenet/wintray,freenet/wintray | Browsers/Chrome.cs | Browsers/Chrome.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace FreenetTray.Browsers
{
class Chrome : IBrowser
{
/*
* Google Chrome does not maintain a registry entry with a path to its executable.
* Usual Google Chrome installation locations:
* See https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/browserlaunchers/locators/GoogleChromeLocator.java#63
*/
private static readonly string[] Locations = {
@"%LOCALAPPDATA%\Google\Chrome\Application",
@"%PROGRAMFILES%\Google\Chrome\Application",
@"%PROGRAMFILES(X86)%\Google\Chrome\Application",
};
private readonly string _path;
private readonly bool _isInstalled;
public Chrome()
{
_path = Locations
.Select(location => Environment.ExpandEnvironmentVariables(location) + @"\chrome.exe")
.Where(File.Exists)
.FirstOrDefault();
_isInstalled = _path != null;
}
public bool Open(Uri target)
{
if (!IsAvailable())
{
return false;
}
// See http://peter.sh/experiments/chromium-command-line-switches/
Process.Start(_path, "--incognito " + target);
return true;
}
public bool IsAvailable()
{
return _isInstalled;
}
public string GetName()
{
return "Chrome";
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace FreenetTray.Browsers
{
class Chrome : IBrowser
{
/*
* Google Chrome does not maintain a registry entry with a path to its exutable.
* Usual Google Chrome installation locations:
* See https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/browserlaunchers/locators/GoogleChromeLocator.java#63
*/
private static readonly string[] Locations = {
@"%LOCALAPPDATA%\Google\Chrome\Application",
@"%PROGRAMFILES%\Google\Chrome\Application",
@"%PROGRAMFILES(X86)%\Google\Chrome\Application",
};
private readonly string _path;
private readonly bool _isInstalled;
public Chrome()
{
_path = Locations
.Select(location => Environment.ExpandEnvironmentVariables(location) + @"\chrome.exe")
.Where(File.Exists)
.FirstOrDefault();
_isInstalled = _path != null;
}
public bool Open(Uri target)
{
if (!IsAvailable())
{
return false;
}
// See http://peter.sh/experiments/chromium-command-line-switches/
Process.Start(_path, "--incognito " + target);
return true;
}
public bool IsAvailable()
{
return _isInstalled;
}
public string GetName()
{
return "Chrome";
}
}
}
| mit | C# |
260356d075823feee0b83a4de1620b38b11f6f48 | Add tostring | Klocman/Bulk-Crap-Uninstaller,Klocman/Bulk-Crap-Uninstaller,Klocman/Bulk-Crap-Uninstaller | source/UninstallTools/Junk/Containers/JunkResultBase.cs | source/UninstallTools/Junk/Containers/JunkResultBase.cs | /*
Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/)
Apache License Version 2.0
*/
using System.IO;
using System.Security.Permissions;
using Klocman.Tools;
using UninstallTools.Junk.Confidence;
using UninstallTools.Properties;
namespace UninstallTools.Junk.Containers
{
public abstract class JunkResultBase : IJunkResult
{
protected JunkResultBase(ApplicationUninstallerEntry application, IJunkCreator source) : this(application, source, new ConfidenceCollection())
{
}
protected JunkResultBase(ApplicationUninstallerEntry application, IJunkCreator source, ConfidenceCollection confidence)
{
Application = application;
Source = source;
Confidence = confidence;
}
public ConfidenceCollection Confidence { get; }
public IJunkCreator Source { get; }
public ApplicationUninstallerEntry Application { get; }
public abstract void Backup(string backupDirectory);
public abstract void Delete();
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
public abstract void Open();
public abstract string GetDisplayName();
public virtual string ToLongString()
{
return
$@"{Application} - {Localisation.JunkRemover_Confidence}: {Confidence.GetConfidence()} - {
GetDisplayName()}";
}
/// <summary>
/// Prepare a backup directory in the specified parent folder, and return it.
/// </summary>
protected string CreateBackupDirectory(string parent)
{
var p = Path.Combine(parent, PathTools.SanitizeFileName(Application.DisplayName));
Directory.CreateDirectory(p);
return p;
}
public override string ToString()
{
return GetType().Name + " - " + GetDisplayName();
}
}
} | /*
Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/)
Apache License Version 2.0
*/
using System.IO;
using System.Security.Permissions;
using Klocman.Tools;
using UninstallTools.Junk.Confidence;
using UninstallTools.Properties;
namespace UninstallTools.Junk.Containers
{
public abstract class JunkResultBase : IJunkResult
{
protected JunkResultBase(ApplicationUninstallerEntry application, IJunkCreator source) : this(application, source, new ConfidenceCollection())
{
}
protected JunkResultBase(ApplicationUninstallerEntry application, IJunkCreator source, ConfidenceCollection confidence)
{
Application = application;
Source = source;
Confidence = confidence;
}
public ConfidenceCollection Confidence { get; }
public IJunkCreator Source { get; }
public ApplicationUninstallerEntry Application { get; }
public abstract void Backup(string backupDirectory);
public abstract void Delete();
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
public abstract void Open();
public abstract string GetDisplayName();
public virtual string ToLongString()
{
return
$@"{Application} - {Localisation.JunkRemover_Confidence}: {Confidence.GetConfidence()} - {
GetDisplayName()}";
}
/// <summary>
/// Prepare a backup directory in the specified parent folder, and return it.
/// </summary>
protected string CreateBackupDirectory(string parent)
{
var p = Path.Combine(parent, PathTools.SanitizeFileName(Application.DisplayName));
Directory.CreateDirectory(p);
return p;
}
}
} | apache-2.0 | C# |
15a725aa4bf5d031950436e22adccd53fb06fe02 | Fix formatting and add some constructor overloads | sharwell/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,mavasani/roslyn,mavasani/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,diryboy/roslyn,diryboy/roslyn,sharwell/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,diryboy/roslyn,bartdesmet/roslyn,dotnet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,dotnet/roslyn,KevinRansom/roslyn | src/EditorFeatures/Core/CodeDefinitionWindowLocation.cs | src/EditorFeatures/Core/CodeDefinitionWindowLocation.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor
{
internal struct CodeDefinitionWindowLocation
{
public string DisplayName { get; }
public string FilePath { get; }
public int Line { get; }
public int Character { get; }
public CodeDefinitionWindowLocation(string displayName, string filePath, int line, int character)
{
DisplayName = displayName;
FilePath = filePath;
Line = line;
Character = character;
}
public CodeDefinitionWindowLocation(string displayName, string filePath, LinePositionSpan position)
: this (displayName, filePath, position.Start.Line, position.Start.Character)
{
}
public CodeDefinitionWindowLocation(string displayName, FileLinePositionSpan position)
: this (displayName, position.Path, position.Span)
{
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor
{
internal struct CodeDefinitionWindowLocation
{
public string DisplayName { get; }
public string FilePath { get; }
public int Line { get; }
public int Character { get; }
public CodeDefinitionWindowLocation(string displayName, string filePath, int line, int character)
{
DisplayName = displayName;
FilePath = filePath;
Line = line;
Character = character;
}
}
}
| mit | C# |
1eb89b4f03901004fa766ae72a01cf77c9d6dcce | Remove Academic Year Left Of Line Unit Test | SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice | src/SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests/Orchestrators/Commitments/WhenValidatingApprenticeshipViewModel.cs | src/SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests/Orchestrators/Commitments/WhenValidatingApprenticeshipViewModel.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderApprenticeshipsService.Application.Queries.GetOverlappingApprenticeships;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Services;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models.Types;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests.Orchestrators.Commitments
{
[TestFixture]
public class WhenValidatingApprenticeshipViewModel : ApprenticeshipValidationTestBase
{
[SetUp]
public override void SetUp()
{
_currentDateTime = new CurrentDateTime(new DateTime(DateTime.Now.Year, 11, 01));
_mockMapper.Setup(m => m.MapOverlappingErrors(It.IsAny<GetOverlappingApprenticeshipsQueryResponse>()))
.Returns(new Dictionary<string, string>());
base.SetUp();
}
[Test]
public async Task ShouldAllowUpdateOfApprenticeshipWithStartDateInLastAcademicYear()
{
ValidModel.StartDate = new DateTimeViewModel(1, 08, DateTime.Now.Year);
ValidModel.EndDate = new DateTimeViewModel(1, 12, DateTime.Now.Year);
ValidModel.ULN = "1238894231";
var result = await _orchestrator.ValidateApprenticeship(ValidModel);
result.Keys.Should().NotContain($"{nameof(ValidModel.StartDate)}");
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderApprenticeshipsService.Application.Queries.GetOverlappingApprenticeships;
using SFA.DAS.ProviderApprenticeshipsService.Infrastructure.Services;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models.Types;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests.Orchestrators.Commitments
{
[TestFixture]
public class WhenValidatingApprenticeshipViewModel : ApprenticeshipValidationTestBase
{
[SetUp]
public override void SetUp()
{
_currentDateTime = new CurrentDateTime(new DateTime(DateTime.Now.Year, 11, 01));
_mockMapper.Setup(m => m.MapOverlappingErrors(It.IsAny<GetOverlappingApprenticeshipsQueryResponse>()))
.Returns(new Dictionary<string, string>());
base.SetUp();
}
[Test]
public async Task ShouldPreventUpdateOfApprenticeshipWithStartDateInLastAcademicYear()
{
ValidModel.StartDate = new DateTimeViewModel(1, 07, DateTime.Now.Year);
ValidModel.EndDate = new DateTimeViewModel(1, 12, DateTime.Now.Year);
ValidModel.ULN = "1238894231";
var result = await _orchestrator.ValidateApprenticeship(ValidModel);
result.Keys.Should().Contain($"{nameof(ValidModel.StartDate)}");
}
[Test]
public async Task ShouldAllowUpdateOfApprenticeshipWithStartDateInLastAcademicYear()
{
ValidModel.StartDate = new DateTimeViewModel(1, 08, DateTime.Now.Year);
ValidModel.EndDate = new DateTimeViewModel(1, 12, DateTime.Now.Year);
ValidModel.ULN = "1238894231";
var result = await _orchestrator.ValidateApprenticeship(ValidModel);
result.Keys.Should().NotContain($"{nameof(ValidModel.StartDate)}");
}
}
}
| mit | C# |
b59bd199eee50c1bc357e8d8d678fa2ea1fca108 | Add more properties found in Twitter V2 Url | linvi/tweetinvi,linvi/tweetinvi,linvi/tweetinvi,linvi/tweetinvi | src/Tweetinvi.Core/Public/Models/V2/Properties/UrlV2.cs | src/Tweetinvi.Core/Public/Models/V2/Properties/UrlV2.cs | using Newtonsoft.Json;
namespace Tweetinvi.Models.V2
{
public class UrlV2
{
/// <summary>
/// The URL as displayed in the Twitter client.
/// </summary>
[JsonProperty("display_url")] public string DisplayUrl { get; set; }
/// <summary>
/// The end position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("end")] public int End { get; set; }
/// <summary>
/// The fully resolved URL.
/// </summary>
[JsonProperty("expanded_url")] public string ExpandedUrl { get; set; }
/// <summary>
/// The start position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("start")] public int Start { get; set; }
/// <summary>
/// The URL in the format tweeted by the user.
/// </summary>
[JsonProperty("url")] public string Url { get; set; }
/// <summary>
/// The full destination URL.
/// </summary>
[JsonProperty("unwound_url")] public string UnwoundUrl { get; set; }
/// <summary>
/// Title of the URL
/// </summary>
[JsonProperty("title")] public string Title { get; set; }
/// <summary>
/// Description of the URL
/// </summary>
[JsonProperty("description")] public string Description { get; set; }
}
public class UrlsV2
{
/// <summary>
/// Contains details about text recognized as a URL.
/// </summary>
[JsonProperty("urls")] public UrlV2[] Urls { get; set; }
}
}
| using Newtonsoft.Json;
namespace Tweetinvi.Models.V2
{
public class UrlV2
{
/// <summary>
/// The URL as displayed in the Twitter client.
/// </summary>
[JsonProperty("display_url")] public string DisplayUrl { get; set; }
/// <summary>
/// The end position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("end")] public int End { get; set; }
/// <summary>
/// The fully resolved URL.
/// </summary>
[JsonProperty("expanded_url")] public string ExpandedUrl { get; set; }
/// <summary>
/// The start position (zero-based) of the recognized URL within the Tweet.
/// </summary>
[JsonProperty("start")] public int Start { get; set; }
/// <summary>
/// The URL in the format tweeted by the user.
/// </summary>
[JsonProperty("url")] public string Url { get; set; }
/// <summary>
/// The full destination URL.
/// </summary>
[JsonProperty("unwound_url")] public string UnwoundUrl { get; set; }
}
public class UrlsV2
{
/// <summary>
/// Contains details about text recognized as a URL.
/// </summary>
[JsonProperty("urls")] public UrlV2[] Urls { get; set; }
}
} | mit | C# |
176aa37aa3c78f303bbb901c2a27b70c005011dc | Add Japanese language to DefaultLanguagesCreator | aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template | aspnet-core/src/AbpCompanyName.AbpProjectName.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultLanguagesCreator.cs | aspnet-core/src/AbpCompanyName.AbpProjectName.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultLanguagesCreator.cs | using System.Collections.Generic;
using System.Linq;
using Abp.Localization;
using Microsoft.EntityFrameworkCore;
namespace AbpCompanyName.AbpProjectName.EntityFrameworkCore.Seed.Host
{
public class DefaultLanguagesCreator
{
public static List<ApplicationLanguage> InitialLanguages => GetInitialLanguages();
private readonly AbpProjectNameDbContext _context;
private static List<ApplicationLanguage> GetInitialLanguages()
{
return new List<ApplicationLanguage>
{
new ApplicationLanguage(null, "en", "English", "famfamfam-flags gb"),
new ApplicationLanguage(null, "ar", "العربية", "famfamfam-flags sa"),
new ApplicationLanguage(null, "de", "German", "famfamfam-flags de"),
new ApplicationLanguage(null, "it", "Italiano", "famfamfam-flags it"),
new ApplicationLanguage(null, "fr", "Français", "famfamfam-flags fr"),
new ApplicationLanguage(null, "pt-BR", "Portuguese", "famfamfam-flags br"),
new ApplicationLanguage(null, "tr", "Türkçe", "famfamfam-flags tr"),
new ApplicationLanguage(null, "ru", "Русский", "famfamfam-flags ru"),
new ApplicationLanguage(null, "zh-CN", "简体中文", "famfamfam-flags cn"),
new ApplicationLanguage(null, "es-MX", "Español México", "famfamfam-flags mx"),
new ApplicationLanguage(null, "ja", "日本語", "famfamfam-flags jp")
};
}
public DefaultLanguagesCreator(AbpProjectNameDbContext context)
{
_context = context;
}
public void Create()
{
CreateLanguages();
}
private void CreateLanguages()
{
foreach (var language in InitialLanguages)
{
AddLanguageIfNotExists(language);
}
}
private void AddLanguageIfNotExists(ApplicationLanguage language)
{
if (_context.Languages.IgnoreQueryFilters().Any(l => l.TenantId == language.TenantId && l.Name == language.Name))
{
return;
}
_context.Languages.Add(language);
_context.SaveChanges();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Abp.Localization;
using Microsoft.EntityFrameworkCore;
namespace AbpCompanyName.AbpProjectName.EntityFrameworkCore.Seed.Host
{
public class DefaultLanguagesCreator
{
public static List<ApplicationLanguage> InitialLanguages => GetInitialLanguages();
private readonly AbpProjectNameDbContext _context;
private static List<ApplicationLanguage> GetInitialLanguages()
{
return new List<ApplicationLanguage>
{
new ApplicationLanguage(null, "en", "English", "famfamfam-flags gb"),
new ApplicationLanguage(null, "ar", "العربية", "famfamfam-flags sa"),
new ApplicationLanguage(null, "de", "German", "famfamfam-flags de"),
new ApplicationLanguage(null, "it", "Italiano", "famfamfam-flags it"),
new ApplicationLanguage(null, "fr", "Français", "famfamfam-flags fr"),
new ApplicationLanguage(null, "pt-BR", "Portuguese", "famfamfam-flags br"),
new ApplicationLanguage(null, "tr", "Türkçe", "famfamfam-flags tr"),
new ApplicationLanguage(null, "ru", "Русский", "famfamfam-flags ru"),
new ApplicationLanguage(null, "zh-CN", "简体中文", "famfamfam-flags cn"),
new ApplicationLanguage(null, "es-MX", "Español México", "famfamfam-flags mx")
};
}
public DefaultLanguagesCreator(AbpProjectNameDbContext context)
{
_context = context;
}
public void Create()
{
CreateLanguages();
}
private void CreateLanguages()
{
foreach (var language in InitialLanguages)
{
AddLanguageIfNotExists(language);
}
}
private void AddLanguageIfNotExists(ApplicationLanguage language)
{
if (_context.Languages.IgnoreQueryFilters().Any(l => l.TenantId == language.TenantId && l.Name == language.Name))
{
return;
}
_context.Languages.Add(language);
_context.SaveChanges();
}
}
} | mit | C# |
b6254a1f252f55750cb66a9033f8e65719b35291 | Remove unnecessary casting | peppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu | osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/MultiSpectatorPlayer.cs | osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/MultiSpectatorPlayer.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.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
{
/// <summary>
/// A single spectated player within a <see cref="MultiSpectatorScreen"/>.
/// </summary>
public class MultiSpectatorPlayer : SpectatorPlayer
{
private readonly Bindable<bool> waitingOnFrames = new Bindable<bool>(true);
private readonly SpectatorPlayerClock spectatorPlayerClock;
/// <summary>
/// Creates a new <see cref="MultiSpectatorPlayer"/>.
/// </summary>
/// <param name="score">The score containing the player's replay.</param>
/// <param name="spectatorPlayerClock">The clock controlling the gameplay running state.</param>
public MultiSpectatorPlayer(Score score, SpectatorPlayerClock spectatorPlayerClock)
: base(score, new PlayerConfiguration { AllowUserInteraction = false })
{
this.spectatorPlayerClock = spectatorPlayerClock;
}
[BackgroundDependencyLoader]
private void load()
{
spectatorPlayerClock.WaitingOnFrames.BindTo(waitingOnFrames);
HUDOverlay.PlayerSettingsOverlay.Expire();
HUDOverlay.HoldToQuit.Expire();
}
protected override void Update()
{
// The player clock's running state is controlled externally, but the local pausing state needs to be updated to start/stop gameplay.
if (GameplayClockContainer.SourceClock.IsRunning)
GameplayClockContainer.Start();
else
GameplayClockContainer.Stop();
base.Update();
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
// This is required because the frame stable clock is set to WaitingOnFrames = false for one frame.
waitingOnFrames.Value = DrawableRuleset.FrameStableClock.WaitingOnFrames.Value || Score.Replay.Frames.Count == 0;
}
protected override GameplayClockContainer CreateGameplayClockContainer(WorkingBeatmap beatmap, double gameplayStart)
=> new GameplayClockContainer(spectatorPlayerClock);
}
}
| // 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.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
{
/// <summary>
/// A single spectated player within a <see cref="MultiSpectatorScreen"/>.
/// </summary>
public class MultiSpectatorPlayer : SpectatorPlayer
{
private readonly Bindable<bool> waitingOnFrames = new Bindable<bool>(true);
private readonly SpectatorPlayerClock spectatorPlayerClock;
/// <summary>
/// Creates a new <see cref="MultiSpectatorPlayer"/>.
/// </summary>
/// <param name="score">The score containing the player's replay.</param>
/// <param name="spectatorPlayerClock">The clock controlling the gameplay running state.</param>
public MultiSpectatorPlayer(Score score, SpectatorPlayerClock spectatorPlayerClock)
: base(score, new PlayerConfiguration { AllowUserInteraction = false })
{
this.spectatorPlayerClock = spectatorPlayerClock;
}
[BackgroundDependencyLoader]
private void load()
{
spectatorPlayerClock.WaitingOnFrames.BindTo(waitingOnFrames);
HUDOverlay.PlayerSettingsOverlay.Expire();
HUDOverlay.HoldToQuit.Expire();
}
protected override void Update()
{
// The player clock's running state is controlled externally, but the local pausing state needs to be updated to start/stop gameplay.
SpectatorPlayerClock clock = (SpectatorPlayerClock)GameplayClockContainer.SourceClock;
if (clock.IsRunning)
GameplayClockContainer.Start();
else
GameplayClockContainer.Stop();
base.Update();
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
// This is required because the frame stable clock is set to WaitingOnFrames = false for one frame.
waitingOnFrames.Value = DrawableRuleset.FrameStableClock.WaitingOnFrames.Value || Score.Replay.Frames.Count == 0;
}
protected override GameplayClockContainer CreateGameplayClockContainer(WorkingBeatmap beatmap, double gameplayStart)
=> new GameplayClockContainer(spectatorPlayerClock);
}
}
| mit | C# |
1cb5a4264096e5e563672e8bc48b0e2720376e67 | Use my enumerable in a loop | sushantgoel/MVA-LINQ,BillWagner/MVA-LINQ | CodePlayground/Program.cs | CodePlayground/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
class Program
{
static void Main(string[] args)
{
// This doesn't change (yet):
foreach (var item in GeneratedStrings())
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<string> GeneratedStrings()
{
var i = 0;
while (i++ < 100)
yield return i.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
class Program
{
static void Main(string[] args)
{
// This doesn't change (yet):
foreach (var item in GeneratedStrings())
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<string> GeneratedStrings()
{
yield return "one";
yield return "two";
yield return "three";
}
}
}
| apache-2.0 | C# |
7901081607b56fa6af1cf54fb262900b8d6f0834 | Fix missing newline after file header. | Sharparam/Colore,CoraleStudios/Colore,WolfspiritM/Colore,danpierce1/Colore | Colore/Razer/Constants.cs | Colore/Razer/Constants.cs | // ---------------------------------------------------------------------------------------
// <copyright file="Constants.cs" company="">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees
// and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility
// for any harm caused, direct or indirect, to any Razer peripherals
// via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
using System;
namespace Colore.Razer
{
/// <summary>
/// The definitions of generic constant values used in the project
/// </summary>
public static class Constants
{
/// <summary>
/// The Windows Message constant
/// </summary>
private const UInt32 WmApp = 0x8000;
/// <summary>
/// The Windows Chroma Event constant
/// </summary>
const UInt32 WmChromaEvent = WmApp + 0x2000;
}
}
| // ---------------------------------------------------------------------------------------
// <copyright file="Constants.cs" company="">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees
// and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility
// for any harm caused, direct or indirect, to any Razer peripherals
// via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
using System;
namespace Colore.Razer
{
/// <summary>
/// The definitions of generic constant values used in the project
/// </summary>
public static class Constants
{
/// <summary>
/// The Windows Message constant
/// </summary>
private const UInt32 WmApp = 0x8000;
/// <summary>
/// The Windows Chroma Event constant
/// </summary>
const UInt32 WmChromaEvent = WmApp + 0x2000;
}
}
| mit | C# |
9b7f6b3227cd8498daa59579bd273964b234e524 | Add meaningful ToString implementation for Target | chkn/Tempest | Desktop/Tempest/Target.cs | Desktop/Tempest/Target.cs | //
// Target.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2012 Eric Maupin
//
// 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 Tempest
{
public sealed class Target
: IEquatable<Target>, ISerializable
{
public const string AnyIP = "0.0.0.0";
public const string AnyIPv6 = "::";
public const string LoopbackIP = "127.0.0.1";
public const string LoopbackIPv6 = "[::1]";
public Target (string hostname, int port)
{
if (hostname == null)
throw new ArgumentNullException ("hostname");
Hostname = hostname;
Port = port;
}
public Target (ISerializationContext context, IValueReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
Deserialize (context, reader);
}
public string Hostname
{
get;
private set;
}
public int Port
{
get;
private set;
}
public override bool Equals (object obj)
{
if (ReferenceEquals (null, obj))
return false;
if (ReferenceEquals (this, obj))
return true;
return obj is Target && Equals ((Target)obj);
}
public bool Equals (Target other)
{
if (ReferenceEquals (null, other))
return false;
if (ReferenceEquals (this, other))
return true;
return (String.Equals (Hostname, other.Hostname) && Port == other.Port);
}
public override int GetHashCode()
{
unchecked
{
return (Hostname.GetHashCode() * 397) ^ Port;
}
}
public override string ToString ()
{
return string.Format ("{0}:{1}", Hostname, Port);
}
public static bool operator == (Target left, Target right)
{
return Equals (left, right);
}
public static bool operator != (Target left, Target right)
{
return !Equals (left, right);
}
public void Serialize (ISerializationContext context, IValueWriter writer)
{
writer.WriteString (Hostname);
writer.WriteInt32 (Port);
}
public void Deserialize (ISerializationContext context, IValueReader reader)
{
Hostname = reader.ReadString();
Port = reader.ReadInt32();
}
}
} | //
// Target.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2012 Eric Maupin
//
// 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 Tempest
{
public sealed class Target
: IEquatable<Target>, ISerializable
{
public const string AnyIP = "0.0.0.0";
public const string AnyIPv6 = "::";
public const string LoopbackIP = "127.0.0.1";
public const string LoopbackIPv6 = "[::1]";
public Target (string hostname, int port)
{
if (hostname == null)
throw new ArgumentNullException ("hostname");
Hostname = hostname;
Port = port;
}
public Target (ISerializationContext context, IValueReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
Deserialize (context, reader);
}
public string Hostname
{
get;
private set;
}
public int Port
{
get;
private set;
}
public override bool Equals (object obj)
{
if (ReferenceEquals (null, obj))
return false;
if (ReferenceEquals (this, obj))
return true;
return obj is Target && Equals ((Target)obj);
}
public bool Equals (Target other)
{
if (ReferenceEquals (null, other))
return false;
if (ReferenceEquals (this, other))
return true;
return (String.Equals (Hostname, other.Hostname) && Port == other.Port);
}
public override int GetHashCode()
{
unchecked
{
return (Hostname.GetHashCode() * 397) ^ Port;
}
}
public static bool operator == (Target left, Target right)
{
return Equals (left, right);
}
public static bool operator != (Target left, Target right)
{
return !Equals (left, right);
}
public void Serialize (ISerializationContext context, IValueWriter writer)
{
writer.WriteString (Hostname);
writer.WriteInt32 (Port);
}
public void Deserialize (ISerializationContext context, IValueReader reader)
{
Hostname = reader.ReadString();
Port = reader.ReadInt32();
}
}
} | mit | C# |
7ea404c862e74cdf04d806b6e8856948435bbf44 | Make sure window is visible. | fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game | game/client/ui/shell/shell.cs | game/client/ui/shell/shell.cs | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - shell.cs
// Code for Revenge Of The Cats' Shell
//------------------------------------------------------------------------------
if(isObject(DefaultCursor))
{
DefaultCursor.delete();
new GuiCursor(DefaultCursor)
{
hotSpot = "1 1";
bitmapName = "./pixmaps/mg_arrow2";
};
}
function addWindow(%control)
{
%parent = Shell;
if(Canvas.getContent() != Shell.getId())
%parent = ShellDlg;
%parent.add(%control);
%parent.pushToBack(%control);
%control.onAddedAsWindow();
Canvas.repaint();
}
function removeWindow(%control)
{
%control.getParent().remove(%control);
%control.onRemovedAsWindow();
Canvas.repaint();
}
function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount)
{
//
// display the root menu...
//
if( Shell.isMember(RootMenu) )
removeWindow(RootMenu);
else
{
RootMenu.position = %coord;
//addWindow(RootMenu);
//Canvas.repaint();
}
}
function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount)
{
//
}
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - shell.cs
// Code for Revenge Of The Cats' Shell
//------------------------------------------------------------------------------
if(isObject(DefaultCursor))
{
DefaultCursor.delete();
new GuiCursor(DefaultCursor)
{
hotSpot = "1 1";
bitmapName = "./pixmaps/mg_arrow2";
};
}
function addWindow(%control)
{
if(Canvas.getContent() == Shell.getId())
Shell.add(%control);
else
ShellDlg.add(%control);
%control.onAddedAsWindow();
Canvas.repaint();
}
function removeWindow(%control)
{
%control.getParent().remove(%control);
%control.onRemovedAsWindow();
Canvas.repaint();
}
function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount)
{
//
// display the root menu...
//
if( Shell.isMember(RootMenu) )
removeWindow(RootMenu);
else
{
RootMenu.position = %coord;
//addWindow(RootMenu);
//Canvas.repaint();
}
}
function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount)
{
//
}
| lgpl-2.1 | C# |
b69180e35f855479550596cc9aef3868c113df55 | Add basic test for ParallelFireworkAlgorithm. | sleshJdev/Fireworks.NET | src/FireworksNet.Tests/Algorithm/ParallelFireworkAlgorithmTests.cs | src/FireworksNet.Tests/Algorithm/ParallelFireworkAlgorithmTests.cs | using FireworksNet.Algorithm;
using FireworksNet.Algorithm.Implementation;
using FireworksNet.Problems;
using FireworksNet.StopConditions;
using System;
using Xunit;
namespace FireworksNet.Tests.Algorithm
{
public class ParallelFireworkAlgorithmTests : AlgorithmTestDataSource
{
[Theory]
[MemberData("DataForTestingCreationOfParallelFireworkAlgorithm")]
public void CreationParallelFireworkAlgorithm_PassEachParameterAsNullAndOtherIsCorrect_ArgumentNullExceptionThrown(
Problem problem, IStopCondition stopCondition, ParallelFireworksAlgorithmSettings settings, string expectedParamName)
{
ArgumentException exception = Assert.Throws<ArgumentNullException>(() => new ParallelFireworksAlgorithm(problem, stopCondition, settings));
Assert.Equal(expectedParamName, exception.ParamName);
}
}
}
| using FireworksNet.Algorithm;
using FireworksNet.Algorithm.Implementation;
using FireworksNet.Problems;
using FireworksNet.StopConditions;
using System;
using Xunit;
namespace FireworksNet.Tests.Algorithm
{
public class ParallelFireworkAlgorithmTests : AlgorithmTestDataSource
{
}
}
| mit | C# |
3ce9dd203ceb8e0e2a02669d99d637bb385db59e | Use proper format parameter names when logging | jskeet/nodatime.org,jskeet/nodatime.org,jskeet/nodatime.org,jskeet/nodatime.org | src/NodaTime.Web/Middleware/SingleLineResponseLoggingMiddleware.cs | src/NodaTime.Web/Middleware/SingleLineResponseLoggingMiddleware.cs | // Copyright 2019 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
namespace NodaTime.Web.Middleware
{
/// <summary>
/// By default, ASP.NET Core logs one line at the start of each request, and one line at the end of the request.
/// This middleware logs a single line per request. That means we can't see when a request starts as easily,
/// and won't see failure information, but it's otherwise easier to use.
/// </summary>
public sealed class SingleLineResponseLoggingMiddleware
{
private readonly Stopwatch stopwatch;
private readonly ILogger<SingleLineResponseLoggingMiddleware> logger;
private readonly RequestDelegate next;
public SingleLineResponseLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
stopwatch = Stopwatch.StartNew();
this.next = next;
logger = loggerFactory.CreateLogger<SingleLineResponseLoggingMiddleware>();
}
public async Task InvokeAsync(HttpContext context)
{
TimeSpan start = stopwatch.Elapsed;
await next(context);
TimeSpan end = stopwatch.Elapsed;
TimeSpan duration = end - start;
if (logger.IsEnabled(LogLevel.Information))
{
var request = context.Request;
var response = context.Response;
logger.LogInformation("{Method} {Path}{Query} => {StatusCode} {Duration:0.000}ms ({ForwardedFor}: {UserAgent})",
request.Method, request.Path, request.QueryString,
(HttpStatusCode) response.StatusCode, duration.TotalMilliseconds,
request.Headers["X-Forwarded-For"], request.Headers["User-Agent"]);
}
}
}
}
| // Copyright 2019 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
namespace NodaTime.Web.Middleware
{
/// <summary>
/// By default, ASP.NET Core logs one line at the start of each request, and one line at the end of the request.
/// This middleware logs a single line per request. That means we can't see when a request starts as easily,
/// and won't see failure information, but it's otherwise easier to use.
/// </summary>
public sealed class SingleLineResponseLoggingMiddleware
{
private readonly Stopwatch stopwatch;
private readonly ILogger<SingleLineResponseLoggingMiddleware> logger;
private readonly RequestDelegate next;
public SingleLineResponseLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
stopwatch = Stopwatch.StartNew();
this.next = next;
logger = loggerFactory.CreateLogger<SingleLineResponseLoggingMiddleware>();
}
public async Task InvokeAsync(HttpContext context)
{
TimeSpan start = stopwatch.Elapsed;
await next(context);
TimeSpan end = stopwatch.Elapsed;
TimeSpan duration = end - start;
if (logger.IsEnabled(LogLevel.Information))
{
var request = context.Request;
var response = context.Response;
logger.LogInformation("{0} {1}{2} => {3} {4:0.000}ms ({5}: {6})",
request.Method, request.Path, request.QueryString,
(HttpStatusCode) response.StatusCode, duration.TotalMilliseconds,
request.Headers["X-Forwarded-For"], request.Headers["User-Agent"]);
}
}
}
}
| apache-2.0 | C# |
80d3e332d1f1b2993f1358be4284332a86d81e26 | Remove unused usings | nguerrera/roslyn,jamesqo/roslyn,robinsedlaczek/roslyn,KevinRansom/roslyn,dotnet/roslyn,wvdd007/roslyn,srivatsn/roslyn,orthoxerox/roslyn,genlu/roslyn,diryboy/roslyn,mattwar/roslyn,lorcanmooney/roslyn,tmat/roslyn,OmarTawfik/roslyn,lorcanmooney/roslyn,vslsnap/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,vslsnap/roslyn,gafter/roslyn,reaction1989/roslyn,shyamnamboodiripad/roslyn,KevinH-MS/roslyn,srivatsn/roslyn,bkoelman/roslyn,robinsedlaczek/roslyn,physhi/roslyn,jasonmalinowski/roslyn,AnthonyDGreen/roslyn,jcouv/roslyn,amcasey/roslyn,AArnott/roslyn,mattscheffer/roslyn,jmarolf/roslyn,jcouv/roslyn,xasx/roslyn,paulvanbrenk/roslyn,stephentoub/roslyn,Pvlerick/roslyn,mmitche/roslyn,Hosch250/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,bbarry/roslyn,Pvlerick/roslyn,VSadov/roslyn,xoofx/roslyn,vslsnap/roslyn,KevinRansom/roslyn,mattwar/roslyn,MichalStrehovsky/roslyn,jkotas/roslyn,amcasey/roslyn,jmarolf/roslyn,swaroop-sridhar/roslyn,abock/roslyn,Pvlerick/roslyn,dpoeschl/roslyn,eriawan/roslyn,agocke/roslyn,wvdd007/roslyn,AmadeusW/roslyn,Giftednewt/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,xasx/roslyn,a-ctor/roslyn,physhi/roslyn,weltkante/roslyn,davkean/roslyn,mmitche/roslyn,brettfo/roslyn,Giftednewt/roslyn,mavasani/roslyn,eriawan/roslyn,diryboy/roslyn,OmarTawfik/roslyn,reaction1989/roslyn,khyperia/roslyn,jcouv/roslyn,tmeschter/roslyn,brettfo/roslyn,bkoelman/roslyn,kelltrick/roslyn,pdelvo/roslyn,aelij/roslyn,tannergooding/roslyn,AmadeusW/roslyn,cston/roslyn,xoofx/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,nguerrera/roslyn,dpoeschl/roslyn,a-ctor/roslyn,agocke/roslyn,VSadov/roslyn,jkotas/roslyn,eriawan/roslyn,jeffanders/roslyn,dotnet/roslyn,KevinH-MS/roslyn,MattWindsor91/roslyn,jasonmalinowski/roslyn,TyOverby/roslyn,davkean/roslyn,MattWindsor91/roslyn,drognanar/roslyn,pdelvo/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,tmat/roslyn,tannergooding/roslyn,AnthonyDGreen/roslyn,CaptainHayashi/roslyn,jeffanders/roslyn,tvand7093/roslyn,gafter/roslyn,yeaicc/roslyn,KevinH-MS/roslyn,diryboy/roslyn,tmat/roslyn,MattWindsor91/roslyn,MattWindsor91/roslyn,bbarry/roslyn,aelij/roslyn,panopticoncentral/roslyn,drognanar/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,kelltrick/roslyn,nguerrera/roslyn,brettfo/roslyn,tvand7093/roslyn,gafter/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,Hosch250/roslyn,xasx/roslyn,MichalStrehovsky/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,OmarTawfik/roslyn,orthoxerox/roslyn,lorcanmooney/roslyn,abock/roslyn,genlu/roslyn,mmitche/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,akrisiun/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,CaptainHayashi/roslyn,tmeschter/roslyn,aelij/roslyn,a-ctor/roslyn,sharwell/roslyn,paulvanbrenk/roslyn,reaction1989/roslyn,wvdd007/roslyn,zooba/roslyn,Giftednewt/roslyn,stephentoub/roslyn,AArnott/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,dotnet/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,tannergooding/roslyn,DustinCampbell/roslyn,davkean/roslyn,akrisiun/roslyn,zooba/roslyn,amcasey/roslyn,jkotas/roslyn,DustinCampbell/roslyn,tvand7093/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,kelltrick/roslyn,jamesqo/roslyn,srivatsn/roslyn,xoofx/roslyn,shyamnamboodiripad/roslyn,Hosch250/roslyn,pdelvo/roslyn,AArnott/roslyn,stephentoub/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,tmeschter/roslyn,orthoxerox/roslyn,CaptainHayashi/roslyn,agocke/roslyn,jasonmalinowski/roslyn,AnthonyDGreen/roslyn,TyOverby/roslyn,bkoelman/roslyn,mavasani/roslyn,drognanar/roslyn,bbarry/roslyn,yeaicc/roslyn,khyperia/roslyn,akrisiun/roslyn,bartdesmet/roslyn,mattwar/roslyn,physhi/roslyn,weltkante/roslyn,mattscheffer/roslyn,jmarolf/roslyn,cston/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,yeaicc/roslyn,heejaechang/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,cston/roslyn,KevinRansom/roslyn,genlu/roslyn,CyrusNajmabadi/roslyn,paulvanbrenk/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,mattscheffer/roslyn,zooba/roslyn,jeffanders/roslyn,khyperia/roslyn,shyamnamboodiripad/roslyn,robinsedlaczek/roslyn,dpoeschl/roslyn,weltkante/roslyn | src/Features/CSharp/Portable/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.FixAllProvider.cs | src/Features/CSharp/Portable/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.FixAllProvider.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.FixAllOccurrences;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess
{
internal partial class InvokeDelegateWithConditionalAccessCodeFixProvider : CodeFixProvider
{
/// <summary>
/// We use a specialized <see cref="FixAllProvider"/> so that we can make many edits to
/// the syntax tree which would otherwise be in close proximity. Close-proximity
/// edits can fail in the normal <see cref="BatchFixAllProvider" />. That's because
/// each individual edit will be diffed in the syntax tree. The diff is purely textual
/// and may result in a value that doesn't actually correspond to the syntax edit
/// made. As such, the individual textual edits wll overlap and won't merge properly.
///
/// By taking control ourselves, we can simply make all the tree edits and not have to
/// try to back-infer textual changes which then may or may not merge properly.
/// </summary>
private class InvokeDelegateWithConditionalAccessFixAllProvider : DocumentBasedFixAllProvider
{
private readonly InvokeDelegateWithConditionalAccessCodeFixProvider _provider;
public InvokeDelegateWithConditionalAccessFixAllProvider(InvokeDelegateWithConditionalAccessCodeFixProvider provider)
{
_provider = provider;
}
protected override Task<Document> FixDocumentAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
// Filter out the diagnostics we created for the faded out code. We don't want
// to try to fix those as well as the normal diagnostics we created.
var filteredDiagnostics = diagnostics.WhereAsArray(
d => !d.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary));
// Defer to the actual SimplifyNullCheckCodeFixProvider to process htis
// document. It can process all the diagnostics and apply them properly.
return _provider.FixAllAsync(document, filteredDiagnostics, cancellationToken);
}
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.FixAllOccurrences;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess
{
internal partial class InvokeDelegateWithConditionalAccessCodeFixProvider : CodeFixProvider
{
/// <summary>
/// We use a specialized <see cref="FixAllProvider"/> so that we can make many edits to
/// the syntax tree which would otherwise be in close proximity. Close-proximity
/// edits can fail in the normal <see cref="BatchFixAllProvider" />. That's because
/// each individual edit will be diffed in the syntax tree. The diff is purely textual
/// and may result in a value that doesn't actually correspond to the syntax edit
/// made. As such, the individual textual edits wll overlap and won't merge properly.
///
/// By taking control ourselves, we can simply make all the tree edits and not have to
/// try to back-infer textual changes which then may or may not merge properly.
/// </summary>
private class InvokeDelegateWithConditionalAccessFixAllProvider : DocumentBasedFixAllProvider
{
private readonly InvokeDelegateWithConditionalAccessCodeFixProvider _provider;
public InvokeDelegateWithConditionalAccessFixAllProvider(InvokeDelegateWithConditionalAccessCodeFixProvider provider)
{
_provider = provider;
}
protected override Task<Document> FixDocumentAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
// Filter out the diagnostics we created for the faded out code. We don't want
// to try to fix those as well as the normal diagnostics we created.
var filteredDiagnostics = diagnostics.WhereAsArray(
d => !d.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary));
// Defer to the actual SimplifyNullCheckCodeFixProvider to process htis
// document. It can process all the diagnostics and apply them properly.
return _provider.FixAllAsync(document, filteredDiagnostics, cancellationToken);
}
}
}
} | mit | C# |
09c5e2bf4cf2c65178a345afce0a38dd913d5a9d | Make solution mutation explicit | mavasani/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,tannergooding/roslyn,KevinRansom/roslyn,tmat/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,physhi/roslyn,bartdesmet/roslyn,sharwell/roslyn,heejaechang/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,aelij/roslyn,diryboy/roslyn,aelij/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,weltkante/roslyn,weltkante/roslyn,tmat/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,KevinRansom/roslyn,gafter/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,brettfo/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,tmat/roslyn,gafter/roslyn,AmadeusW/roslyn,physhi/roslyn,diryboy/roslyn,heejaechang/roslyn,AmadeusW/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,physhi/roslyn,gafter/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,brettfo/roslyn,sharwell/roslyn,mavasani/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,diryboy/roslyn,aelij/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,brettfo/roslyn | src/Features/LanguageServer/Protocol/Handler/ExportLspMethodAttribute.cs | src/Features/LanguageServer/Protocol/Handler/ExportLspMethodAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Defines an attribute for LSP request handlers to map to LSP methods.
/// </summary>
[AttributeUsage(AttributeTargets.Class), MetadataAttribute]
internal class ExportLspMethodAttribute : ExportAttribute, IRequestHandlerMetadata
{
public string MethodName { get; }
public string? LanguageName { get; }
/// <summary>
/// Whether or not handling this method results in changes to the current solution state.
/// Mutating requests will block all subsequent requests from starting until after they have
/// completed and mutations have been applied. See <see cref="RequestExecutionQueue"/>.
/// </summary>
public bool MutatesSolutionState { get; }
public ExportLspMethodAttribute(string methodName, bool mutatesSolutionState, string? languageName = null) : base(typeof(IRequestHandler))
{
if (string.IsNullOrEmpty(methodName))
{
throw new ArgumentException(nameof(methodName));
}
MethodName = methodName;
MutatesSolutionState = mutatesSolutionState;
LanguageName = languageName;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Defines an attribute for LSP request handlers to map to LSP methods.
/// </summary>
[AttributeUsage(AttributeTargets.Class), MetadataAttribute]
internal class ExportLspMethodAttribute : ExportAttribute, IRequestHandlerMetadata
{
public string MethodName { get; }
public string? LanguageName { get; }
/// <summary>
/// Whether or not handling this method results in changes to the current solution state.
/// Mutating requests will block all subsequent requests from starting until after they have
/// completed and mutations have been applied. See <see cref="RequestExecutionQueue"/>.
/// </summary>
public bool MutatesSolutionState { get; }
public ExportLspMethodAttribute(string methodName, string? languageName = null, bool mutatesSolutionState = false) : base(typeof(IRequestHandler))
{
if (string.IsNullOrEmpty(methodName))
{
throw new ArgumentException(nameof(methodName));
}
MethodName = methodName;
LanguageName = languageName;
MutatesSolutionState = mutatesSolutionState;
}
}
}
| mit | C# |
b0118afdbd9bb877eac3a1a6b88fb99b86323c50 | Update DisabledFacetTest.cs | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | NakedFramework/NakedFramework.Metamodel.Test/Facet/DisabledFacetTest.cs | NakedFramework/NakedFramework.Metamodel.Test/Facet/DisabledFacetTest.cs | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.VisualStudio.TestTools.UnitTesting;
using Moq;
using NakedFramework;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.interactions;
using NakedFramework.Core.Exception;
using NakedObjects.Meta.Facet;
namespace NakedObjects.Metamodel.Test.Facet {
[TestClass]
public class DisabledFacetTest {
[TestMethod]
public void TestDisabledFacetAlways() {
IDisabledFacet facet = new DisabledFacetAlways(null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationAlways() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Always, null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationNever() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Never, null);
Assert.IsNull(facet.DisabledReason(null));
}
private static INakedObjectAdapter Mock(object obj) {
var mockParm = new Mock<INakedObjectAdapter>();
mockParm.Setup(p => p.Object).Returns(obj);
return mockParm.Object;
}
[TestMethod]
public void TestDisabledFacetAnnotationAsInteraction() {
IDisablingInteractionAdvisor facet = new DisabledFacetAnnotation(WhenTo.Never, null);
var target = Mock(new object());
var mockIc = new Mock<IInteractionContext>();
mockIc.Setup(ic => ic.Target).Returns(target);
var e = facet.CreateExceptionFor(mockIc.Object);
Assert.IsInstanceOfType(e, typeof(DisabledException));
Assert.AreEqual("Exception of type 'NakedFramework.Core.DisabledException' was thrown.", e.Message);
}
}
} | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.VisualStudio.TestTools.UnitTesting;
using Moq;
using NakedFramework;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.interactions;
using NakedFramework.Core.Exception;
using NakedObjects.Meta.Facet;
namespace NakedObjects.Metamodel.Test.Facet {
[TestClass]
public class DisabledFacetTest {
[TestMethod]
public void TestDisabledFacetAlways() {
IDisabledFacet facet = new DisabledFacetAlways(null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationAlways() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Always, null);
Assert.AreEqual(Resources.NakedObjects.AlwaysDisabled, facet.DisabledReason(null));
}
[TestMethod]
public void TestDisabledFacetAnnotationNever() {
IDisabledFacet facet = new DisabledFacetAnnotation(WhenTo.Never, null);
Assert.IsNull(facet.DisabledReason(null));
}
private static INakedObjectAdapter Mock(object obj) {
var mockParm = new Mock<INakedObjectAdapter>();
mockParm.Setup(p => p.Object).Returns(obj);
return mockParm.Object;
}
[TestMethod]
public void TestDisabledFacetAnnotationAsInteraction() {
IDisablingInteractionAdvisor facet = new DisabledFacetAnnotation(WhenTo.Never, null);
var target = Mock(new object());
var mockIc = new Mock<IInteractionContext>();
mockIc.Setup(ic => ic.Target).Returns(target);
var e = facet.CreateExceptionFor(mockIc.Object);
Assert.IsInstanceOfType(e, typeof(DisabledException));
Assert.AreEqual("Exception of type 'NakedObjects.Core.DisabledException' was thrown.", e.Message);
}
}
} | apache-2.0 | C# |
659d4c8e269ad9b526dc64d04f3d968e4c4faafd | Add EndpointAssessorName to Apprenticeship type so can generate a new nuget package | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/SFA.DAS.Commitments.Api.Types/Apprenticeship/Apprenticeship.cs | src/SFA.DAS.Commitments.Api.Types/Apprenticeship/Apprenticeship.cs | using System;
using SFA.DAS.Commitments.Api.Types.Apprenticeship.Types;
namespace SFA.DAS.Commitments.Api.Types.Apprenticeship
{
public class Apprenticeship
{
public long Id { get; set; }
public long CommitmentId { get; set; }
public long EmployerAccountId { get; set; }
public long ProviderId { get; set; }
public string Reference { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public string NINumber { get; set; }
public string ULN { get; set; }
public TrainingType TrainingType { get; set; }
public string TrainingCode { get; set; }
public string TrainingName { get; set; }
public decimal? Cost { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime? PauseDate { get; set; }
public DateTime? StopDate { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public AgreementStatus AgreementStatus { get; set; }
public string EmployerRef { get; set; }
public string ProviderRef { get; set; }
public bool CanBeApproved { get; set; }
public Originator? PendingUpdateOriginator { get; set; }
public string ProviderName { get; set; }
public string LegalEntityId { get; set; }
public string LegalEntityName { get; set; }
public bool DataLockPrice { get; set; }
public bool DataLockPriceTriaged { get; set; }
public bool DataLockCourse { get; set; }
public bool DataLockCourseTriaged { get; set; }
public bool DataLockCourseChangeTriaged { get; set; }
public bool DataLockTriagedAsRestart { get; set; }
public bool HasHadDataLockSuccess { get; set; }
public string ApprenticeshipName => $"{FirstName} {LastName}";
public string EndpointAssessorName { get; set; }
}
} | using System;
using SFA.DAS.Commitments.Api.Types.Apprenticeship.Types;
namespace SFA.DAS.Commitments.Api.Types.Apprenticeship
{
public class Apprenticeship
{
public long Id { get; set; }
public long CommitmentId { get; set; }
public long EmployerAccountId { get; set; }
public long ProviderId { get; set; }
public string Reference { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public string NINumber { get; set; }
public string ULN { get; set; }
public TrainingType TrainingType { get; set; }
public string TrainingCode { get; set; }
public string TrainingName { get; set; }
public decimal? Cost { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime? PauseDate { get; set; }
public DateTime? StopDate { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public AgreementStatus AgreementStatus { get; set; }
public string EmployerRef { get; set; }
public string ProviderRef { get; set; }
public bool CanBeApproved { get; set; }
public Originator? PendingUpdateOriginator { get; set; }
public string ProviderName { get; set; }
public string LegalEntityId { get; set; }
public string LegalEntityName { get; set; }
public bool DataLockPrice { get; set; }
public bool DataLockPriceTriaged { get; set; }
public bool DataLockCourse { get; set; }
public bool DataLockCourseTriaged { get; set; }
public bool DataLockCourseChangeTriaged { get; set; }
public bool DataLockTriagedAsRestart { get; set; }
public bool HasHadDataLockSuccess { get; set; }
public string ApprenticeshipName => $"{FirstName} {LastName}";
}
} | mit | C# |
eb88b32b38a43db9b66d9c22b2b9145853247f17 | bump version in client message | MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net | Mindscape.Raygun4Net.NetCore.Common/Messages/RaygunClientMessage.cs | Mindscape.Raygun4Net.NetCore.Common/Messages/RaygunClientMessage.cs | namespace Mindscape.Raygun4Net
{
public class RaygunClientMessage
{
public RaygunClientMessage()
{
Name = "Raygun4Net.NetCore";
Version = "6.5.1";
ClientUrl = @"https://github.com/MindscapeHQ/raygun4net";
}
public string Name { get; set; }
public string Version { get; set; }
public string ClientUrl { get; set; }
}
} | namespace Mindscape.Raygun4Net
{
public class RaygunClientMessage
{
public RaygunClientMessage()
{
Name = "Raygun4Net.NetCore";
Version = "6.5.0";
ClientUrl = @"https://github.com/MindscapeHQ/raygun4net";
}
public string Name { get; set; }
public string Version { get; set; }
public string ClientUrl { get; set; }
}
} | mit | C# |
ad5da1d356b62b708fe90a5b67b20126408fcdfb | change props names in json file | juankakode/Drone | src/Drone/Drone.Lib/DroneConfig.cs | src/Drone/Drone.Lib/DroneConfig.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Drone.Lib.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Drone.Lib
{
public class DroneConfig
{
public static readonly string DroneFileName = "drone.json";
public static readonly string DroneDirName = "drone-files";
public static readonly string DroneReferencesDirName = "refs";
public static readonly string DroneBuildBaseDirName = "bin";
public static readonly string DroneSourceDirName = "src";
public static readonly string AssemblyFileName = "DroneUserTasks.dll";
[JsonIgnore]
public string HashId { get; private set; }
[JsonIgnore]
public string FilePath { get; private set; }
[JsonIgnore]
public string FileName { get; private set; }
[JsonIgnore]
public string DirPath { get; private set; }
[JsonIgnore]
public string BuildDirPath { get; private set; }
[JsonIgnore]
public string DroneDirPath { get; private set; }
[JsonIgnore]
public string DroneReferencesDirPath { get; private set; }
[JsonIgnore]
public string DroneSourceDirPath { get; private set; }
[JsonIgnore]
public string AssemblyFilePath { get; private set; }
[JsonProperty("src")]
public IList<string> SourceFiles { get; private set; }
[JsonProperty("refs")]
public IList<string> ReferenceFiles { get; private set; }
[JsonProperty("props")]
public JObject Props { get; private set; }
public DroneConfig()
{
this.SourceFiles = new List<string>();
this.ReferenceFiles = new List<string>();
this.Props = new JObject();
}
public void SetConfigFilename(string filePath)
{
if(filePath == null)
throw new ArgumentNullException("filePath");
this.FilePath = Path.GetFullPath(filePath);
this.FileName = Path.GetFileName(filePath);
this.HashId = HashHelper.GetHash(this.FilePath);
this.DirPath = Path.GetDirectoryName(this.FilePath);
this.DroneDirPath = Path.Combine(this.DirPath, DroneDirName);
this.DroneSourceDirPath = Path.Combine(this.DroneDirPath, DroneSourceDirName);
this.DroneReferencesDirPath = Path.Combine(this.DroneDirPath, DroneReferencesDirName);
this.BuildDirPath = Path.Combine(this.DroneDirPath, DroneBuildBaseDirName, this.HashId.Substring(0, 8));
this.AssemblyFilePath = Path.Combine(this.BuildDirPath, AssemblyFileName);
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Drone.Lib.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Drone.Lib
{
public class DroneConfig
{
public static readonly string DroneFileName = "drone.json";
public static readonly string DroneDirName = "drone-files";
public static readonly string DroneReferencesDirName = "refs";
public static readonly string DroneBuildBaseDirName = "bin";
public static readonly string DroneSourceDirName = "src";
public static readonly string AssemblyFileName = "DroneUserTasks.dll";
[JsonIgnore]
public string HashId { get; private set; }
[JsonIgnore]
public string FilePath { get; private set; }
[JsonIgnore]
public string FileName { get; private set; }
[JsonIgnore]
public string DirPath { get; private set; }
[JsonIgnore]
public string BuildDirPath { get; private set; }
[JsonIgnore]
public string DroneDirPath { get; private set; }
[JsonIgnore]
public string DroneReferencesDirPath { get; private set; }
[JsonIgnore]
public string DroneSourceDirPath { get; private set; }
[JsonIgnore]
public string AssemblyFilePath { get; private set; }
[JsonProperty("source-files")]
public IList<string> SourceFiles { get; private set; }
[JsonProperty("reference-files")]
public IList<string> ReferenceFiles { get; private set; }
[JsonProperty("props")]
public JObject Props { get; private set; }
public DroneConfig()
{
this.SourceFiles = new List<string>();
this.ReferenceFiles = new List<string>();
this.Props = new JObject();
}
public void SetConfigFilename(string filePath)
{
if(filePath == null)
throw new ArgumentNullException("filePath");
this.FilePath = Path.GetFullPath(filePath);
this.FileName = Path.GetFileName(filePath);
this.HashId = HashHelper.GetHash(this.FilePath);
this.DirPath = Path.GetDirectoryName(this.FilePath);
this.DroneDirPath = Path.Combine(this.DirPath, DroneDirName);
this.DroneSourceDirPath = Path.Combine(this.DroneDirPath, DroneSourceDirName);
this.DroneReferencesDirPath = Path.Combine(this.DroneDirPath, DroneReferencesDirName);
this.BuildDirPath = Path.Combine(this.DroneDirPath, DroneBuildBaseDirName, this.HashId.Substring(0, 8));
this.AssemblyFilePath = Path.Combine(this.BuildDirPath, AssemblyFileName);
}
}
} | mit | C# |
a85624bc7500c0bcca74f80ed9e2960be2e914f1 | Update PackagedProduct.cs | ADAPT/ADAPT | source/ADAPT/Products/PackagedProduct.cs | source/ADAPT/Products/PackagedProduct.cs | /*******************************************************************************
* Copyright (C) 2020 AgGateway and ADAPT Contributors
* Copyright (C) 2020 Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* R. Andres Ferreyra - initial implementation based on ProductStatusEnum class.
* *******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Representations;
namespace AgGateway.ADAPT.ApplicationDataModel.Products
{
public class PackagedProduct
{
public PackagedProduct()
{
Id = CompoundIdentifierFactory.Instance.Create();
ContainedPackagedProducts = new List<ContainedPackagedProduct>();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Description { get; set; }
public int ProductId { get; set; }
public int ContainerModelId { get; set; }
public PackagedProductStatusEnum Status { get; set; }
public NumericRepresentationValue ProductQuantity { get; set; }
public List<ContainedPackagedProduct> ContainedPackagedProducts { get; set; }
public NumericRepresentationValue GrossWeight { get; set; }
public NumericRepresentationValue NetWeight { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
| /*******************************************************************************
* Copyright (C) 2020 AgGateway and ADAPT Contributors
* Copyright (C) 2020 Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* R. Andres Ferreyra - initial implementation based on ProductStatusEnum class.
* *******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Representations;
namespace AgGateway.ADAPT.ApplicationDataModel.Products
{
public class PackagedProduct
{
public PackagedProduct()
{
Id = CompoundIdentifierFactory.Instance.Create();
ContainedPackagedProducts = new List(ContainedPackagedProduct);
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Description { get; set; }
public int ProductId { get; set; }
public int ContainerModelId { get; set; }
public PackagedProductStatusEnum Status { get; set; }
public NumericRepresentationValue ProductQuantity { get; set; }
public List<ContainedPackagedProduct> ContainedPackagedProducts { get; set; }
public NumericRepresentationValue GrossWeight { get; set; }
public NumericRepresentationValue NetWeight { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
| epl-1.0 | C# |
745780618d5a9f3e6fd411d97d86804cb91e8057 | Fix session parameter for moderator | c410echo/echo-asp | login.aspx.cs | login.aspx.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using TicketDBTableAdapters;
public partial class login:System.Web.UI.Page {
protected void Page_Load( object sender, EventArgs e ) {
}
protected void login_login_Authenticate( object sender, AuthenticateEventArgs e ) {
string login_name = login_login.UserName;
string pass = login_login.Password;
moderatorsTableAdapter mod_adapter = new moderatorsTableAdapter();
using (mod_adapter) {
TicketDB.moderatorsDataTable moderators = new TicketDB.moderatorsDataTable();
moderators = mod_adapter.get_authenticated_moderator( login_name, pass );
if (moderators.Rows.Count != 0) {
int mod_id = Convert.ToInt32(moderators.Rows[0].ItemArray[0]);
string mod_login_name = Convert.ToString(moderators.Rows[0].ItemArray[1]);
Hashtable moderator = new Hashtable();
moderator.Add( "mod_id", mod_id );
moderator.Add( "mod_login_name", mod_login_name );
Session.Add("Moderator",moderator);
Session.Add("mod_id", mod_id);
FormsAuthentication.SetAuthCookie(mod_login_name,false);
Response.Redirect("~/admin/profile.aspx");
}
else if (moderators.Rows.Count == 0) {
Response.Redirect( "~/contact.aspx" );
}
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using TicketDBTableAdapters;
public partial class login:System.Web.UI.Page {
protected void Page_Load( object sender, EventArgs e ) {
}
protected void login_login_Authenticate( object sender, AuthenticateEventArgs e ) {
string login_name = login_login.UserName;
string pass = login_login.Password;
moderatorsTableAdapter mod_adapter = new moderatorsTableAdapter();
using (mod_adapter) {
TicketDB.moderatorsDataTable moderators = new TicketDB.moderatorsDataTable();
moderators = mod_adapter.get_authenticated_moderator( login_name, pass );
if (moderators.Rows.Count != 0) {
int mod_id = Convert.ToInt32(moderators.Rows[0].ItemArray[0]);
string mod_login_name = Convert.ToString(moderators.Rows[0].ItemArray[1]);
Hashtable moderator = new Hashtable();
moderator.Add( "mod_id", mod_id );
moderator.Add( "mod_login_name", mod_login_name );
Session.Add("Moderator",moderator);
Session.Add("profile", mod_id);
FormsAuthentication.SetAuthCookie(mod_login_name,false);
Response.Redirect("~/admin/profile.aspx");
}
else if (moderators.Rows.Count == 0) {
Response.Redirect( "~/contact.aspx" );
}
}
}
} | mit | C# |
123b51ae768e5a5242581836e27161c13a629d02 | Update Version Information | usagirei/3DS-Theme-Editor | ThemeEditor.WPF/Properties/AssemblyInfo.cs | ThemeEditor.WPF/Properties/AssemblyInfo.cs | // --------------------------------------------------
// 3DS Theme Editor - AssemblyInfo.cs
// --------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;
// 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("Usagi 3DS Theme Editor")]
[assembly: AssemblyDescription("WPF Based 3DS Theme Editor ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Usagirei")]
[assembly: AssemblyProduct("3DS Theme Editor")]
[assembly: AssemblyCopyright("Copyright © Usagirei 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: DisableDpiAwareness]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.1")]
[assembly: AssemblyFileVersion("1.0.3.1")]
| // --------------------------------------------------
// 3DS Theme Editor - AssemblyInfo.cs
// --------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;
// 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("Usagi 3DS Theme Editor")]
[assembly: AssemblyDescription("WPF Based 3DS Theme Editor ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Usagirei")]
[assembly: AssemblyProduct("3DS Theme Editor")]
[assembly: AssemblyCopyright("Copyright © Usagirei 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: DisableDpiAwareness]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.0")]
[assembly: AssemblyFileVersion("1.0.3.1")]
| mit | C# |
590f43995270f5350b703e4165d41d76529f8347 | Add some xmldocs | vostok/core | Vostok.Core/Tracing/ITraceConfiguration.cs | Vostok.Core/Tracing/ITraceConfiguration.cs | using System;
using System.Collections.Generic;
using Vostok.Flow;
namespace Vostok.Tracing
{
public interface ITraceConfiguration
{
/// <summary>
/// Fields to be added as trace annotations from current <see cref="Context"/>
/// </summary>
ISet<string> ContextFieldsWhitelist { get; }
/// <summary>
/// Fields to be added as trace annotations from parent span
/// </summary>
ISet<string> InheritedFieldsWhitelist { get; }
Func<bool> IsEnabled { get; set; }
// TODO(iloktionov): Invent a way to automatically fill this with an out-of-the-box implementation in apps.
ITraceReporter Reporter { get; set; }
}
}
| using System;
using System.Collections.Generic;
namespace Vostok.Tracing
{
public interface ITraceConfiguration
{
ISet<string> ContextFieldsWhitelist { get; }
ISet<string> InheritedFieldsWhitelist { get; }
Func<bool> IsEnabled { get; set; }
// TODO(iloktionov): Invent a way to automatically fill this with an out-of-the-box implementation in apps.
ITraceReporter Reporter { get; set; }
}
}
| mit | C# |
a1aed44f109c0e38d9da85bea51f2e6a4ed6094c | Fix health not being calculated in osu! mode (regression). | 2yangk23/osu,tacchinotacchi/osu,Damnae/osu,DrabWeb/osu,Frontear/osuKyzer,osu-RP/osu-RP,peppy/osu,EVAST9919/osu,nyaamara/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,peppy/osu,naoey/osu,smoogipooo/osu,johnneijzen/osu,RedNesto/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,2yangk23/osu,DrabWeb/osu,NeoAdonis/osu,naoey/osu,peppy/osu-new,smoogipoo/osu,naoey/osu,UselessToucan/osu,Nabile-Rahmani/osu,Drezi126/osu,UselessToucan/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu | osu.Game.Modes.Osu/Scoring/OsuScoreProcessor.cs | osu.Game.Modes.Osu/Scoring/OsuScoreProcessor.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Judgements;
using osu.Game.Modes.Osu.Objects;
using osu.Game.Modes.Scoring;
using osu.Game.Modes.UI;
namespace osu.Game.Modes.Osu.Scoring
{
internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement>
{
public OsuScoreProcessor()
{
}
public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(OsuJudgement judgement)
{
if (judgement != null)
{
switch (judgement.Result)
{
case HitResult.Hit:
Health.Value += 0.1f;
break;
case HitResult.Miss:
Health.Value -= 0.2f;
break;
}
}
int score = 0;
int maxScore = 0;
foreach (var j in Judgements)
{
score += j.ScoreValue;
maxScore += j.MaxScoreValue;
}
TotalScore.Value = score;
Accuracy.Value = (double)score / maxScore;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Judgements;
using osu.Game.Modes.Osu.Objects;
using osu.Game.Modes.Scoring;
using osu.Game.Modes.UI;
namespace osu.Game.Modes.Osu.Scoring
{
internal class OsuScoreProcessor : ScoreProcessor<OsuHitObject, OsuJudgement>
{
public OsuScoreProcessor()
{
}
public OsuScoreProcessor(HitRenderer<OsuHitObject, OsuJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(OsuJudgement judgement)
{
int score = 0;
int maxScore = 0;
foreach (var j in Judgements)
{
score += j.ScoreValue;
maxScore += j.MaxScoreValue;
}
TotalScore.Value = score;
Accuracy.Value = (double)score / maxScore;
}
}
}
| mit | C# |
73929345bcb2a88dc7fc93d4bd48f0d4d42b300c | Add new overload to Compare method | Ackara/Daterpillar | src/Daterpillar.Core/Management/ISchemaComparer.cs | src/Daterpillar.Core/Management/ISchemaComparer.cs | using Gigobyte.Daterpillar.Transformation;
namespace Gigobyte.Daterpillar.Management
{
public interface ISchemaComparer : System.IDisposable
{
SchemaDiscrepancy Compare(Schema source, Schema target);
SchemaDiscrepancy Compare(ISchemaAggregator source, ISchemaAggregator target);
}
} | namespace Gigobyte.Daterpillar.Management
{
public interface ISchemaComparer : System.IDisposable
{
SchemaDiscrepancy Compare(ISchemaAggregator source, ISchemaAggregator target);
}
} | mit | C# |
65352f4a5ad1b29386cfccb39944ce566e5a0e79 | Fix comment typo. | autofac/Autofac.Extensions.DependencyInjection | src/Autofac.Extensions.DependencyInjection/ServiceCollectionExtensions.cs | src/Autofac.Extensions.DependencyInjection/ServiceCollectionExtensions.cs | // This software is part of the Autofac IoC container
// Copyright © 2017 Autofac Contributors
// http://autofac.org
//
// 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 Microsoft.Extensions.DependencyInjection;
namespace Autofac.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods on <see cref="IServiceCollection"/> to register the <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="AutofacServiceProviderFactory"/> to the service collection.
/// </summary>
/// <param name="services">The service collection to add the factory to.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the container.</param>
/// <returns>The service collection.</returns>
public static IServiceCollection AddAutofac(this IServiceCollection services, Action<ContainerBuilder> configurationAction = null)
{
return services.AddSingleton<IServiceProviderFactory<ContainerBuilder>>(new AutofacServiceProviderFactory(configurationAction));
}
}
}
| // This software is part of the Autofac IoC container
// Copyright © 2017 Autofac Contributors
// http://autofac.org
//
// 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 Microsoft.Extensions.DependencyInjection;
namespace Autofac.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods on <see cref="IServiceCollection"/> to register the <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="AutofacServiceProviderFactory"/> to the service collection.
/// </summary>
/// <param name="services">The service collection to add the factory to.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the conatiner.</param>
/// <returns>The service collection.</returns>
public static IServiceCollection AddAutofac(this IServiceCollection services, Action<ContainerBuilder> configurationAction = null)
{
return services.AddSingleton<IServiceProviderFactory<ContainerBuilder>>(new AutofacServiceProviderFactory(configurationAction));
}
}
}
| mit | C# |
2efbf9e579ce5f6aebaa73134ea74bf6434f1699 | Modify to read only for BindingVisibleRegionBehavior#Value. | nuitsjp/Xamarin.Forms.GoogleMaps.Bindings | Soruce/Xamarin.Forms.GoogleMaps.Bindings/BindingVisibleRegionBehavior.cs | Soruce/Xamarin.Forms.GoogleMaps.Bindings/BindingVisibleRegionBehavior.cs | using System.ComponentModel;
namespace Xamarin.Forms.GoogleMaps.Bindings
{
[Preserve(AllMembers = true)]
public class BindingVisibleRegionBehavior : BehaviorBase<Map>
{
private static readonly BindablePropertyKey ValuePropertyKey = BindableProperty.CreateReadOnly("Value", typeof(MapSpan), typeof(BindingVisibleRegionBehavior), default(MapSpan));
public static readonly BindableProperty ValueProperty = ValuePropertyKey.BindableProperty;
private MapSpan Value
{
set { SetValue(ValuePropertyKey, value); }
}
protected override void OnAttachedTo(Map bindable)
{
base.OnAttachedTo(bindable);
bindable.PropertyChanged += MapOnPropertyChanged;
}
protected override void OnDetachingFrom(Map bindable)
{
bindable.PropertyChanged -= MapOnPropertyChanged;
base.OnDetachingFrom(bindable);
}
private void MapOnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "VisibleRegion")
{
Value = AssociatedObject.VisibleRegion;
}
}
}
}
| using System.ComponentModel;
namespace Xamarin.Forms.GoogleMaps.Bindings
{
[Preserve(AllMembers = true)]
public class BindingVisibleRegionBehavior : BehaviorBase<Map>
{
public static readonly BindableProperty ValueProperty = BindableProperty.Create("Value", typeof(MapSpan), typeof(BindingVisibleRegionBehavior), default(MapSpan), BindingMode.OneWayToSource);
public MapSpan Value
{
set { SetValue(ValueProperty, value); }
}
protected override void OnAttachedTo(Map bindable)
{
base.OnAttachedTo(bindable);
bindable.PropertyChanged += BindableOnPropertyChanged;
}
protected override void OnDetachingFrom(Map bindable)
{
bindable.PropertyChanged -= BindableOnPropertyChanged;
base.OnDetachingFrom(bindable);
}
private void BindableOnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "VisibleRegion")
{
Value = AssociatedObject.VisibleRegion;
}
}
}
}
| mit | C# |
1aee75a0f3bf1812cf57d9f0369e423e5d78f5f0 | Rearrange invitee page | tpkelly/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,Generic-Voting-Application/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application | VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml | VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml | <div ng-app="GVA.Creation" ng-controller="ManageInviteesController">
<div class="centered">
<h2>Poll Invitees</h2>
<h4>Invited</h4>
<p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in invitedUsers">
<span class="invitee-pill-text">{{invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitedVoter(invitee)" aria-hidden="true"></span>
</div>
</div>
<h4>Pending</h4>
<input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" />
<span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span>
<p ng-if="pendingUsers.length === 0">No pending invitations</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="pending in pendingUsers">
<span class="invitee-pill-text">{{pending.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deletePendingVoter(pending)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section">
<button class="manage-btn" ng-click="discardChanges()">Cancel</button>
<button class="manage-btn" ng-disabled="isSaving" ng-click="saveChanges()">Save</button>
<button class="manage-btn" ng-if="pendingUsers.length > 0" ng-click="addInvitee(inviteString); sendInvitations();">Invite Pending</button>
</div>
</div>
</div>
| <div ng-app="GVA.Creation" ng-controller="ManageInviteesController">
<div class="centered">
<h2>Poll Invitees</h2>
<h4>Email to Invite</h4>
<input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" />
<span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span>
<h4>Pending</h4>
<p ng-if="pendingUsers.length === 0">No pending users</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="pending in pendingUsers">
<span class="invitee-pill-text">{{pending.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deletePendingVoter(pending)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section" ng-if="pendingUsers.length > 0">
<button class="manage-btn" ng-click="addInvitee(inviteString); sendInvitations();">Invite</button>
</div>
<h4>Invited</h4>
<p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in invitedUsers">
<span class="invitee-pill-text">{{invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitedVoter(invitee)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section">
<button class="manage-btn" ng-disabled="isSaving" ng-click="saveChanges()">Save</button>
<button class="manage-btn" ng-click="discardChanges()">Cancel</button>
</div>
</div>
</div>
| apache-2.0 | C# |
e8bdb60c10c4f0dd986c6ad63936fd76de07837e | Update XSelectableTests.cs | Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | tests/Core2D.UnitTests/Project/XSelectableTests.cs | tests/Core2D.UnitTests/Project/XSelectableTests.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 Core2D.Project;
using Xunit;
namespace Core2D.UnitTests
{
public class XSelectableTests
{
[Fact]
[Trait("Core2D.Project", "Project")]
public void Inherits_From_ObservableObject()
{
var target = new Class1();
Assert.True(target is ObservableObject);
}
private class Class1 : XSelectable
{
}
}
}
| // 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 Core2D.Project;
using Xunit;
namespace Core2D.UnitTests
{
public class XSelectableTests
{
[Fact]
[Trait("Core2D.Project", "Project")]
public void Inherits_From_ObservableResource()
{
var target = new Class1();
Assert.True(target is ObservableResource);
}
private class Class1 : XSelectable
{
}
}
}
| mit | C# |
523bfccc0e82fbfa974707a06cb574cc385ba882 | Fix missing code docs. | korsimoro/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,korsimoro/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,korsimoro/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,srottem/indy-sdk,korsimoro/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,korsimoro/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,korsimoro/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,korsimoro/indy-sdk,anastasia-tarasova/indy-sdk | wrappers/dotnet/indy-sdk-dotnet/SovrinConstants.cs | wrappers/dotnet/indy-sdk-dotnet/SovrinConstants.cs | using System;
namespace Indy.Sdk.Dotnet
{
/// <summary>
/// Constants used in Sovrin.
/// </summary>
public static class SovrinConstants
{
/// <summary>
/// Role for trustees.
/// </summary>
public const String ROLE_TRUSTEE = "TRUSTEE";
/// <summary>
/// Role for stewards.
/// </summary>
public const String ROLE_STEWARD = "STEWARD";
/// <summary>
/// OP_NODE value.
/// </summary>
public const String OP_NODE = "0";
/// <summary>
/// OP_NYM value.
/// </summary>
public const String OP_NYM = "1";
/// <summary>
/// OP_ATTRIB value.
/// </summary>
public const String OP_ATTRIB = "100";
/// <summary>
/// OP_SCHEMA value.
/// </summary>
public const String OP_SCHEMA = "101";
/// <summary>
/// OP_CLAIM_DEF value.
/// </summary>
public const String OP_CLAIM_DEF = "102";
/// <summary>
/// OP_GET_ATTR value.
/// </summary>
public const String OP_GET_ATTR = "104";
/// <summary>
/// OP_GET_NYM value.
/// </summary>
public const String OP_GET_NYM = "105";
/// <summary>
/// OP_GET_SCHEMA value.
/// </summary>
public const String OP_GET_SCHEMA = "107";
/// <summary>
/// OP_GET_CLAIM_DEF value.
/// </summary>
public const String OP_GET_CLAIM_DEF = "108";
}
}
| using System;
namespace Indy.Sdk.Dotnet
{
/// <summary>
/// Constants used in Sovrin.
/// </summary>
public static class SovrinConstants
{
public const String ROLE_TRUSTEE = "TRUSTEE";
public const String ROLE_STEWARD = "STEWARD";
public const String OP_NODE = "0";
public const String OP_NYM = "1";
public const String OP_ATTRIB = "100";
public const String OP_SCHEMA = "101";
public const String OP_CLAIM_DEF = "102";
public const String OP_GET_ATTR = "104";
public const String OP_GET_NYM = "105";
public const String OP_GET_SCHEMA = "107";
public const String OP_GET_CLAIM_DEF = "108";
}
}
| apache-2.0 | C# |
878f1bf194d376c1feee9e92a4bb5452b0cddd98 | Test that nameof nag is ignored in [DebuggerDisplay] | JohanLarsson/Gu.Analyzers | Gu.Analyzers.Test/GU0006UseNameofTests/HappyPath.cs | Gu.Analyzers.Test/GU0006UseNameofTests/HappyPath.cs | namespace Gu.Analyzers.Test.GU0006UseNameofTests
{
using System.Threading.Tasks;
using NUnit.Framework;
internal class HappyPath : HappyPathVerifier<GU0006UseNameof>
{
[Test]
public async Task WhenThrowingArgumentException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
[Test]
public async Task ArgumentOutOfRangeException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(StringComparison value)
{
switch (value)
{
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
[Test]
public async Task IgnoresDebuggerDisplay()
{
var testCode = @"
[System.Diagnostics.DebuggerDisplay(""{Name}"")]
public class Foo
{
public string Name { get; }
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
}
} | namespace Gu.Analyzers.Test.GU0006UseNameofTests
{
using System.Threading.Tasks;
using NUnit.Framework;
internal class HappyPath : HappyPathVerifier<GU0006UseNameof>
{
[Test]
public async Task WhenThrowingArgumentException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
[Test]
public async Task ArgumentOutOfRangeException()
{
var testCode = @"
using System;
public class Foo
{
public void Meh(StringComparison value)
{
switch (value)
{
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
}";
await this.VerifyHappyPathAsync(testCode)
.ConfigureAwait(false);
}
}
} | mit | C# |
0fbe1054303ec6c7270d5f84948b991979992b8e | Revert "give compilation error instead of warning or exception at runtime" | adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,redknightlois/BenchmarkDotNet,Ky7m/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,Ky7m/BenchmarkDotNet | BenchmarkDotNet.Diagnostics.Windows/GCDiagnoser.cs | BenchmarkDotNet.Diagnostics.Windows/GCDiagnoser.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
namespace BenchmarkDotNet.Diagnostics.Windows
{
[Obsolete(message)]
public class GCDiagnoser : IDiagnoser, IColumnProvider
{
const string message = "The \"GCDiagnoser\" has been renamed, please us the \"MemoryDiagnoser\" instead (it has the same functionality)";
public IEnumerable<IColumn> GetColumns
{
get { throw new InvalidOperationException(message); }
}
public void AfterBenchmarkHasRun(Benchmark benchmark, Process process)
{
throw new InvalidOperationException(message);
}
public void DisplayResults(ILogger logger)
{
throw new InvalidOperationException(message);
}
public void ProcessStarted(Process process)
{
throw new InvalidOperationException(message);
}
public void ProcessStopped(Process process)
{
throw new InvalidOperationException(message);
}
public void Start(Benchmark benchmark)
{
throw new InvalidOperationException(message);
}
public void Stop(Benchmark benchmark, BenchmarkReport report)
{
throw new InvalidOperationException(message);
}
}
}
| using System;
namespace BenchmarkDotNet.Diagnostics
{
[Obsolete("The \"GCDiagnoser\" has been renamed, please use the \"MemoryDiagnoser\" instead (it has the same functionality)", true)]
public class GCDiagnoser
{
}
}
| mit | C# |
4702f28ae51dfebbdf93b4562d0ea6a2784b08a0 | Allow to extract 000xx.idx from the UI version of IdxImg | Xeeynamo/KingdomHearts | OpenKh.Tools.IdxImg/ViewModels/EntryParserModel.cs | OpenKh.Tools.IdxImg/ViewModels/EntryParserModel.cs | using OpenKh.Kh2;
using OpenKh.Tools.IdxImg.Interfaces;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Tools.IdxImg.ViewModels
{
internal class EntryParserModel
{
internal EntryParserModel(Idx.Entry entry)
{
Entry = entry;
Path = entry.GetFullName();
SplitPath = Path.Split('/');
}
public Idx.Entry Entry { get; }
public string Path { get; }
public string[] SplitPath { get; }
public string Name => SplitPath[^1];
public bool IsIdx => IsLeaf(0) &&
System.IO.Path.GetExtension(Name).ToLower() == ".idx";
public bool IsLeaf(int index) => SplitPath.Length == index + 1;
public static IEnumerable<EntryViewModel> GetEntries(
List<EntryParserModel> entries, int depth, IIdxManager idxManager)
{
var dirs = entries
.Where(x => !x.IsLeaf(depth))
.GroupBy(x => x.SplitPath[depth])
.Select(x => new FolderViewModel(x.Key, depth + 1, x, idxManager));
var files =
entries
.Where(x => x.IsLeaf(depth))
.Select(x => new FileViewModel(x, idxManager));
var tree = dirs.Cast<EntryViewModel>().Concat(files);
if (depth == 0)
tree = entries
.Where(x => x.IsIdx)
.Select(x => new IdxViewModel(x.Name, x.Entry, idxManager))
.Cast<EntryViewModel>()
.Concat(tree);
return tree;
}
public static IEnumerable<EntryViewModel> GetChildren(
List<Idx.Entry> idxEntries, IIdxManager idxManager)
{
var entries = idxEntries
.Select(x => new EntryParserModel(x))
.OrderBy(x => x.Path)
.ToList();
return GetEntries(entries, 0, idxManager);
}
}
}
| using OpenKh.Kh2;
using OpenKh.Tools.IdxImg.Interfaces;
using System.Collections.Generic;
using System.Linq;
namespace OpenKh.Tools.IdxImg.ViewModels
{
internal class EntryParserModel
{
internal EntryParserModel(Idx.Entry entry)
{
Entry = entry;
Path = entry.GetFullName();
SplitPath = Path.Split('/');
}
public Idx.Entry Entry { get; }
public string Path { get; }
public string[] SplitPath { get; }
public string Name => SplitPath[^1];
public bool IsIdx => IsLeaf(0) &&
System.IO.Path.GetExtension(Name).ToLower() == ".idx";
public bool IsLeaf(int index) => SplitPath.Length == index + 1;
public static IEnumerable<EntryViewModel> GetEntries(
List<EntryParserModel> entries, int depth, IIdxManager idxManager)
{
var dirs = entries
.Where(x => !x.IsLeaf(depth))
.GroupBy(x => x.SplitPath[depth])
.Select(x => new FolderViewModel(x.Key, depth + 1, x, idxManager));
var files =
entries
.Where(x => x.IsLeaf(depth) && !x.IsIdx)
.Select(x => new FileViewModel(x, idxManager));
var tree = dirs.Cast<EntryViewModel>().Concat(files);
if (depth == 0)
tree = entries
.Where(x => x.IsIdx)
.Select(x => new IdxViewModel(x.Name, x.Entry, idxManager))
.Cast<EntryViewModel>()
.Concat(tree);
return tree;
}
public static IEnumerable<EntryViewModel> GetChildren(
List<Idx.Entry> idxEntries, IIdxManager idxManager)
{
var entries = idxEntries
.Select(x => new EntryParserModel(x))
.OrderBy(x => x.Path)
.ToList();
return GetEntries(entries, 0, idxManager);
}
}
}
| mit | C# |
9de14b0744122562b637bbf58054f406a82cde68 | copy change | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Web/Views/EmployerCommitments/SubmitCommitmentEntry.cshtml | src/SFA.DAS.EAS.Web/Views/EmployerCommitments/SubmitCommitmentEntry.cshtml | @using SFA.DAS.EAS.Web.Models
@model SubmitCommitmentViewModel
@{
var targetName = string.IsNullOrWhiteSpace(Model.HashedCommitmentId) ? "SubmitNewCommitmentEntry" : "SubmitExistingCommitmentEntry";
}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Instructions for your training provider</h1>
<p class="lede">Let <span class="heading-medium">@Model.ProviderName</span> know which apprentices you'd like them to add.
</p>
<form method="POST" action="@Url.Action(targetName)">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label strong" for="Message">Instructions (optional)</label>
<p class="form-hint">For example, please add the 12 admin level 2 apprentices and 13 engineering level 3 apprentices</p>
<textarea class="form-control form-control-3-4" id="Message" name="Message"
cols="40" rows="10"
aria-required="true"></textarea>
</div>
@Html.HiddenFor(x => x.HashedCommitmentId)
@Html.HiddenFor(x => x.LegalEntityCode)
@Html.HiddenFor(x => x.LegalEntityName)
@Html.HiddenFor(x => x.ProviderId)
@Html.HiddenFor(x => x.ProviderName)
@Html.HiddenFor(x => x.CohortRef)
@Html.HiddenFor(x => x.SaveOrSend)
<button type="submit" class="button">Send</button>
</form>
</div>
</div>
| @using SFA.DAS.EAS.Web.Models
@model SubmitCommitmentViewModel
@{
var targetName = string.IsNullOrWhiteSpace(Model.HashedCommitmentId) ? "SubmitNewCommitmentEntry" : "SubmitExistingCommitmentEntry";
}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Instructions for your training provider</h1>
<p class="lede">Let <span class="heading-medium">@Model.ProviderName</span> know which apprentices you'd like them to add.
</p>
<form method="POST" action="@Url.Action(targetName)">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label strong" for="Message">Instructions</label>
<p class="form-hint">For example, please add the 12 admin level 2 apprentices and 13 engineering level 3 apprentices</p>
<textarea class="form-control form-control-3-4" id="Message" name="Message"
cols="40" rows="10"
aria-required="true"></textarea>
</div>
@Html.HiddenFor(x => x.HashedCommitmentId)
@Html.HiddenFor(x => x.LegalEntityCode)
@Html.HiddenFor(x => x.LegalEntityName)
@Html.HiddenFor(x => x.ProviderId)
@Html.HiddenFor(x => x.ProviderName)
@Html.HiddenFor(x => x.CohortRef)
@Html.HiddenFor(x => x.SaveOrSend)
<button type="submit" class="button">Send</button>
</form>
</div>
</div>
| mit | C# |
3d7b5d7ea0218394adeede54aff24cfd564f153f | Install all indexes by scanning assembly | dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan | Snittlistan/Infrastructure/Indexes/IndexCreator.cs | Snittlistan/Infrastructure/Indexes/IndexCreator.cs | using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using Raven.Client;
using Raven.Client.Indexes;
namespace Snittlistan.Infrastructure.Indexes
{
public static class IndexCreator
{
public static void CreateIndexes(IDocumentStore store)
{
var indexes = from type in Assembly.GetExecutingAssembly().GetTypes()
where
type.IsSubclassOf(typeof(AbstractIndexCreationTask))
select type;
var typeCatalog = new TypeCatalog(indexes.ToArray());
IndexCreation.CreateIndexes(new CompositionContainer(typeCatalog), store);
}
}
} | using System.ComponentModel.Composition.Hosting;
using Raven.Client;
using Raven.Client.Indexes;
namespace Snittlistan.Infrastructure.Indexes
{
public static class IndexCreator
{
public static void CreateIndexes(IDocumentStore store)
{
var typeCatalog = new TypeCatalog(typeof(Matches_PlayerStats), typeof(Match_ByDate));
IndexCreation.CreateIndexes(new CompositionContainer(typeCatalog), store);
}
}
} | mit | C# |
503878bcb23d6dc7479d44416cb15f096685e1eb | move RenderContextForTest out of BuiltinPrimitiveRendererFacts | zwcloud/ImGui,zwcloud/ImGui,zwcloud/ImGui | test/ImGui.UnitTest/GraphicsImplementation/Builtin/RenderContextForTest.cs | test/ImGui.UnitTest/GraphicsImplementation/Builtin/RenderContextForTest.cs | using ImGui.Common.Primitive;
using ImGui.OSImplentation.Windows;
using System;
namespace ImGui.UnitTest
{
internal class RenderContextForTest : IDisposable
{
//TODO de-cuple with Windows platform
public Win32Window Window { get; private set; }
public Win32OpenGLRenderer Renderer { get; private set; }
public RenderContextForTest(Size size)
{
Application.Init();
this.Window = new Win32Window();
this.Window.Init(Point.Zero, size, WindowTypes.Regular);
this.Renderer = new Win32OpenGLRenderer();
this.Renderer.Init(this.Window.Pointer, this.Window.ClientSize);
}
public void Clear()
{
this.Renderer.Clear(Color.FrameBg);
}
public void DrawShapeMesh(Mesh shapeMesh)
{
Win32OpenGLRenderer.DrawMesh(this.Renderer.shapeMaterial, shapeMesh,
(int)this.Window.ClientSize.Width, (int)this.Window.ClientSize.Height);
}
public void DrawImageMesh(Mesh imageMesh)
{
Win32OpenGLRenderer.DrawMesh(this.Renderer.imageMaterial, imageMesh,
(int)this.Window.ClientSize.Width, (int)this.Window.ClientSize.Height);
}
public void DrawTextMesh(TextMesh textMesh)
{
Win32OpenGLRenderer.DrawTextMesh(this.Renderer.glyphMaterial, textMesh,
(int)this.Window.ClientSize.Width, (int)this.Window.ClientSize.Height);
}
public void Dispose()
{
this.Renderer.ShutDown();
this.Window.Close();
}
}
} | using System;
using ImGui.Common.Primitive;
using ImGui.OSImplentation.Windows;
namespace ImGui.UnitTest.Rendering
{
public partial class BuiltinPrimitiveRendererFacts
{
internal class RenderContextForTest : IDisposable
{
//TODO de-cuple with Windows platform
public Win32Window Window { get; private set; }
public Win32OpenGLRenderer Renderer { get; private set; }
public RenderContextForTest(Size size)
{
Application.Init();
this.Window = new Win32Window();
this.Window.Init(Point.Zero, size, WindowTypes.Regular);
this.Renderer = new Win32OpenGLRenderer();
this.Renderer.Init(this.Window.Pointer, this.Window.ClientSize);
}
public void Clear()
{
this.Renderer.Clear(Color.FrameBg);
}
public void DrawShapeMesh(Mesh shapeMesh)
{
Win32OpenGLRenderer.DrawMesh(this.Renderer.shapeMaterial, shapeMesh,
(int)this.Window.ClientSize.Width, (int)this.Window.ClientSize.Height);
}
public void DrawImageMesh(Mesh imageMesh)
{
Win32OpenGLRenderer.DrawMesh(this.Renderer.imageMaterial, imageMesh,
(int)this.Window.ClientSize.Width, (int)this.Window.ClientSize.Height);
}
public void DrawTextMesh(TextMesh textMesh)
{
Win32OpenGLRenderer.DrawTextMesh(this.Renderer.glyphMaterial, textMesh,
(int)this.Window.ClientSize.Width, (int)this.Window.ClientSize.Height);
}
public void Dispose()
{
this.Renderer.ShutDown();
this.Window.Close();
}
}
}
} | agpl-3.0 | C# |
418df5fe8e6562cb549735253f6b69aa4ea3702f | Add explanatory text comment for person-prisoner example | pavlosmcg/solid | LSP/Person/Program.cs | LSP/Person/Program.cs | namespace PersonPrisoner
{
class Program
{
static void Main(string[] args)
{
Person person = new Prisoner();
person.WalkEast(5);
}
}
#region Explanation
// At a first glance, it would be pretty obvious to make the prisoner derive from person class.
// Just as obviously, this leads us into trouble, since a prisoner is not free to move an arbitrary distance
// in any direction, yet the contract of the Person class states that a Person can.
//So, in fact, the class Person could better be named FreePerson. If that were the case, then the idea that
//class Prisoner extends FreePerson is clearly wrong.
//By analogy, then, a Square is not an Rectangle, because it lacks the same degrees of freedom as an Rectangle.
//This strongly suggests that inheritance should never be used when the sub-class restricts the freedom
//implicit in the base class. It should only be used when the sub-class adds extra detail to the concept
//represented by the base class, for example, 'Monkey' is-an 'Animal'.
#endregion
}
| namespace PersonPrisoner
{
class Program
{
static void Main(string[] args)
{
Person person = new Prisoner();
person.WalkEast(5);
}
}
}
| mit | C# |
e6377c171c5f0af56b42e1ed277959d7303e47ee | Simplify init to work around editor hot-reload | googlevr/tilt-brush-toolkit,googlevr/tilt-brush-toolkit | UnitySDK/Assets/TiltBrush/Scripts/BrushManifest.cs | UnitySDK/Assets/TiltBrush/Scripts/BrushManifest.cs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace TiltBrushToolkit {
public class BrushManifest : ScriptableObject {
// static API
private static BrushManifest sm_Instance;
public static BrushManifest Instance {
get {
// How can we get a reference to the singleton AllBrushes.asset?
// LoadAssetAtPath<>() is fragile, because it bakes in a file path.
// Instead, (ab)use the ability for scripts to have default values
// (which are stored in the .meta)
if (sm_Instance == null) {
var dummy = CreateInstance<BrushManifest>();
sm_Instance = dummy.m_DefaultManifest;
DestroyImmediate(dummy);
}
Debug.Assert(sm_Instance != null, "Misconfigured singleton");
return sm_Instance;
}
}
// instance API
// See Instance.get for an explanation of this
[HideInInspector]
[SerializeField]
private BrushManifest m_DefaultManifest;
[SerializeField] private BrushDescriptor[] m_Brushes;
private Dictionary<Guid, BrushDescriptor> m_ByGuid;
private ILookup<string, BrushDescriptor> m_ByName;
public IEnumerable<BrushDescriptor> AllBrushes {
get { return m_Brushes; }
}
public Dictionary<Guid, BrushDescriptor> BrushesByGuid {
get {
if (m_ByGuid == null) {
m_ByGuid = m_Brushes.ToDictionary(desc => (Guid)desc.m_Guid);
}
return m_ByGuid;
}
}
public ILookup<string, BrushDescriptor> BrushesByName {
get {
if (m_ByName == null) {
m_ByName = m_Brushes.ToLookup(desc => desc.m_DurableName);
}
return m_ByName;
}
}
/*
[MenuItem("Tilt Brush/Update Manifest")]
public static void MenuItem_UpdateManifest() {
BrushManifest manifest = Instance;
Undo.RecordObject(manifest, "Recreate brush list");
manifest.m_Brushes = AssetDatabase.FindAssets("t:BrushDescriptor")
.Select(g => AssetDatabase.GUIDToAssetPath(g))
.Select(p => AssetDatabase.LoadAssetAtPath<BrushDescriptor>(p))
.ToArray();
}
*/
}
}
| // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace TiltBrushToolkit {
public class BrushManifest : ScriptableObject {
// static API
private static BrushManifest sm_Instance;
public static BrushManifest Instance {
get {
// How can we get a reference to the singleton AllBrushes.asset?
// LoadAssetAtPath<>() is fragile, because it bakes in a file path.
// Instead, (ab)use the ability for scripts to have default values
// (which are stored in the .meta)
if (sm_Instance == null) {
var dummy = CreateInstance<BrushManifest>();
sm_Instance = dummy.m_DefaultManifest;
DestroyImmediate(dummy);
}
Debug.Assert(sm_Instance != null, "Misconfigured singleton");
return sm_Instance;
}
}
// instance API
// See Instance.get for an explanation of this
[HideInInspector]
[SerializeField]
private BrushManifest m_DefaultManifest;
[SerializeField] private BrushDescriptor[] m_Brushes;
private bool m_LookupInitialized;
private Dictionary<Guid, BrushDescriptor> m_ByGuid;
private ILookup<string, BrushDescriptor> m_ByName;
public IEnumerable<BrushDescriptor> AllBrushes {
get { return m_Brushes; }
}
public Dictionary<Guid, BrushDescriptor> BrushesByGuid {
get { InitLookup(); return m_ByGuid; }
}
public ILookup<string, BrushDescriptor> BrushesByName {
get { InitLookup(); return m_ByName; }
}
private void InitLookup() {
if (m_LookupInitialized) { return; }
m_LookupInitialized = true;
m_ByGuid = m_Brushes.ToDictionary(desc => (Guid)desc.m_Guid);
m_ByName = m_Brushes.ToLookup(desc => desc.m_DurableName);
}
/*
[MenuItem("Tilt Brush/Update Manifest")]
public static void MenuItem_UpdateManifest() {
BrushManifest manifest = Instance;
Undo.RecordObject(manifest, "Recreate brush list");
manifest.m_Brushes = AssetDatabase.FindAssets("t:BrushDescriptor")
.Select(g => AssetDatabase.GUIDToAssetPath(g))
.Select(p => AssetDatabase.LoadAssetAtPath<BrushDescriptor>(p))
.ToArray();
}
*/
}
}
| apache-2.0 | C# |
3b990400626c654bab14f42326cb2c4d55a37782 | upgrade version | tynor88/Topshelf.SimpleInjector | Source/AssemblyVersion.cs | Source/AssemblyVersion.cs | using System.Reflection;
[assembly: AssemblyVersion("0.1.4.0")]
[assembly: AssemblyFileVersion("0.1.4.0")] | using System.Reflection;
[assembly: AssemblyVersion("0.1.3.2")]
[assembly: AssemblyFileVersion("0.1.3.2")] | mit | C# |
1972ca6633812c3bceb4c491e598f33cea648fde | Update version number for new nuget release. | SAEnergy/Infrastructure,SAEnergy/Infrastructure | Src/GlobalAssemblyInfo.cs | Src/GlobalAssemblyInfo.cs | using System.Reflection;
// 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: AssemblyCompany("Simple Answers Energy, Inc.")]
[assembly: AssemblyProduct("Infrastructure")]
[assembly: AssemblyCopyright("Copyright (c) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
| using System.Reflection;
// 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: AssemblyCompany("Simple Answers Energy, Inc.")]
[assembly: AssemblyProduct("Infrastructure")]
[assembly: AssemblyCopyright("Copyright (c) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.5.0")]
[assembly: AssemblyFileVersion("0.1.5.0")]
| mit | C# |
6981498aea28b8adc62ef2867c2441b222ed9040 | Update assembly info | SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk | SnapMD.ConnectedCare.Sdk/Properties/AssemblyInfo.cs | SnapMD.ConnectedCare.Sdk/Properties/AssemblyInfo.cs | // Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Reflection;
using System.Runtime.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("SnapMD.ConnectedCare.Sdk")]
[assembly: AssemblyDescription("Open-source wrapper for the REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SnapMD")]
[assembly: AssemblyProduct("Connected Care")]
[assembly: AssemblyCopyright("Copyright © 2015 SnapMD, Inc.")]
[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("fc089857-9e43-41eb-b5e3-e397174f7f00")]
// 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.11.*")]
[assembly: AssemblyFileVersion("1.0.0.0")] | // Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Reflection;
using System.Runtime.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("SnapMD.ConnectedCare.Sdk")]
[assembly: AssemblyDescription("Open-source wrapper for the REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SnapMD")]
[assembly: AssemblyProduct("Connected Care")]
[assembly: AssemblyCopyright("Copyright © 2015 SnapMD, Inc.")]
[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("fc089857-9e43-41eb-b5e3-e397174f7f00")]
// 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.10.5")]
[assembly: AssemblyFileVersion("1.0.0.0")] | apache-2.0 | C# |
6fc60956660a2186ab6432bcccbce2a4eca851b1 | Optimize SetUp method initialization style | SICU-Stress-Measurement-System/frontend-cs | StressMeasurementSystem.Tests/Models/ContactTest.cs | StressMeasurementSystem.Tests/Models/ContactTest.cs | using NUnit.Framework;
using StressMeasurementSystem.Models;
using System.Collections.Generic;
namespace StressMeasurementSystem.Tests.Models
{
[TestFixture]
public class ContactTest
{
#region Fields
private Contact _contact;
private Contact.NameInfo _name;
private Contact.OrganizationInfo _organization;
private List<Contact.PhoneInfo> _phoneNumbers;
private List<Contact.EmailInfo> _emailAddresses;
#endregion
[SetUp]
public void SetUp()
{
_name = new Contact.NameInfo
{
First = "John",
Last = "Smith"
};
_organization = new Contact.OrganizationInfo
{
Company = "Smith Co.",
JobTitle = "CEO"
};
_phoneNumbers = new List<Contact.PhoneInfo>();
var phoneNumberWork = new Contact.PhoneInfo
{
Number = "(800) 123-4567",
T = Contact.PhoneInfo.Type.Work
};
_phoneNumbers.Add(phoneNumberWork);
var phoneNumberMobile = new Contact.PhoneInfo
{
Number = "(123) 456-7890",
T = Contact.PhoneInfo.Type.Mobile
};
_phoneNumbers.Add(phoneNumberMobile);
_emailAddresses = new List<Contact.EmailInfo>();
var emailAddressWork =
new Contact.EmailInfo
{
Address = new System.Net.Mail.MailAddress("jsmith@smith.com"),
T = Contact.EmailInfo.Type.Work
};
_emailAddresses.Add(emailAddressWork);
_contact = new Contact(_name, _organization, _phoneNumbers, _emailAddresses);
}
[Test]
public void Test1()
{
Assert.True(true);
}
[TearDown]
public void TearDown()
{
//TODO: Implement
}
}
}
| using NUnit.Framework;
using StressMeasurementSystem.Models;
using System.Collections.Generic;
namespace StressMeasurementSystem.Tests.Models
{
[TestFixture]
public class ContactTest
{
#region Fields
private Contact _contact;
private Contact.NameInfo _name;
private Contact.OrganizationInfo _organization;
private List<Contact.PhoneInfo> _phoneNumbers;
private List<Contact.EmailInfo> _emailAddresses;
#endregion
[SetUp]
public void SetUp()
{
_name = new Contact.NameInfo();
_name.First = "John";
_name.Last = "Smith";
_organization = new Contact.OrganizationInfo();
_organization.Company = "Smith Co.";
_organization.JobTitle = "CEO";
_phoneNumbers = new List<Contact.PhoneInfo>();
Contact.PhoneInfo phoneNumberWork = new Contact.PhoneInfo();
phoneNumberWork.Number = "(800) 123-4567";
phoneNumberWork.T = Contact.PhoneInfo.Type.Work;
_phoneNumbers.Add(phoneNumberWork);
Contact.PhoneInfo phoneNumberMobile = new Contact.PhoneInfo();
phoneNumberMobile.Number = "(123) 456-7890";
phoneNumberMobile.T = Contact.PhoneInfo.Type.Mobile;
_phoneNumbers.Add(phoneNumberMobile);
_emailAddresses = new List<Contact.EmailInfo>();
Contact.EmailInfo emailAddressWork = new Contact.EmailInfo();
emailAddressWork.Address = new System.Net.Mail.MailAddress("jsmith@smith.com");
emailAddressWork.T = Contact.EmailInfo.Type.Work;
_emailAddresses.Add(emailAddressWork);
_contact = new Contact(_name, _organization, _phoneNumbers, _emailAddresses);
}
[Test]
public void Test1()
{
Assert.True(true);
}
[TearDown]
public void TearDown()
{
//TODO: Implement
}
}
}
| apache-2.0 | C# |
6ecd9265ab9e1a4f52da50a672a347f04b73eb7c | Update SingleDatabaseFixture.cs | unosquare/tenantcore | Unosquare.TenantCore.Tests/SingleDatabaseFixture.cs | Unosquare.TenantCore.Tests/SingleDatabaseFixture.cs | using Effort;
using Microsoft.Owin.Testing;
using NUnit.Framework;
using Owin;
using System.Collections.Generic;
using System.Linq;
using Unosquare.TenantCore.SampleDatabase;
namespace Unosquare.TenantCore.Tests
{
[TestFixture]
public class SingleDatabaseFixture
{
private ApplicationDbContext _context;
private TestServer _server;
private ITenantResolver _resolver;
[SetUp]
public void Setup()
{
Effort.Provider.EffortProviderConfiguration.RegisterProvider();
var connection = DbConnectionFactory.CreateTransient();
_context = new ApplicationDbContext(connection);
_context.GenerateRandomData();
_resolver = new HostNameTenantResolver(new List<ITenant>
{
new Tenant(1, "local", "localhost"),
new Tenant(2, "sample", "sample.local")
}, "TenantId");
_server = TestServer.Create(app =>
{
app.UseTenantCore(_resolver);
app.Run(context =>
{
var tenant = context.GetCurrentTenant();
return context.Response.WriteAsync(tenant.Name);
});
});
}
[Test]
public async Task GetTenant()
{
var response = await _server.HttpClient.GetAsync("/");
Assert.IsTrue(response.IsSuccessStatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.IsNotNull(content);
Assert.AreEqual(content, _resolver.GetTenants().First().Name);
}
}
}
| using Effort;
using Microsoft.Owin.Testing;
using NUnit.Framework;
using Owin;
using System.Collections.Generic;
using System.Linq;
using Unosquare.TenantCore.SampleDatabase;
namespace Unosquare.TenantCore.Tests
{
[TestFixture]
public class SingleDatabaseFixture
{
private ApplicationDbContext _context;
private TestServer _server;
private ITenantResolver _resolver;
[SetUp]
public void Setup()
{
Effort.Provider.EffortProviderConfiguration.RegisterProvider();
var connection = DbConnectionFactory.CreateTransient();
_context = new ApplicationDbContext(connection);
_context.GenerateRandomData();
_resolver = new HostNameTenantResolver(new List<ITenant>
{
new Tenant(1, "local", "localhost"),
new Tenant(2, "sample", "sample.local")
}, "TenantId");
_server = TestServer.Create(app =>
{
app.UseTenantCore(_resolver);
app.Run(context =>
{
var tenant = context.GetCurrentTenant();
return context.Response.WriteAsync(tenant.Name);
});
});
}
[Test]
public async void GetTenant()
{
var response = await _server.HttpClient.GetAsync("/");
Assert.IsTrue(response.IsSuccessStatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.IsNotNull(content);
Assert.AreEqual(content, _resolver.GetTenants().First().Name);
}
}
} | mit | C# |
8ec750115734f5571da7e3cb63d8906a72e41200 | Fix fade out interrupt | DMagic1/KSP_Contract_Window | Source/ContractsWindow.Unity/CanvasFader.cs | Source/ContractsWindow.Unity/CanvasFader.cs | #region license
/*The MIT License (MIT)
CanvasFader - Monobehaviour for making smooth fade in and fade out for UI windows
Copyright (c) 2016 DMagic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace ContractsWindow.Unity
{
[RequireComponent(typeof(CanvasGroup), typeof(RectTransform))]
public class CanvasFader : MonoBehaviour
{
[SerializeField]
private float SlowRate = 0.9f;
[SerializeField]
private float FastRate = 0.3f;
private CanvasGroup canvas;
private IEnumerator fader;
private bool allowInterrupt = true;
protected virtual void Awake()
{
canvas = GetComponent<CanvasGroup>();
}
public bool Fading
{
get { return fader != null; }
}
protected void Fade(float to, bool fast, Action call = null, bool interrupt = true)
{
if (canvas == null)
return;
Fade(canvas.alpha, to, fast ? FastRate : SlowRate, call, interrupt);
}
protected void Alpha(float to)
{
if (canvas == null)
return;
to = Mathf.Clamp01(to);
canvas.alpha = to;
}
private void Fade(float from, float to, float duration, Action call, bool interrupt)
{
if (!allowInterrupt)
return;
if (fader != null)
StopCoroutine(fader);
fader = FadeRoutine(from, to, duration, call, interrupt);
StartCoroutine(fader);
}
private IEnumerator FadeRoutine(float from, float to, float duration, Action call, bool interrupt)
{
allowInterrupt = interrupt;
yield return new WaitForEndOfFrame();
float f = 0;
while (f <= 1)
{
f += Time.deltaTime / duration;
Alpha(Mathf.Lerp(from, to, f));
yield return null;
}
if (call != null)
call.Invoke();
allowInterrupt = true;
fader = null;
}
}
}
| #region license
/*The MIT License (MIT)
CanvasFader - Monobehaviour for making smooth fade in and fade out for UI windows
Copyright (c) 2016 DMagic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace ContractsWindow.Unity
{
[RequireComponent(typeof(CanvasGroup), typeof(RectTransform))]
public class CanvasFader : MonoBehaviour
{
[SerializeField]
private float SlowRate = 0.9f;
[SerializeField]
private float FastRate = 0.3f;
private CanvasGroup canvas;
private IEnumerator fader;
protected virtual void Awake()
{
canvas = GetComponent<CanvasGroup>();
}
public bool Fading
{
get { return fader != null; }
}
protected void Fade(float to, bool fast, Action call = null, bool interrupt = true)
{
if (canvas == null)
return;
Fade(canvas.alpha, to, fast ? FastRate : SlowRate, call, interrupt);
}
protected void Alpha(float to)
{
if (canvas == null)
return;
to = Mathf.Clamp01(to);
canvas.alpha = to;
}
private void Fade(float from, float to, float duration, Action call, bool interrupt)
{
if (fader != null && interrupt)
StopCoroutine(fader);
fader = FadeRoutine(from, to, duration, call);
StartCoroutine(fader);
}
private IEnumerator FadeRoutine(float from, float to, float duration, Action call)
{
yield return new WaitForEndOfFrame();
float f = 0;
while (f <= 1)
{
f += Time.deltaTime / duration;
Alpha(Mathf.Lerp(from, to, f));
yield return null;
}
if (call != null)
call.Invoke();
fader = null;
}
}
}
| mit | C# |
5d4e49021869038422183e908192afc5021bbafd | Add logic to validate when function has zero expected parameters | bijington/expressive | Source/Expressive/Functions/FunctionBase.cs | Source/Expressive/Functions/FunctionBase.cs | using Expressive.Exceptions;
using Expressive.Expressions;
using System.Collections.Generic;
using System.Linq;
namespace Expressive.Functions
{
public abstract class FunctionBase : IFunction
{
#region IFunction Members
/// <inheritdoc />
#pragma warning disable CA2227 // Collection properties should be read only - it is likely this can be passed in to Evaluate but it will need to be done carefully (e.g. mark this setter as obsolete first).
public IDictionary<string, object> Variables { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
/// <inheritdoc />
public abstract string Name { get; }
/// <inheritdoc />
public abstract object Evaluate(IExpression[] parameters, Context context);
#endregion
/// <summary>
/// Validates whether the expected number of parameters are present.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="expectedCount">The expected number of parameters, use -1 for an unknown number.</param>
/// <param name="minimumCount">The minimum number of parameters.</param>
/// <returns>True if the correct number are present, false otherwise.</returns>
protected bool ValidateParameterCount(IExpression[] parameters, int expectedCount, int minimumCount)
{
if (expectedCount == 0 && (parameters.Any() || parameters.Length != expectedCount))
{
throw new ParameterCountMismatchException($"{this.Name}() does not take any arguments");
}
if (expectedCount != -1 && expectedCount != 0 && (parameters is null || !parameters.Any() || parameters.Length != expectedCount))
{
throw new ParameterCountMismatchException($"{this.Name}() takes only {expectedCount} argument(s)");
}
if (minimumCount > 0 && (parameters is null || !parameters.Any() || parameters.Length < minimumCount))
{
throw new ParameterCountMismatchException($"{this.Name}() expects at least {minimumCount} argument(s)");
}
return true;
}
}
}
| using Expressive.Exceptions;
using Expressive.Expressions;
using System.Collections.Generic;
using System.Linq;
namespace Expressive.Functions
{
public abstract class FunctionBase : IFunction
{
#region IFunction Members
/// <inheritdoc />
#pragma warning disable CA2227 // Collection properties should be read only - it is likely this can be passed in to Evaluate but it will need to be done carefully (e.g. mark this setter as obsolete first).
public IDictionary<string, object> Variables { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
/// <inheritdoc />
public abstract string Name { get; }
/// <inheritdoc />
public abstract object Evaluate(IExpression[] parameters, Context context);
#endregion
/// <summary>
/// Validates whether the expected number of parameters are present.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="expectedCount">The expected number of parameters, use -1 for an unknown number.</param>
/// <param name="minimumCount">The minimum number of parameters.</param>
/// <returns>True if the correct number are present, false otherwise.</returns>
protected bool ValidateParameterCount(IExpression[] parameters, int expectedCount, int minimumCount)
{
if (expectedCount != -1 && (parameters is null || !parameters.Any() || parameters.Length != expectedCount))
{
throw new ParameterCountMismatchException($"{this.Name}() takes only {expectedCount} argument(s)");
}
if (minimumCount > 0 && (parameters is null || !parameters.Any() || parameters.Length < minimumCount))
{
throw new ParameterCountMismatchException($"{this.Name}() expects at least {minimumCount} argument(s)");
}
return true;
}
}
}
| mit | C# |
75435030410ad665c227f3fb109c8da4d241a157 | Update UserViewModel.cs | xcjs/ASP.NET-WebForm-MVVM-Demo | MVVMDemo/ViewModels/Account/UserViewModel.cs | MVVMDemo/ViewModels/Account/UserViewModel.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using MVVMDemo.Entities;
using MVVMDemo.ViewModels;
namespace MVVMDemo.ViewModels.Account
{
public class UserViewModel : ViewModelBase<UserViewModel>
{
private User _user;
public User User
{
get
{
return _user;
}
set
{
_user = value;
NotifyPropertyChanged("User");
}
}
public UserViewModel() { }
public bool SaveUser(User updatedUser)
{
bool saved = false;
User = new User();
User.ID = updatedUser.ID;
User.FirstName = updatedUser.FirstName.Trim();
User.LastName = updatedUser.LastName.Trim();
User.Address = updatedUser.Address.Trim();
User.Address2 = updatedUser.Address2.Trim();
User.City = updatedUser.City.Trim();
User.State = updatedUser.State.Trim();
User.Zip = updatedUser.Zip.Trim();
try
{
using (var db = new UsersEntities())
{
User existingUser = db.Users.FirstOrDefault(u => u.ID == User.ID);
if (existingUser != null)
{
existingUser.FirstName = User.FirstName;
existingUser.LastName = User.LastName;
existingUser.Address = User.Address;
existingUser.Address2 = User.Address2;
existingUser.City = User.City;
existingUser.State = User.State;
existingUser.Zip = User.Zip;
}
else
{
db.Users.AddObject(User);
}
if (db.SaveChanges() > 0)
{
saved = true;
}
}
}
catch (Exception ex)
{
Debug.WriteLine("AN exception occurred while saving User changes: " + ex.Message);
}
return saved;
}
public static UserViewModel CreateInstance()
{
UserViewModel m = new UserViewModel();
m.User = User.CreateInstance();
return m;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using MVVMDemo.Entities;
using MVVMDemo.ViewModels;
namespace MVVMDemo.ViewModels.Account
{
public class UserViewModel : ViewModelBase<UserViewModel>
{
private User _user;
public User User
{
get
{
return _user;
}
set
{
_user = value;
NotifyPropertyChanged("User");
}
}
public UserViewModel() { }
public bool SaveUser(User updatedUser)
{
bool saved = false;
User = new User();
User.ID = updatedUser.ID;
User.FirstName = updatedUser.FirstName.Trim();
User.LastName = updatedUser.LastName.Trim();
User.Address = updatedUser.Address.Trim();
User.Address2 = updatedUser.Address2.Trim();
User.City = updatedUser.Address2.Trim();
User.State = updatedUser.State.Trim();
User.Zip = updatedUser.Zip.Trim();
try
{
using (var db = new UsersEntities())
{
User existingUser = db.Users.FirstOrDefault(u => u.ID == User.ID);
if (existingUser != null)
{
existingUser.FirstName = User.FirstName;
existingUser.LastName = User.LastName;
existingUser.Address = User.Address;
existingUser.Address2 = User.Address2;
existingUser.City = User.City;
existingUser.State = User.State;
existingUser.Zip = User.Zip;
}
else
{
db.Users.AddObject(User);
}
if (db.SaveChanges() > 0)
{
saved = true;
}
}
}
catch (Exception ex)
{
Debug.WriteLine("AN exception occurred while saving User changes: " + ex.Message);
}
return saved;
}
public static UserViewModel CreateInstance()
{
UserViewModel m = new UserViewModel();
m.User = User.CreateInstance();
return m;
}
}
} | mit | C# |
211b29538384ca2f741a739e82eff04bdccef9dd | Remove redundant controller specification. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | MitternachtWeb/Controllers/HomeController.cs | MitternachtWeb/Controllers/HomeController.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace MitternachtWeb.Controllers {
public class HomeController : DiscordUserController {
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) {
_logger = logger;
}
public IActionResult Index() {
return View();
}
[Authorize]
public IActionResult Login() {
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Logout() {
await HttpContext.SignOutAsync("Cookies");
return RedirectToAction(nameof(Index));
}
}
}
| using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace MitternachtWeb.Controllers {
public class HomeController : DiscordUserController {
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) {
_logger = logger;
}
public IActionResult Index() {
return View();
}
[Authorize]
public IActionResult Login() {
return RedirectToAction(nameof(Index), "Home");
}
public async Task<IActionResult> Logout() {
await HttpContext.SignOutAsync("Cookies");
return RedirectToAction(nameof(Index), "Home");
}
}
}
| mit | C# |
d8e64cb8aee5a1a4965a112e6bf1956a83cbc407 | Add the 'Schedule' value to the 'LogType' enum | Jericho/CakeMail.RestClient | Source/CakeMail.RestClient/Models/LogType.cs | Source/CakeMail.RestClient/Models/LogType.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
namespace CakeMail.RestClient.Models
{
/// <summary>
/// Enumeration to indicate the type of log.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum LogType
{
/// <summary>
/// Subscribe
/// </summary>
[EnumMember(Value = "subscribe")]
Subscribe,
/// <summary>
/// Sent
/// </summary>
[EnumMember(Value = "in_queue")]
Sent,
/// <summary>
/// Open
/// </summary>
[EnumMember(Value = "opened")]
Open,
/// <summary>
/// Opened forward
/// </summary>
[EnumMember(Value = "opened_forward")]
OpenForward,
/// <summary>
/// Click
/// </summary>
[EnumMember(Value = "clickthru")]
Click,
/// <summary>
/// Forward
/// </summary>
[EnumMember(Value = "forward")]
Forward,
/// <summary>
/// Unsubscribe
/// </summary>
[EnumMember(Value = "unsubscribe")]
Unsubscribe,
/// <summary>
/// View
/// </summary>
[EnumMember(Value = "view")]
View,
/// <summary>
/// Spam
/// </summary>
[EnumMember(Value = "spam")]
Spam,
/// <summary>
/// Skipped
/// </summary>
[EnumMember(Value = "skipped")]
Skipped,
/// <summary>
/// Implied open
/// </summary>
[EnumMember(Value = "implied_open")]
ImpliedOpen,
/// <summary>
/// Soft bounce
/// </summary>
[EnumMember(Value = "bounce_sb")]
SoftBounce,
/// <summary>
/// Address change
/// </summary>
[EnumMember(Value = "bounce_ac")]
AddressChange,
/// <summary>
/// Automatic reply
/// </summary>
[EnumMember(Value = "bounce_ar")]
AutoReply,
/// <summary>
/// Challenge response
/// </summary>
[EnumMember(Value = "bounce_cr")]
ChallengeResponse,
/// <summary>
/// Mail block
/// </summary>
[EnumMember(Value = "bounce_mb")]
MailBlock,
/// <summary>
/// Full mailbox
/// </summary>
[EnumMember(Value = "bounce_fm")]
FullMailbox,
/// <summary>
/// Transient bounce
/// </summary>
[EnumMember(Value = "bounce_tr")]
TransientBounce,
/// <summary>
/// Hard bounce
/// </summary>
[EnumMember(Value = "bounce_hb")]
HardBounce,
/// <summary>
/// DNS failure
/// </summary>
[EnumMember(Value = "bounce_df")]
DnsFailure,
/// <summary>
/// Received
/// </summary>
[EnumMember(Value = "received")]
Received,
/// <summary>
/// Schedule
/// </summary>
[EnumMember(Value = "schedule")]
Schedule
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
namespace CakeMail.RestClient.Models
{
/// <summary>
/// Enumeration to indicate the type of log.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum LogType
{
/// <summary>
/// Subscribe
/// </summary>
[EnumMember(Value = "subscribe")]
Subscribe,
/// <summary>
/// Sent
/// </summary>
[EnumMember(Value = "in_queue")]
Sent,
/// <summary>
/// Open
/// </summary>
[EnumMember(Value = "opened")]
Open,
/// <summary>
/// Opened forward
/// </summary>
[EnumMember(Value = "opened_forward")]
OpenForward,
/// <summary>
/// Click
/// </summary>
[EnumMember(Value = "clickthru")]
Click,
/// <summary>
/// Forward
/// </summary>
[EnumMember(Value = "forward")]
Forward,
/// <summary>
/// Unsubscribe
/// </summary>
[EnumMember(Value = "unsubscribe")]
Unsubscribe,
/// <summary>
/// View
/// </summary>
[EnumMember(Value = "view")]
View,
/// <summary>
/// Spam
/// </summary>
[EnumMember(Value = "spam")]
Spam,
/// <summary>
/// Skipped
/// </summary>
[EnumMember(Value = "skipped")]
Skipped,
/// <summary>
/// Implied open
/// </summary>
[EnumMember(Value = "implied_open")]
ImpliedOpen,
/// <summary>
/// Soft bounce
/// </summary>
[EnumMember(Value = "bounce_sb")]
SoftBounce,
/// <summary>
/// Address change
/// </summary>
[EnumMember(Value = "bounce_ac")]
AddressChange,
/// <summary>
/// Automatic reply
/// </summary>
[EnumMember(Value = "bounce_ar")]
AutoReply,
/// <summary>
/// Challenge response
/// </summary>
[EnumMember(Value = "bounce_cr")]
ChallengeResponse,
/// <summary>
/// Mail block
/// </summary>
[EnumMember(Value = "bounce_mb")]
MailBlock,
/// <summary>
/// Full mailbox
/// </summary>
[EnumMember(Value = "bounce_fm")]
FullMailbox,
/// <summary>
/// Transient bounce
/// </summary>
[EnumMember(Value = "bounce_tr")]
TransientBounce,
/// <summary>
/// Hard bounce
/// </summary>
[EnumMember(Value = "bounce_hb")]
HardBounce,
/// <summary>
/// DNS failure
/// </summary>
[EnumMember(Value = "bounce_df")]
DnsFailure,
/// <summary>
/// Received
/// </summary>
[EnumMember(Value = "received")]
Received
}
}
| mit | C# |
9ac934ad51efd8bb54831fabec657ccf0bc7fe0e | Remove `in` from IGame and change method signatures | TalkTakesTime/csharpgamesuite | GameSuite.Games/IGame.cs | GameSuite.Games/IGame.cs | using System.Collections.Generic;
namespace GameSuite.Games
{
public interface IGame<G, M>
where G : IGame<G, M>
where M : IMove<G>
{
bool CanPlay(M move);
bool Play(M move);
void Undo();
List<M> GenerateMoves();
G GenerateChild(M move);
/// <summary>
/// Evaluates the current game state, giving a positive score if the
/// state is better for player 1, and a negative score if the state
/// is better for player 2.
/// </summary>
/// <returns>
/// A score, >0 if the state benefits player 1, <0 if it benefits
/// player 2, and 0 if neither player has an advantage.
/// </returns>
int Evaluate();
}
}
| using System.Collections.Generic;
namespace GameSuite.Games
{
// this may be a misuse of contravariance
public interface IGame<G, in M>
where G : IGame<G, M>
where M : IMove<G>
{
bool CanPlay(M move);
bool Play(M move);
bool Undo();
G GenerateMoves();
G GenerateChild();
/// <summary>
/// Evaluates the current game state, giving a positive score if the
/// state is better for player 1, and a negative score if the state
/// is better for player 2.
/// </summary>
/// <returns>
/// A score, >0 if the state benefits player 1, <0 if it benefits
/// player 2, and 0 if neither player has an advantage.
/// </returns>
int Evaluate();
}
}
| mit | C# |
a2702ce37fd9d36fb86f56c3c7b645dac50da5e9 | Update AboutWindow.xaml.cs | Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D.UI/Views/AboutWindow.xaml.cs | src/Core2D.UI/Views/AboutWindow.xaml.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Core2D.UI.Views
{
/// <summary>
/// Interaction logic for <see cref="AboutWindow"/> xaml.
/// </summary>
public class AboutWindow : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="AboutWindow"/> class.
/// </summary>
public AboutWindow()
{
InitializeComponent();
this.AttachDevTools();
App.Selector.EnableThemes(this);
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Core2D.UI.Views
{
/// <summary>
/// Interaction logic for <see cref="AboutWindow"/> xaml.
/// </summary>
public class AboutWindow : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="AboutWindow"/> class.
/// </summary>
public AboutWindow()
{
InitializeComponent();
this.AttachDevTools();
}
/// <summary>
/// Initialize the Xaml components.
/// </summary>
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
App.Selector.EnableThemes(this);
}
}
}
| mit | C# |
3455f650cd3283f0d024ceee6f6adf3dcc0ea855 | Copy change completed to Error403 page. (#153) | SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice | src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Error/_Error403.cshtml | src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Error/_Error403.cshtml | @{
ViewBag.Title = "Access denied - Error 403";
ViewBag.PageId = "error-403";
}
<main id="content" role="main" class="error-403">
<div class="grid-row">
<div class="column-two-thirds">
<div class="hgroup">
<h1 class="heading-xlarge">
Access denied
</h1>
</div>
<div class="inner">
<p>
You don’t have permission to access the Apprenticeship Service.
</p>
<p>
If you want to access the service, you’ll need to contact your organisation’s Information Management Services system (Idams) super user.
</p>
<h2 class="heading-medium">Help</h2>
<p>
You can contact the Apprenticeship Service for advice or help on how to use the service.
</p>
<h3 class="heading-small">Apprenticeship Service</h3>
<p>
Telephone: 0800 015 0600 <a href="https://www.gov.uk/call-charges" target="_blank">Find out about call charges</a>
</p>
</div>
</div>
</div>
</main> | @{
ViewBag.Title = "Access denied - Error 403";
ViewBag.PageId = "error-403";
}
<main id="content" role="main" class="error-403">
<div class="grid-row">
<div class="column-two-thirds">
<div class="hgroup">
<h1 class="heading-xlarge">
Your account does not have sufficient privileges
</h1>
</div>
<div class="inner">
<p>
If you are experiencing difficulty accessing the area of the site you need, first contact an/the account owner to ensure you have the correct role assigned to your account.
</p>
<p>
You can return to the
<a href="/">start page</a>
to try again.
</p>
</div>
</div>
</div>
</main> | mit | C# |
698541057dd23f9ba5ff6c69a75209c011f4f1fd | Access operator for array is now "item" | hahoyer/reni.cs,hahoyer/reni.cs,hahoyer/reni.cs | src/reni2/FeatureTest/Text.cs | src/reni2/FeatureTest/Text.cs | using System.Collections.Generic;
using System.Linq;
using System;
using hw.Parser;
using hw.UnitTest;
using Reni.FeatureTest.Array;
using Reni.FeatureTest.BitArrayOp;
namespace Reni.FeatureTest.Text
{
[TestFixture]
[TargetSet(@"'Hallo' dump_print", "Hallo")]
public sealed class Hallo : CompilerTest
{}
[TestFixture]
[TargetSet(@"
x: 'Hallo';
x item(0) dump_print;
x item(1) dump_print;
x item(2) dump_print;
x item(3) dump_print;
x item(4) dump_print;
", "Hallo")]
[Hallo]
[ElementAccessVariable]
[ArrayVariable]
public sealed class Hallo01234 : CompilerTest
{}
[TestFixture]
[TargetSet("'Hal''lo' dump_print", "Hal'lo")]
[Hallo]
public sealed class HalloApo : CompilerTest
{}
[TestFixture]
[TargetSet("\"Hal''lo\" dump_print", "Hal''lo")]
[HalloApo]
public sealed class HalloApoApo : CompilerTest
{}
[TestFixture]
[TargetSet("\"Hal'\"\"'lo\" dump_print", "Hal'\"'lo")]
[HalloApoApo]
public sealed class HalloApoQuoApo : CompilerTest
{}
[TestFixture]
[TargetSet("('Hallo' << ' Welt!') dump_print", "Hallo Welt!")]
[Hallo]
[CombineArraysFromPieces]
public sealed class HalloWelt : CompilerTest
{}
[TestFixture]
[Hallo]
[TargetSet("108 text_item dump_print", "l")]
public sealed class ConvertFromNumber : CompilerTest
{}
[TestFixture]
[ConvertFromNumber]
//[CompilerParameters.Trace.Parser]
[TargetSet("(<< (108)text_item<< (109)text_item)text_item dump_print", "lm")]
[ArrayFromPieces]
[Hallo]
public sealed class ConvertFromNumbers : CompilerTest
{}
[TestFixture]
[Hallo]
[Number]
[ConvertFromNumber]
[ConversionService.Closure]
[TargetSet("('80' to_number_of_base 16) dump_print", "128")]
public sealed class ConvertHexadecimal : CompilerTest
{}
} | using System.Collections.Generic;
using System.Linq;
using System;
using hw.Parser;
using hw.UnitTest;
using Reni.FeatureTest.Array;
using Reni.FeatureTest.BitArrayOp;
namespace Reni.FeatureTest.Text
{
[TestFixture]
[TargetSet(@"'Hallo' dump_print", "Hallo")]
public sealed class Hallo : CompilerTest
{}
[TestFixture]
[TargetSet(@"
x: 'Hallo';
(x>>0) dump_print;
(x>>1) dump_print;
(x>>2) dump_print;
(x>>3) dump_print;
(x>>4) dump_print;
", "Hallo")]
[Hallo]
[ElementAccessVariable]
[ArrayVariable]
public sealed class Hallo01234 : CompilerTest
{}
[TestFixture]
[TargetSet("'Hal''lo' dump_print", "Hal'lo")]
[Hallo]
public sealed class HalloApo : CompilerTest
{}
[TestFixture]
[TargetSet("\"Hal''lo\" dump_print", "Hal''lo")]
[HalloApo]
public sealed class HalloApoApo : CompilerTest
{}
[TestFixture]
[TargetSet("\"Hal'\"\"'lo\" dump_print", "Hal'\"'lo")]
[HalloApoApo]
public sealed class HalloApoQuoApo : CompilerTest
{}
[TestFixture]
[TargetSet("('Hallo' << ' Welt!') dump_print", "Hallo Welt!")]
[Hallo]
[CombineArraysFromPieces]
public sealed class HalloWelt : CompilerTest
{}
[TestFixture]
[Hallo]
[TargetSet("108 text_item dump_print", "l")]
public sealed class ConvertFromNumber : CompilerTest
{}
[TestFixture]
[ConvertFromNumber]
//[CompilerParameters.Trace.Parser]
[TargetSet("(<< (108)text_item<< (109)text_item)text_item dump_print", "lm")]
[ArrayFromPieces]
[Hallo]
public sealed class ConvertFromNumbers : CompilerTest
{}
[TestFixture]
[Hallo]
[Number]
[ConvertFromNumber]
[ConversionService.Closure]
[TargetSet("('80' to_number_of_base 16) dump_print", "128")]
public sealed class ConvertHexadecimal : CompilerTest
{}
} | mit | C# |
6c9470ae0a9a24437e5c5e6cbd9af016741c9c62 | Add missing obsolete method for sprite pools. | Damnae/storybrew | common/Storyboarding/Util/OsbSpritePools.cs | common/Storyboarding/Util/OsbSpritePools.cs | using System;
using System.Collections.Generic;
namespace StorybrewCommon.Storyboarding.Util
{
public class OsbSpritePools
{
private Dictionary<string, OsbSpritePool> pools = new Dictionary<string, OsbSpritePool>();
private StoryboardLayer layer;
public OsbSpritePools(StoryboardLayer layer)
{
this.layer = layer;
}
public void Clear()
{
foreach (var pool in pools)
pool.Value.Clear();
pools.Clear();
}
[Obsolete("OsbLayer comes from the storyboard layer and is ignored by this method")]
public OsbSprite Get(double startTime, double endTime, string path, OsbLayer layer, OsbOrigin origin = OsbOrigin.Centre, bool additive = false, int poolGroup = 0)
=> Get(startTime, endTime, path, origin, additive, poolGroup);
public OsbSprite Get(double startTime, double endTime, string path, OsbOrigin origin = OsbOrigin.Centre, bool additive = false, int poolGroup = 0)
=> getPool(path, origin, additive, poolGroup).Get(startTime, endTime);
public void Release(OsbSprite sprite, double endTime)
=> getPool(sprite.TexturePath, sprite.Origin, false, 0).Release(sprite, endTime);
private OsbSpritePool getPool(string path, OsbOrigin origin, bool additive, int poolGroup)
{
string key = getKey(path, origin, additive, poolGroup);
OsbSpritePool pool;
if (!pools.TryGetValue(key, out pool))
pools.Add(key, pool = new OsbSpritePool(layer, path, origin, additive));
return pool;
}
private string getKey(string path, OsbOrigin origin, bool additive, int poolGroup)
=> $"{path}#{origin}#{(additive ? "1" : "0")}#{poolGroup}";
}
} | using System.Collections.Generic;
namespace StorybrewCommon.Storyboarding.Util
{
public class OsbSpritePools
{
private Dictionary<string, OsbSpritePool> pools = new Dictionary<string, OsbSpritePool>();
private StoryboardLayer layer;
public OsbSpritePools(StoryboardLayer layer)
{
this.layer = layer;
}
public void Clear()
{
foreach (var pool in pools)
pool.Value.Clear();
pools.Clear();
}
public OsbSprite Get(double startTime, double endTime, string path, OsbOrigin origin = OsbOrigin.Centre, bool additive = false, int poolGroup = 0)
=> getPool(path, origin, additive, poolGroup).Get(startTime, endTime);
public void Release(OsbSprite sprite, double endTime)
=> getPool(sprite.TexturePath, sprite.Origin, false, 0).Release(sprite, endTime);
private OsbSpritePool getPool(string path, OsbOrigin origin, bool additive, int poolGroup)
{
string key = getKey(path, origin, additive, poolGroup);
OsbSpritePool pool;
if (!pools.TryGetValue(key, out pool))
pools.Add(key, pool = new OsbSpritePool(layer, path, origin, additive));
return pool;
}
private string getKey(string path, OsbOrigin origin, bool additive, int poolGroup)
=> $"{path}#{origin}#{(additive ? "1" : "0")}#{poolGroup}";
}
} | mit | C# |
6ff9e44ffa558160f2abe9b166cbce6b3284c9d6 | Remove linq allocation. | robinsedlaczek/roslyn,bkoelman/roslyn,dotnet/roslyn,davkean/roslyn,dpoeschl/roslyn,VSadov/roslyn,aelij/roslyn,pdelvo/roslyn,KevinRansom/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,jamesqo/roslyn,Giftednewt/roslyn,jmarolf/roslyn,diryboy/roslyn,Hosch250/roslyn,physhi/roslyn,jamesqo/roslyn,genlu/roslyn,CaptainHayashi/roslyn,diryboy/roslyn,mavasani/roslyn,orthoxerox/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,lorcanmooney/roslyn,OmarTawfik/roslyn,jcouv/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,wvdd007/roslyn,davkean/roslyn,mmitche/roslyn,sharwell/roslyn,reaction1989/roslyn,pdelvo/roslyn,CyrusNajmabadi/roslyn,tvand7093/roslyn,sharwell/roslyn,brettfo/roslyn,kelltrick/roslyn,nguerrera/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,cston/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,mmitche/roslyn,DustinCampbell/roslyn,eriawan/roslyn,mavasani/roslyn,Hosch250/roslyn,mattscheffer/roslyn,KirillOsenkov/roslyn,Hosch250/roslyn,paulvanbrenk/roslyn,wvdd007/roslyn,orthoxerox/roslyn,agocke/roslyn,weltkante/roslyn,sharwell/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,tannergooding/roslyn,srivatsn/roslyn,jasonmalinowski/roslyn,davkean/roslyn,genlu/roslyn,khyperia/roslyn,cston/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,aelij/roslyn,ErikSchierboom/roslyn,tvand7093/roslyn,bkoelman/roslyn,jmarolf/roslyn,abock/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,AnthonyDGreen/roslyn,paulvanbrenk/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,AnthonyDGreen/roslyn,dpoeschl/roslyn,khyperia/roslyn,brettfo/roslyn,agocke/roslyn,ErikSchierboom/roslyn,physhi/roslyn,TyOverby/roslyn,heejaechang/roslyn,AmadeusW/roslyn,eriawan/roslyn,brettfo/roslyn,gafter/roslyn,AmadeusW/roslyn,srivatsn/roslyn,tannergooding/roslyn,AmadeusW/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jkotas/roslyn,diryboy/roslyn,xasx/roslyn,xasx/roslyn,VSadov/roslyn,nguerrera/roslyn,dotnet/roslyn,abock/roslyn,khyperia/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,CaptainHayashi/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,tmeschter/roslyn,TyOverby/roslyn,robinsedlaczek/roslyn,physhi/roslyn,mattscheffer/roslyn,mavasani/roslyn,Giftednewt/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,abock/roslyn,nguerrera/roslyn,tmat/roslyn,agocke/roslyn,tmat/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,AlekseyTs/roslyn,OmarTawfik/roslyn,DustinCampbell/roslyn,jkotas/roslyn,panopticoncentral/roslyn,gafter/roslyn,paulvanbrenk/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,CaptainHayashi/roslyn,jamesqo/roslyn,aelij/roslyn,stephentoub/roslyn,jmarolf/roslyn,robinsedlaczek/roslyn,weltkante/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,xasx/roslyn,shyamnamboodiripad/roslyn,mmitche/roslyn,eriawan/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,orthoxerox/roslyn,kelltrick/roslyn,cston/roslyn,CyrusNajmabadi/roslyn,dpoeschl/roslyn,swaroop-sridhar/roslyn,pdelvo/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,Giftednewt/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,VSadov/roslyn,jcouv/roslyn,bkoelman/roslyn,kelltrick/roslyn,mgoertz-msft/roslyn,AnthonyDGreen/roslyn,jcouv/roslyn,KevinRansom/roslyn,tmeschter/roslyn,lorcanmooney/roslyn,reaction1989/roslyn,tvand7093/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,weltkante/roslyn,genlu/roslyn,jkotas/roslyn,TyOverby/roslyn,tmat/roslyn,heejaechang/roslyn | src/Workspaces/Core/Portable/PatternMatching/PatternMatcherExtensions.cs | src/Workspaces/Core/Portable/PatternMatching/PatternMatcherExtensions.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal static class PatternMatcherExtensions
{
public static PatternMatch? GetFirstMatch(this PatternMatcher matcher, string candidate)
{
var matches = ArrayBuilder<PatternMatch>.GetInstance();
matcher.AddMatches(candidate, matches);
var result = matches.Any() ? (PatternMatch?)matches.First() : null;
matches.Free();
return result;
}
public static bool Matches(this PatternMatcher matcher, string candidate)
=> matcher.GetFirstMatch(candidate) != null;
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal static class PatternMatcherExtensions
{
public static PatternMatch? GetFirstMatch(this PatternMatcher matcher, string candidate)
{
var matches = ArrayBuilder<PatternMatch>.GetInstance();
matcher.AddMatches(candidate, matches);
var result = matches.FirstOrNullable();
matches.Free();
return result;
}
public static bool Matches(this PatternMatcher matcher, string candidate)
=> matcher.GetFirstMatch(candidate) != null;
}
}
| mit | C# |
c652102e406e09bb0c5f5407eb71f7149a20ffa0 | Implement RemoveHostnameCommand#Execute | appharbor/appharbor-cli | src/AppHarbor/Commands/RemoveHostnameCommand.cs | src/AppHarbor/Commands/RemoveHostnameCommand.cs | namespace AppHarbor.Commands
{
public class RemoveHostnameCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public RemoveHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("No hostname was specified");
}
var applicationId = _applicationConfiguration.GetApplicationId();
_appharborClient.RemoveHostname(applicationId, arguments[0]);
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class RemoveHostnameCommand : ICommand
{
private readonly IApplicationConfiguration _applicationConfiguration;
private readonly IAppHarborClient _appharborClient;
public RemoveHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient)
{
_applicationConfiguration = applicationConfiguration;
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("No hostname was specified");
}
throw new NotImplementedException();
}
}
}
| mit | C# |
e77a518db2ba617c988a8828f72d9a204c82447c | change return type to List | LagoVista/DeviceAdmin | src/LagoVista.IoT.DeviceAdmin/Models/UnitSet.cs | src/LagoVista.IoT.DeviceAdmin/Models/UnitSet.cs | using LagoVista.Core.Attributes;
using LagoVista.Core.Interfaces;
using LagoVista.Core.Validation;
using LagoVista.IoT.DeviceAdmin.Resources;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace LagoVista.IoT.DeviceAdmin.Models
{
[EntityDescription(DeviceAdminDomain.DeviceAdmin, Resources.DeviceLibraryResources.Names.UnitSet_Title, Resources.DeviceLibraryResources.Names.UnitSet_Help, Resources.DeviceLibraryResources.Names.UnitSet_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, ResourceType: typeof(DeviceLibraryResources))]
public class UnitSet : KeyOwnedDeviceAdminBase, IValidateable, INoSQLEntity
{
public String DatabaseName { get; set; }
public String EntityType { get; set; }
public UnitSet()
{
Units = new List<Unit>();
}
[JsonProperty]
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.UnitSet_Units, FieldType:FieldTypes.ChildList, ResourceType: typeof(DeviceLibraryResources))]
public List<Unit> Units { get; set; }
public UnitSetSummary CreateUnitSetSummary()
{
return new UnitSetSummary()
{
Id = Id,
IsPublic = IsPublic,
Key = Key,
Name = Name
};
}
}
public class UnitSetSummary : IIDEntity, IKeyedEntity, INamedEntity
{
public string Id { get; set; }
[ListColumn(HeaderResource: Resources.DeviceLibraryResources.Names.Common_Name, ResourceType: typeof(DeviceLibraryResources))]
public String Name { get; set; }
[ListColumn(HeaderResource: Resources.DeviceLibraryResources.Names.Common_Key, HelpResources: Resources.DeviceLibraryResources.Names.Common_Key_Help, ResourceType: typeof(DeviceLibraryResources))]
public String Key { get; set; }
[ListColumn(HeaderResource: Resources.DeviceLibraryResources.Names.Common_IsPublic, ResourceType: typeof(DeviceLibraryResources))]
public bool IsPublic { get; set; }
}
}
| using LagoVista.Core.Attributes;
using LagoVista.Core.Interfaces;
using LagoVista.Core.Validation;
using LagoVista.IoT.DeviceAdmin.Resources;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace LagoVista.IoT.DeviceAdmin.Models
{
[EntityDescription(DeviceAdminDomain.DeviceAdmin, Resources.DeviceLibraryResources.Names.UnitSet_Title, Resources.DeviceLibraryResources.Names.UnitSet_Help, Resources.DeviceLibraryResources.Names.UnitSet_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, ResourceType: typeof(DeviceLibraryResources))]
public class UnitSet : KeyOwnedDeviceAdminBase, IValidateable, INoSQLEntity
{
public String DatabaseName { get; set; }
public String EntityType { get; set; }
public UnitSet()
{
Units = new ObservableCollection<Unit>();
}
[JsonProperty]
[FormField(LabelResource: Resources.DeviceLibraryResources.Names.UnitSet_Units, ResourceType: typeof(DeviceLibraryResources))]
public ObservableCollection<Unit> Units { get; set; }
public UnitSetSummary CreateUnitSetSummary()
{
return new UnitSetSummary()
{
Id = Id,
IsPublic = IsPublic,
Key = Key,
Name = Name
};
}
}
public class UnitSetSummary : IIDEntity, IKeyedEntity, INamedEntity
{
public string Id { get; set; }
[ListColumn(HeaderResource: Resources.DeviceLibraryResources.Names.Common_Name, ResourceType: typeof(DeviceLibraryResources))]
public String Name { get; set; }
[ListColumn(HeaderResource: Resources.DeviceLibraryResources.Names.Common_Key, HelpResources: Resources.DeviceLibraryResources.Names.Common_Key_Help, ResourceType: typeof(DeviceLibraryResources))]
public String Key { get; set; }
[ListColumn(HeaderResource: Resources.DeviceLibraryResources.Names.Common_IsPublic, ResourceType: typeof(DeviceLibraryResources))]
public bool IsPublic { get; set; }
}
}
| mit | C# |
4b2899690d07dcd4fbcd6bc006c9d8a934a19a8f | add Invalid static instances and Length getter for Log | bpowers/Raft.NET | Log.cs | Log.cs | // Copyright 2017 Bobby Powers. All rights reserved.
// Use of this source code is governed by the ISC
// license that can be found in the LICENSE file.
namespace Raft
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public struct LogIndex
{
public static readonly LogIndex Invalid = new LogIndex(-1);
internal int N;
public LogIndex(int n)
{
N = n;
}
}
public struct Term
{
public static readonly Term Invalid = new Term(-1);
internal int N;
public Term(int n)
{
N = n;
}
}
internal interface ILogEntry<TWriteOp>
{
LogIndex Index { get; set; }
Term Term { get; set; }
TWriteOp Operation { get; set; }
}
internal interface ILog<TWriteOp>
{
int Length { get; }
Task<bool> WriteAsync(ILogEntry<TWriteOp> entry);
ILogEntry<TWriteOp> Get(LogIndex index);
}
internal class Log<TWriteOp> : ILog<TWriteOp>
{
Config _config;
List<ILogEntry<TWriteOp>> _log = new List<ILogEntry<TWriteOp>>();
public Log(Config config)
{
_config = config;
}
public Task<bool> WriteAsync(ILogEntry<TWriteOp> entry)
{
if (entry.Index.N > _log.Count)
throw new InvalidOperationException("too far ahead");
return Task.FromResult(true);
}
public ILogEntry<TWriteOp> Get(LogIndex index)
{
return _log[index.N];
}
public int Length
{
get { return _log.Count; }
}
}
}
| // Copyright 2017 Bobby Powers. All rights reserved.
// Use of this source code is governed by the ISC
// license that can be found in the LICENSE file.
namespace Raft
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public struct LogIndex
{
internal int N;
public LogIndex(int n)
{
N = n;
}
}
public struct Term
{
internal int N;
public Term(int n)
{
N = n;
}
}
internal interface ILogEntry<TWriteOp>
{
LogIndex Index { get; set; }
Term Term { get; set; }
TWriteOp Operation { get; set; }
}
internal interface ILog<TWriteOp>
{
Task<bool> WriteAsync(ILogEntry<TWriteOp> entry);
ILogEntry<TWriteOp> Get(LogIndex index);
}
internal class Log<TWriteOp> : ILog<TWriteOp>
{
Config _config;
List<ILogEntry<TWriteOp>> _log = new List<ILogEntry<TWriteOp>>();
public Log(Config config)
{
_config = config;
}
public Task<bool> WriteAsync(ILogEntry<TWriteOp> entry)
{
if (entry.Index.N > _log.Count)
throw new InvalidOperationException("too far ahead");
return Task.FromResult(true);
}
public ILogEntry<TWriteOp> Get(LogIndex index)
{
return _log[index.N];
}
}
}
| isc | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.