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 |
|---|---|---|---|---|---|---|---|---|
8ab1af4f9319895c1b231f29576fe6ba0c5befbc | Test async fire & forget | davidebbo-test/MvcFireAndForgetIssue,davidebbo-test/MvcFireAndForgetIssue | WebApplicationFireAndForget/Controllers/HomeController.cs | WebApplicationFireAndForget/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace WebApplicationFireAndForget.Controllers
{
public class HomeController : Controller
{
public async Task<ActionResult> Index()
{
await Task.Delay(100);
Task t = StartAsyncStuffAndDontWaitForIt();
return View();
}
async Task StartAsyncStuffAndDontWaitForIt()
{
await Task.Delay(5000);
await Task.Delay(5000);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplicationFireAndForget.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | apache-2.0 | C# |
8b8d8f11cf93ae32345e81a52224029f055f1c43 | check instance.GetType() rather than type param for interfaces | Pondidum/Ledger,Pondidum/Ledger | Ledger/AggregateStore.cs | Ledger/AggregateStore.cs | using System;
using System.Linq;
using Ledger.Infrastructure;
namespace Ledger
{
public class AggregateStore<TKey>
{
private readonly IEventStore _eventStore;
public int DefaultSnapshotInterval { get; set; }
public AggregateStore(IEventStore eventStore)
{
_eventStore = eventStore;
DefaultSnapshotInterval = 10;
}
public void Save<TAggregate>(TAggregate aggregate)
where TAggregate : AggregateRoot<TKey>
{
var lastStoredSequence = _eventStore.GetLatestSequenceIDFor(aggregate.ID);
if (lastStoredSequence.HasValue && lastStoredSequence != aggregate.SequenceID)
{
throw new Exception();
}
var changes = aggregate
.GetUncommittedEvents()
.Apply((e, i) => e.SequenceID = aggregate.SequenceID + i)
.ToList();
if (changes.None())
{
return;
}
if (ImplementsSnapshottable(aggregate) && NeedsSnapshot(aggregate, changes.Last().SequenceID))
{
var methodName = TypeInfo.GetMethodName<ISnapshotable<ISequenced>>(x => x.CreateSnapshot());
var createSnapshot = aggregate
.GetType()
.GetMethod(methodName);
var snapshot = (ISequenced)createSnapshot.Invoke(aggregate, new object[] { });
snapshot.SequenceID = changes.Last().SequenceID;
_eventStore.SaveSnapshot(aggregate.ID, snapshot);
}
_eventStore.SaveEvents(aggregate.ID, changes);
aggregate.MarkEventsCommitted();
}
private bool NeedsSnapshot<TAggregate>(TAggregate aggregate, int sequenceID)
{
var interval = DefaultSnapshotInterval;
var control = aggregate as ISnapshotControl;
if (control != null)
{
interval = control.SnapshotInterval;
}
// +1 due to 0 based index
return (sequenceID + 1) % interval == 0;
}
public TAggregate Load<TAggregate>(TKey aggregateID, Func<TAggregate> createNew)
where TAggregate : AggregateRoot<TKey>
{
var aggregate = createNew();
if (ImplementsSnapshottable(aggregate))
{
var snapshot = _eventStore.GetLatestSnapshotFor(aggregate.ID);
var events = _eventStore.LoadEventsSince(aggregateID, snapshot.SequenceID);
aggregate.LoadFromSnapshot(snapshot, events);
}
else
{
var events = _eventStore.LoadEvents(aggregateID);
aggregate.LoadFromEvents(events);
}
return aggregate;
}
private static bool ImplementsSnapshottable(AggregateRoot<TKey> aggregate)
{
return aggregate
.GetType()
.GetInterfaces()
.Any(i => i.GetGenericTypeDefinition() == typeof(ISnapshotable<>));
}
}
}
| using System;
using System.Linq;
using Ledger.Infrastructure;
namespace Ledger
{
public class AggregateStore<TKey>
{
private readonly IEventStore _eventStore;
public int DefaultSnapshotInterval { get; set; }
public AggregateStore(IEventStore eventStore)
{
_eventStore = eventStore;
DefaultSnapshotInterval = 10;
}
public void Save<TAggregate>(TAggregate aggregate)
where TAggregate : AggregateRoot<TKey>
{
var lastStoredSequence = _eventStore.GetLatestSequenceIDFor(aggregate.ID);
if (lastStoredSequence.HasValue && lastStoredSequence != aggregate.SequenceID)
{
throw new Exception();
}
var changes = aggregate
.GetUncommittedEvents()
.Apply((e, i) => e.SequenceID = aggregate.SequenceID + i)
.ToList();
if (changes.None())
{
return;
}
if (ImplementsSnapshottable<TAggregate>() && NeedsSnapshot(aggregate, changes.Last().SequenceID))
{
var methodName = TypeInfo.GetMethodName<ISnapshotable<ISequenced>>(x => x.CreateSnapshot());
var createSnapshot = aggregate
.GetType()
.GetMethod(methodName);
var snapshot = (ISequenced)createSnapshot.Invoke(aggregate, new object[] { });
snapshot.SequenceID = changes.Last().SequenceID;
_eventStore.SaveSnapshot(aggregate.ID, snapshot);
}
_eventStore.SaveEvents(aggregate.ID, changes);
aggregate.MarkEventsCommitted();
}
private bool NeedsSnapshot<TAggregate>(TAggregate aggregate, int sequenceID)
{
var interval = DefaultSnapshotInterval;
var control = aggregate as ISnapshotControl;
if (control != null)
{
interval = control.SnapshotInterval;
}
// +1 due to 0 based index
return (sequenceID + 1) % interval == 0;
}
public TAggregate Load<TAggregate>(TKey aggregateID, Func<TAggregate> createNew)
where TAggregate : AggregateRoot<TKey>
{
var aggregate = createNew();
if (ImplementsSnapshottable<TAggregate>())
{
var snapshot = _eventStore.GetLatestSnapshotFor(aggregate.ID);
var events = _eventStore.LoadEventsSince(aggregateID, snapshot.SequenceID);
aggregate.LoadFromSnapshot(snapshot, events);
}
else
{
var events = _eventStore.LoadEvents(aggregateID);
aggregate.LoadFromEvents(events);
}
return aggregate;
}
private static bool ImplementsSnapshottable<TAggregate>()
{
return typeof(TAggregate)
.GetInterfaces()
.Any(i => i.GetGenericTypeDefinition() == typeof(ISnapshotable<>));
}
}
}
| lgpl-2.1 | C# |
cd1f8706c4f5ddcce5453457e60fde272c5b5d8a | Tidy up some variables | smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Input/Handlers/Tablet/TabletDriver.cs | osu.Framework/Input/Handlers/Tablet/TabletDriver.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.
#if NET5_0
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using OpenTabletDriver;
using OpenTabletDriver.Plugin;
using OpenTabletDriver.Plugin.Tablet;
using osu.Framework.Logging;
namespace osu.Framework.Input.Handlers.Tablet
{
public class TabletDriver : Driver
{
public TabletDriver()
{
Log.Output += (sender, logMessage) => Logger.Log($"{logMessage.Group}: {logMessage.Message}");
DevicesChanged += (sender, args) =>
{
if (Tablet == null && args.Additions.Any())
DetectTablet();
};
}
public void DetectTablet()
{
foreach (var config in getConfigurations())
{
if (TryMatch(config))
break;
}
}
private IEnumerable<TabletConfiguration> getConfigurations()
{
// Retrieve all embedded configurations
var asm = typeof(Driver).Assembly;
return asm.GetManifestResourceNames()
.Where(path => path.Contains(".json"))
.Select(path => deserialize(asm.GetManifestResourceStream(path)));
}
private TabletConfiguration deserialize(Stream stream)
{
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
return new JsonSerializer().Deserialize<TabletConfiguration>(jsonReader);
}
}
}
#endif
| // 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.
#if NET5_0
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using OpenTabletDriver;
using OpenTabletDriver.Plugin;
using OpenTabletDriver.Plugin.Tablet;
using osu.Framework.Logging;
namespace osu.Framework.Input.Handlers.Tablet
{
public class TabletDriver : Driver
{
public TabletDriver()
{
Log.Output += (sender, logMessage) => Logger.Log($"{logMessage.Group}: {logMessage.Message}");
DevicesChanged += (sender, args) =>
{
if (Tablet == null && args.Additions.Any())
DetectTablet();
};
}
public void DetectTablet()
{
foreach (var config in getConfigurations())
{
if (TryMatch(config))
break;
}
}
private IEnumerable<TabletConfiguration> getConfigurations()
{
// Retrieve all embedded configurations
var asm = typeof(Driver).Assembly;
return asm.GetManifestResourceNames()
.Where(path => path.Contains(".json"))
.Select(path => deserialize(asm.GetManifestResourceStream(path)));
}
private TabletConfiguration deserialize(Stream stream)
{
using (var tr = new StreamReader(stream))
using (var jr = new JsonTextReader(tr))
return configurationSerializer.Deserialize<TabletConfiguration>(jr);
}
private JsonSerializer configurationSerializer { get; } = new JsonSerializer();
}
}
#endif
| mit | C# |
49cbaecf4c8f046c5f4058878ac0e4f41206a7dd | Update licence header | NeoAdonis/osu,smoogipooo/osu,EVAST9919/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,naoey/osu,naoey/osu,2yangk23/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu,naoey/osu,DrabWeb/osu,DrabWeb/osu,johnneijzen/osu,UselessToucan/osu,johnneijzen/osu,2yangk23/osu,UselessToucan/osu | osu.Game/Screens/Select/BeatmapClearScoresDialog.cs | osu.Game/Screens/Select/BeatmapClearScoresDialog.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.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Overlays.Dialog;
using osu.Game.Scoring;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace osu.Game.Screens.Select
{
public class BeatmapClearScoresDialog : PopupDialog
{
private ScoreManager scoreManager;
public BeatmapClearScoresDialog(BeatmapInfo beatmap, Action onCompletion)
{
BodyText = $@"{beatmap.Metadata?.Artist} - {beatmap.Metadata?.Title}";
Icon = FontAwesome.fa_eraser;
HeaderText = @"Clearing all local scores. Are you sure?";
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Yes. Please.",
Action = () =>
{
Task.Run(() => scoreManager.Delete(scoreManager.QueryScores(s => !s.DeletePending && s.Beatmap.ID == beatmap.ID).ToList()))
.ContinueWith(t => Schedule(onCompletion));
}
},
new PopupDialogCancelButton
{
Text = @"No, I'm still attached.",
},
};
}
[BackgroundDependencyLoader]
private void load(ScoreManager scoreManager)
{
this.scoreManager = scoreManager;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Overlays.Dialog;
using osu.Game.Scoring;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace osu.Game.Screens.Select
{
public class BeatmapClearScoresDialog : PopupDialog
{
private ScoreManager scoreManager;
public BeatmapClearScoresDialog(BeatmapInfo beatmap, Action onCompletion)
{
BodyText = $@"{beatmap.Metadata?.Artist} - {beatmap.Metadata?.Title}";
Icon = FontAwesome.fa_eraser;
HeaderText = @"Clearing all local scores. Are you sure?";
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Yes. Please.",
Action = () =>
{
Task.Run(() => scoreManager.Delete(scoreManager.QueryScores(s => !s.DeletePending && s.Beatmap.ID == beatmap.ID).ToList()))
.ContinueWith(t => Schedule(onCompletion));
}
},
new PopupDialogCancelButton
{
Text = @"No, I'm still attached.",
},
};
}
[BackgroundDependencyLoader]
private void load(ScoreManager scoreManager)
{
this.scoreManager = scoreManager;
}
}
}
| mit | C# |
c577377bf043a0aafd05dffaedf4cd64a1a9b5a1 | Repair error by changing endpoint address. | mrwizard82d1/learning_wcf,mrwizard82d1/learning_wcf | labs/ch1/HelloIndigo/Host.Specs/RunServiceHostSteps.cs | labs/ch1/HelloIndigo/Host.Specs/RunServiceHostSteps.cs |
using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace Host.Specs
{
/// <summary>
/// An **copy** of the interface specifying the contract for this service.
/// </summary>
[ServiceContract(
Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
[Binding]
public class RunServiceHostSteps
{
[Given(@"that I have started the host")]
public void GivenThatIHaveStartedTheHost()
{
Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
}
[When(@"I execute the ""(.*)"" method of the service")]
public void WhenIExecuteTheMethodOfTheService(string p0)
{
var endPointAddress =
new EndpointAddress(
"http://localhost:8000/HelloIndigo/HelloIndigoService");
var proxy =
ChannelFactory<IHelloIndigoService>.CreateChannel(
new BasicHttpBinding(),
endPointAddress);
ScenarioContext.Current.Set(proxy);
}
[Then(@"I receive ""(.*)"" as a result")]
public void ThenIReceiveAsAResult(string p0)
{
var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
var result = proxy.HelloIndigo();
Assert.That(result, Is.EqualTo("Hello Indigo"));
}
}
}
|
using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace Host.Specs
{
/// <summary>
/// An **copy** of the interface specifying the contract for this service.
/// </summary>
[ServiceContract(
Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
[Binding]
public class RunServiceHostSteps
{
[Given(@"that I have started the host")]
public void GivenThatIHaveStartedTheHost()
{
Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
}
[When(@"I execute the ""(.*)"" method of the service")]
public void WhenIExecuteTheMethodOfTheService(string p0)
{
var endPointAddress =
new EndpointAddress(
"http://localhost:8000/HelloIndigo");
var proxy =
ChannelFactory<IHelloIndigoService>.CreateChannel(
new BasicHttpBinding(), endPointAddress);
ScenarioContext.Current.Set(proxy);
}
[Then(@"I receive ""(.*)"" as a result")]
public void ThenIReceiveAsAResult(string p0)
{
var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
var result = proxy.HelloIndigo();
Assert.That(result, Is.EqualTo("Hello Indigo"));
}
}
}
| epl-1.0 | C# |
a907c8c5445a1c32c0ecbd226fccdefa6dad9afd | Bump the version. | darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,SparkPost/csharp-sparkpost,darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost | src/SparkPost/Properties/AssemblyInfo.cs | src/SparkPost/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("SparkPost")]
[assembly: AssemblyDescription("SparkPost API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SparkPost")]
[assembly: AssemblyProduct("SparkPost")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5dda3e3-7b3d-46c3-b4bb-c627fba37812")]
// 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.15.0.*")]
[assembly: AssemblyFileVersion("1.15.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SparkPost")]
[assembly: AssemblyDescription("SparkPost API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SparkPost")]
[assembly: AssemblyProduct("SparkPost")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5dda3e3-7b3d-46c3-b4bb-c627fba37812")]
// 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.14.0.*")]
[assembly: AssemblyFileVersion("1.14.0.0")]
| apache-2.0 | C# |
fb6ca776ece951f50ab8b6df529614c6f344b1e9 | Update assembly info | DSaunders/ModelMatcher.Assertions | src/ModelMatcher.Assertions/Properties/AssemblyInfo.cs | src/ModelMatcher.Assertions/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ModelMatcher.Assertions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ModelMatcher.Assertions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f76a0dcc-8f7c-48b7-84cd-e09008030dc3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ModelMatcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ModelMatcher")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f76a0dcc-8f7c-48b7-84cd-e09008030dc3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
06619ba5d99118c17cdb2430bac6260589348a42 | Add Equals and GetHashCode to PipeToken | CodefoundryDE/LegacyWrapper,CodefoundryDE/LegacyWrapper | LegacyWrapper.Common/Token/PipeToken.cs | LegacyWrapper.Common/Token/PipeToken.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PommaLabs.Thrower;
namespace LegacyWrapper.Common.Token
{
public class PipeToken
{
public string Token { get; }
public PipeToken(string token)
{
Raise.ArgumentException.IfIsNullOrWhiteSpace(token, nameof(token));
Token = token;
}
public bool Equals(PipeToken other)
{
return other != null &&
Token == other.Token;
}
public override bool Equals(object obj)
{
return obj is PipeToken other &&
Token == other.Token;
}
public override int GetHashCode()
{
return Token.GetHashCode();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PommaLabs.Thrower;
namespace LegacyWrapper.Common.Token
{
public class PipeToken
{
public string Token { get; }
public PipeToken(string token)
{
Raise.ArgumentException.IfIsNullOrWhiteSpace(token, nameof(token));
Token = token;
}
}
}
| mit | C# |
7811c4f5790a07c2f108fe536f10673dd50767f1 | Fix MAL profile regex name | hey-red/Markdown | MarkdownSharp/Extensions/Mal/Profile.cs | MarkdownSharp/Extensions/Mal/Profile.cs | /**
* This file is part of the MarkdownSharp package
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
using System;
using System.Text.RegularExpressions;
namespace MarkdownSharp.Extensions.Mal
{
/// <summary>
/// Create short link for http://myanimelist.net
/// ex: http://myanimelist.net/profile/ritsufag => mal://ritsufag
/// </summary>
public class Profile : IExtensionInterface
{
private static Regex _malProfiles = new Regex(@"
(?:http\:\/\/)
(?:www\.)?
myanimelist\.net\/profile\/
([\w-]{2,16})", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
public string Transform(string text)
{
return _malProfiles.Replace(text, new MatchEvaluator(ProfileEvaluator));
}
private string ProfileEvaluator(Match match)
{
string userName = match.Groups[1].Value;
return String.Format(
"[mal://{0}](http://myanimelist.net/profile/{1})",
userName, userName
);
}
}
}
| /**
* This file is part of the MarkdownSharp package
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
using System;
using System.Text.RegularExpressions;
namespace MarkdownSharp.Extensions.Mal
{
/// <summary>
/// Create short link for http://myanimelist.net
/// ex: http://myanimelist.net/profile/ritsufag => mal://ritsufag
/// </summary>
public class Profile : IExtensionInterface
{
private static Regex _malArticles = new Regex(@"
(?:http\:\/\/)
(?:www\.)?
myanimelist\.net\/profile\/
([\w-]{2,16})", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
public string Transform(string text)
{
return _malArticles.Replace(text, new MatchEvaluator(ProfileEvaluator));
}
private string ProfileEvaluator(Match match)
{
string userName = match.Groups[1].Value;
return String.Format(
"[mal://{0}](http://myanimelist.net/profile/{1})",
userName, userName
);
}
}
}
| mit | C# |
2c40c3a56d174de10c8b2a5fa0fc59e51a41b4f6 | Fix SubscriptionCollection | Whiteknight/Acquaintance,Whiteknight/Acquaintance | Acquaintance/SubscriptionCollection.cs | Acquaintance/SubscriptionCollection.cs | using System;
using System.Collections.Generic;
namespace Acquaintance
{
public sealed class SubscriptionCollection : ISubscribable, IRequestListenable, IDisposable
{
private readonly IMessageBus _messageBus;
private readonly List<IDisposable> _subscriptions;
public SubscriptionCollection(IMessageBus messageBus)
{
_messageBus = messageBus;
_subscriptions = new List<IDisposable>();
}
public void Dispose()
{
foreach (var subscription in _subscriptions)
subscription.Dispose();
}
public IDisposable Subscribe<TPayload>(string name, Action<TPayload> subscriber, Func<TPayload, bool> filter, SubscribeOptions options = null)
{
var token = _messageBus.Subscribe(name, subscriber, filter, options);
_subscriptions.Add(token);
return token;
}
public IDisposable Listen<TRequest, TResponse>(string name, Func<TRequest, TResponse> subscriber, Func<TRequest, bool> filter, SubscribeOptions options = null)
{
var token = _messageBus.Listen(name, subscriber, filter, options);
_subscriptions.Add(token);
return token;
}
}
}
| using System;
using System.Collections.Generic;
namespace Acquaintance
{
public sealed class SubscriptionCollection : ISubscribable, IDisposable
{
private readonly IMessageBus _messageBus;
private readonly List<IDisposable> _subscriptions;
public SubscriptionCollection(IMessageBus messageBus)
{
_messageBus = messageBus;
_subscriptions = new List<IDisposable>();
}
public void Dispose()
{
foreach (var subscription in _subscriptions)
subscription.Dispose();
}
public IDisposable Subscribe<TPayload>(string name, Action<TPayload> subscriber, Func<TPayload, bool> filter, SubscribeOptions options = null)
{
var token = _messageBus.Subscribe(name, subscriber, filter, options);
_subscriptions.Add(token);
return token;
}
public IDisposable Listen<TRequest, TResponse>(string name, Func<TRequest, TResponse> subscriber, Func<TRequest, bool> filter, SubscribeOptions options = null)
{
var token = _messageBus.Listen(name, subscriber, filter, options);
_subscriptions.Add(token);
return token;
}
}
}
| apache-2.0 | C# |
c67072d7d67dda7431b1ee0426bcc591fb1f0ab1 | Update OpenTsdbSubmissionException.cs | dejanfajfar/openTSDB.net | openTSDB.net/Exceptions/OpenTsdbSubmissionException.cs | openTSDB.net/Exceptions/OpenTsdbSubmissionException.cs | using System;
namespace OpenTsdbNet.Exceptions
{
public class OpenTsdbSubmissionException : Exception
{
public OpenTsdbSubmissionException(int httpStatus, string responseMessage, Uri openTsdbUri)
: base($"[{httpStatus}] : {responseMessage} @ {openTsdbUri}")
{
HttpStatusCode = httpStatus;
HttpResponseMessage = responseMessage;
OpenTsdbUri = openTsdbUri;
}
/// <summary>
/// Gets the URI of the openTSDB servr used
/// </summary>
public Uri OpenTsdbUri { get; }
/// <summary>
/// Gets the HTTP status code returned while submitting the data point
/// </summary>
public int HttpStatusCode { get; }
/// <summary>
/// Gets the response message or explanation of the error that happened while submitting the data point
/// </summary>
public string HttpResponseMessage { get; }
}
} | using System;
namespace OpenTsdbNet.Exceptions
{
/// <summary>
/// Thrown when a data point submission to the openTSDB server fails
/// </summary>
public class OpenTsdbSubmissionException : Exception
{
public OpenTsdbSubmissionException(int httpStatus, string responseMessage, Uri openTsdbUri)
: base($"[{httpStatus}] : {responseMessage} @ {openTsdbUri}")
{
HttpStatusCode = httpStatus;
HttpResponseMessage = responseMessage;
OpenTsdbUri = openTsdbUri;
}
/// <summary>
/// Gets the URI of the openTSDB servr used
/// </summary>
public Uri OpenTsdbUri { get; }
/// <summary>
/// Gets the HTTP status code returned while submitting the data point
/// </summary>
public int HttpStatusCode { get; }
/// <summary>
/// Gets the response message or explanation of the error that happened while submitting the data point
/// </summary>
public string HttpResponseMessage { get; }
}
} | apache-2.0 | C# |
565b8906b08971e7021803252282f37e5ca9bbd6 | Add progress and project name in statusbar. | zhaoboqiang/sln2cmake,zhaoboqiang/sln2cmake | sln2cmake/SolutionConverter.cs | sln2cmake/SolutionConverter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Sln2CMake
{
internal class SolutionConverter
{
static public void Run(IServiceProvider serviceProvider, IVsStatusbar statusbar)
{
uint cookie = 0;
var dte = (DTE2)serviceProvider.GetService(typeof(DTE));
var projects = dte.Solution.Projects;
// Initialize the progress bar.
statusbar.Progress(ref cookie, 1, "", 0, 0);
for (uint i = 1, n = (uint)projects.Count; i <= n; ++i)
{
var project = projects.Item(i);
statusbar.Progress(ref cookie, 1, "", i + 1, n);
statusbar.SetText(string.Format("Converting {0}", project.Name));
}
// Clear the progress bar.
statusbar.Progress(ref cookie, 0, "", 0, 0);
statusbar.FreezeOutput(0);
statusbar.Clear();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Sln2CMake
{
internal class SolutionConverter
{
static public void Run(IServiceProvider serviceProvider, IVsStatusbar statusbar)
{
var dte = (DTE2)serviceProvider.GetService(typeof(DTE));
var projects = dte.Solution.Projects;
for (int i = 1, n = projects.Count; i <= n; ++i)
{
var project = projects.Item(i);
System.Console.WriteLine("[{0} {1}", i, project.Name);
}
}
}
}
| mit | C# |
9ec24457a9f394f374fa8649a90cd540b101adae | Clean up code and message. | xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp | docs/tutorials/printtopdf/src/PdfRenderer/PdfRenderer.cs | docs/tutorials/printtopdf/src/PdfRenderer/PdfRenderer.cs | using System;
using System.Threading.Tasks;
using WebSharpJs.NodeJS;
using WebSharpJs.Electron;
using WebSharpJs.Script;
using WebSharpJs.DOM;
//namespace PdfRenderer
//{
public class Startup
{
static WebSharpJs.NodeJS.Console console;
/// <summary>
/// Default entry into managed code.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<object> Invoke(object input)
{
if (console == null)
console = await WebSharpJs.NodeJS.Console.Instance();
try
{
var page = new HtmlPage();
var document = await page.GetDocument();
var printPDFBtn = await document.GetElementById("print-pdf");
var ipcRenderer = await IpcRenderer.Create();
await printPDFBtn?.AttachEvent("click",
new EventHandler(async (sender, evt) =>
{
await console.Log("clicked");
ipcRenderer.Send("print-to-pdf");
})
);
ipcRenderer.On("wrote-pdf",
new IpcRendererEventListener(async (result) =>
{
var state = result.CallbackState as object[];
var parms = state[1] as object[];
foreach(var parm in parms)
await console.Log(parm);
var pathLabel = await document.GetElementById("file-path");
await pathLabel.SetProperty("innerHTML", $"Wrote PDF to: {parms[0]}");
}));
}
catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); }
return null;
}
}
//}
| using System;
using System.Threading.Tasks;
using WebSharpJs.NodeJS;
using WebSharpJs.Electron;
using WebSharpJs.Script;
using WebSharpJs.DOM;
//namespace PdfRenderer
//{
public class Startup
{
static WebSharpJs.NodeJS.Console console;
/// <summary>
/// Default entry into managed code.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<object> Invoke(object input)
{
if (console == null)
console = await WebSharpJs.NodeJS.Console.Instance();
try
{
var page = new HtmlPage();
var document = await page.GetDocument();
var printPDFBtn = await document.GetElementById("print-pdf");
var ipcRenderer = await IpcRenderer.Create();
await printPDFBtn?.AttachEvent("click",
new EventHandler(async (sender, evt) =>
{
await console.Log("clicked");
ipcRenderer.Send("print-to-pdf");
})
);
ipcRenderer.On("wrote-pdf",
new IpcRendererEventListener(async (result) =>
{
var state = result.CallbackState as object[];
var parms = state[1] as object[];
foreach(var parm in parms)
await console.Log(parm);
var pathLabel = await document.GetElementById("file-path");
await pathLabel.SetProperty("innerHTML", parms[0]);
}));
// printPDFBtn.addEventListener('click', function (event) {
// ipc.send('print-to-pdf')
// })
// ipc.on('wrote-pdf', function (event, path) {
// const message = `Wrote PDF to: ${path}`
// document.getElementById('pdf-path').innerHTML = message
// })
}
catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); }
return null;
}
}
//}
| mit | C# |
e2c043737dbe4c95f8273488cfdac437474072fd | Reword xmldoc to specify intended usage | smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu-new | osu.Game/Screens/IOsuScreen.cs | osu.Game/Screens/IOsuScreen.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.Bindables;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Overlays;
using osu.Game.Rulesets;
namespace osu.Game.Screens
{
public interface IOsuScreen : IScreen
{
/// <summary>
/// Whether the beatmap or ruleset should be allowed to be changed by the user or game.
/// Used to mark exclusive areas where this is strongly prohibited, like gameplay.
/// </summary>
bool DisallowExternalBeatmapRulesetChanges { get; }
/// <summary>
/// Whether the user can exit this this <see cref="IOsuScreen"/> by pressing the back button.
/// </summary>
bool AllowBackButton { get; }
/// <summary>
/// Whether a top-level component should be allowed to exit the current screen to, for example,
/// complete an import. Note that this can be overridden by a user if they specifically request.
/// </summary>
bool AllowExternalScreenChange { get; }
/// <summary>
/// Whether this <see cref="OsuScreen"/> allows the cursor to be displayed.
/// </summary>
bool CursorVisible { get; }
/// <summary>
/// Whether all overlays should be hidden when this screen is entered or resumed.
/// </summary>
bool HideOverlaysOnEnter { get; }
/// <summary>
/// Whether overlays should be able to be opened once this screen is entered or resumed.
/// </summary>
OverlayActivation InitialOverlayActivationMode { get; }
/// <summary>
/// The amount of parallax to be applied while this screen is displayed.
/// </summary>
float BackgroundParallaxAmount { get; }
Bindable<WorkingBeatmap> Beatmap { get; }
Bindable<RulesetInfo> Ruleset { get; }
/// <summary>
/// Whether mod rate adjustments are allowed to be applied.
/// </summary>
bool AllowRateAdjustments { get; }
/// <summary>
/// Invoked when the back button has been pressed to close any overlays before exiting this <see cref="IOsuScreen"/>.
/// </summary>
/// <remarks>
/// Return <c>true</c> to block this <see cref="IOsuScreen"/> from being exited after closing an overlay.
/// Return <c>false</c> if this <see cref="IOsuScreen"/> should continue exiting.
/// </remarks>
bool OnBackButton();
}
}
| // 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.Bindables;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Overlays;
using osu.Game.Rulesets;
namespace osu.Game.Screens
{
public interface IOsuScreen : IScreen
{
/// <summary>
/// Whether the beatmap or ruleset should be allowed to be changed by the user or game.
/// Used to mark exclusive areas where this is strongly prohibited, like gameplay.
/// </summary>
bool DisallowExternalBeatmapRulesetChanges { get; }
/// <summary>
/// Whether the user can exit this this <see cref="IOsuScreen"/> by pressing the back button.
/// </summary>
bool AllowBackButton { get; }
/// <summary>
/// Whether a top-level component should be allowed to exit the current screen to, for example,
/// complete an import. Note that this can be overridden by a user if they specifically request.
/// </summary>
bool AllowExternalScreenChange { get; }
/// <summary>
/// Whether this <see cref="OsuScreen"/> allows the cursor to be displayed.
/// </summary>
bool CursorVisible { get; }
/// <summary>
/// Whether all overlays should be hidden when this screen is entered or resumed.
/// </summary>
bool HideOverlaysOnEnter { get; }
/// <summary>
/// Whether overlays should be able to be opened once this screen is entered or resumed.
/// </summary>
OverlayActivation InitialOverlayActivationMode { get; }
/// <summary>
/// The amount of parallax to be applied while this screen is displayed.
/// </summary>
float BackgroundParallaxAmount { get; }
Bindable<WorkingBeatmap> Beatmap { get; }
Bindable<RulesetInfo> Ruleset { get; }
/// <summary>
/// Whether mod rate adjustments are allowed to be applied.
/// </summary>
bool AllowRateAdjustments { get; }
/// <summary>
/// Whether there are sub overlays/screens that need closing with the back button before this <see cref="IOsuScreen"/> can be exited.
/// </summary>
bool OnBackButton();
}
}
| mit | C# |
a83a5b2ddb553e48471cf87fec0a8f782f643822 | Add commit for auth order | drasticactions/TwitchBot2002 | TwitchBot2002/Program.cs | TwitchBot2002/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TwitchLib;
using TwitchLib.Models.Client;
using System.Speech.Synthesis;
namespace TwitchBot2002
{
class Program
{
static SpeechSynthesizer synth;
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
synth = new SpeechSynthesizer();
synth.SetOutputToDefaultAudioDevice();
var authTokens = System.IO.File.ReadLines("tokens.txt").ToArray();
// Bot Username, API Key, Channel to join.
var client = new TwitchClient(new ConnectionCredentials(authTokens[0], authTokens[1]), "");
client.OnMessageReceived += Client_OnMessageReceived;
client.Connect();
Console.WriteLine("Press any key to quit");
Console.ReadKey();
}
private static async void Client_OnMessageReceived(object sender, TwitchLib.Events.Client.OnMessageReceivedArgs e)
{
if (e.ChatMessage.Bits > 0)
{
// voice message!
synth.SpeakAsync(e.ChatMessage.Message);
Console.WriteLine($"Voice: {e.ChatMessage.Username}: {e.ChatMessage.Message}");
}
else
{
Console.WriteLine($"{e.ChatMessage.Username}: {e.ChatMessage.Message}");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TwitchLib;
using TwitchLib.Models.Client;
using System.Speech.Synthesis;
namespace TwitchBot2002
{
class Program
{
static SpeechSynthesizer synth;
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
synth = new SpeechSynthesizer();
synth.SetOutputToDefaultAudioDevice();
var authTokens = System.IO.File.ReadLines("tokens.txt").ToArray();
var client = new TwitchClient(new ConnectionCredentials(authTokens[0], authTokens[1]), "");
client.OnMessageReceived += Client_OnMessageReceived;
client.Connect();
Console.WriteLine("Press any key to quit");
Console.ReadKey();
}
private static async void Client_OnMessageReceived(object sender, TwitchLib.Events.Client.OnMessageReceivedArgs e)
{
if (e.ChatMessage.Bits > 0)
{
// voice message!
synth.SpeakAsync(e.ChatMessage.Message);
Console.WriteLine($"Voice: {e.ChatMessage.Username}: {e.ChatMessage.Message}");
}
else
{
Console.WriteLine($"{e.ChatMessage.Username}: {e.ChatMessage.Message}");
}
}
}
}
| mit | C# |
fee61c56e76782a77b1e8fb2c03c01b0a9bba4be | Fix foldout | appetizermonster/Unity3D-ActionEngine | Assets/ActionEngine/AEScript/Editor/AEScriptDataDrawer.cs | Assets/ActionEngine/AEScript/Editor/AEScriptDataDrawer.cs | using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
namespace ActionEngine {
[CustomPropertyDrawer(typeof(AEScriptData))]
public sealed class AEScriptDataDrawer : PropertyDrawer {
private const int TEXT_HEIGHT = 18;
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property);
property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, label);
if (!property.isExpanded) {
EditorGUI.EndProperty();
return;
}
var oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
const int INDENT = 30;
const int LABEL_WIDTH = 50;
var keyRect = new Rect(position.x + INDENT + LABEL_WIDTH, position.y + TEXT_HEIGHT, position.width - INDENT - LABEL_WIDTH, TEXT_HEIGHT);
var typeRect = keyRect; typeRect.y += TEXT_HEIGHT;
var valueRect = typeRect; valueRect.y += TEXT_HEIGHT;
var keyLabelRect = new Rect(position.x + INDENT, keyRect.y, LABEL_WIDTH, TEXT_HEIGHT);
var typeLabelRect = keyLabelRect; typeLabelRect.y += TEXT_HEIGHT;
var valueLabelRect = typeLabelRect; valueLabelRect.y += TEXT_HEIGHT;
var keyProp = property.FindPropertyRelative("key");
var typeProp = property.FindPropertyRelative("type");
EditorGUI.PrefixLabel(keyLabelRect, new GUIContent("Key"));
EditorGUI.PropertyField(keyRect, keyProp, GUIContent.none);
EditorGUI.PrefixLabel(typeLabelRect, new GUIContent("Type"));
EditorGUI.PropertyField(typeRect, typeProp, GUIContent.none);
try {
var typeEnumString = typeProp.enumNames[typeProp.enumValueIndex];
// Unity strips '@' prefix for naming variables, so we don't need to add '@' prefix
var valueVariableName = typeEnumString.ToLowerInvariant();
var valueProp = property.FindPropertyRelative(valueVariableName);
EditorGUI.PrefixLabel(valueLabelRect, new GUIContent("Value"));
EditorGUI.PropertyField(valueRect, valueProp, GUIContent.none, true);
} catch (Exception ex) {
Debug.LogException(ex);
}
EditorGUI.indentLevel = oldIndent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
if (property.isExpanded)
return base.GetPropertyHeight(property, label) + TEXT_HEIGHT * 3;
return base.GetPropertyHeight(property, label);
}
}
}
| using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
namespace ActionEngine {
[CustomPropertyDrawer(typeof(AEScriptData))]
public class AEScriptDataDrawer : PropertyDrawer {
private const int TEXT_HEIGHT = 18;
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property);
var labelPosition = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
var oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
const int INDENT = 30;
const int LABEL_WIDTH = 50;
var keyRect = new Rect(position.x + INDENT + LABEL_WIDTH, labelPosition.y + TEXT_HEIGHT, position.width - INDENT - LABEL_WIDTH, TEXT_HEIGHT);
var typeRect = keyRect; typeRect.y += TEXT_HEIGHT;
var valueRect = typeRect; valueRect.y += TEXT_HEIGHT;
var keyLabelRect = new Rect(position.x + INDENT, keyRect.y, LABEL_WIDTH, TEXT_HEIGHT);
var typeLabelRect = keyLabelRect; typeLabelRect.y += TEXT_HEIGHT;
var valueLabelRect = typeLabelRect; valueLabelRect.y += TEXT_HEIGHT;
var keyProp = property.FindPropertyRelative("key");
var typeProp = property.FindPropertyRelative("type");
EditorGUI.PrefixLabel(keyLabelRect, new GUIContent("Key"));
EditorGUI.PropertyField(keyRect, keyProp, GUIContent.none);
EditorGUI.PrefixLabel(typeLabelRect, new GUIContent("Type"));
EditorGUI.PropertyField(typeRect, typeProp, GUIContent.none);
try {
var typeEnumString = typeProp.enumNames[typeProp.enumValueIndex];
// Unity strips '@' prefix for naming variables, so we don't need to add '@' prefix
var valueVariableName = typeEnumString.ToLowerInvariant();
var valueProp = property.FindPropertyRelative(valueVariableName);
EditorGUI.PrefixLabel(valueLabelRect, new GUIContent("Value"));
EditorGUI.PropertyField(valueRect, valueProp, GUIContent.none, true);
} catch (Exception ex) {
Debug.LogException(ex);
}
EditorGUI.indentLevel = oldIndent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
return base.GetPropertyHeight(property, label) + TEXT_HEIGHT * 3;
}
}
}
| mit | C# |
e9179930d70c6c53c1ff87a8cd033c1c8950ec4a | Add parser error message in SerializedConstant. | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver.DotNet/Serialized/SerializedConstant.cs | src/AsmResolver.DotNet/Serialized/SerializedConstant.cs | using System;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Blob;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet.Serialized
{
/// <summary>
/// Represents a lazily initialized implementation of <see cref="Constant"/> that is read from a
/// .NET metadata image.
/// </summary>
public class SerializedConstant : Constant
{
private readonly ModuleReaderContext _context;
private readonly ConstantRow _row;
/// <summary>
/// Creates a constant from a constant metadata row.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="token">The token to initialize the constant for.</param>
/// <param name="row">The metadata table row to base the constant on.</param>
public SerializedConstant(
ModuleReaderContext context,
MetadataToken token,
in ConstantRow row)
: base(token)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_row = row;
Type = row.Type;
}
/// <inheritdoc />
protected override IHasConstant GetParent()
{
var token = _context.ParentModule.GetConstantOwner(MetadataToken.Rid);
return _context.ParentModule.TryLookupMember(token, out var member)
? member as IHasConstant
: _context.BadImageAndReturn<IHasConstant>($"Invalid parent member in constant {MetadataToken.ToString()}.");
}
/// <inheritdoc />
protected override DataBlobSignature GetValue()
{
if (!_context.Image.DotNetDirectory.Metadata
.GetStream<BlobStream>()
.TryGetBlobReaderByIndex(_row.Value, out var reader))
{
// Don't report error. null constants are allowed (e.g. null strings).
return null;
}
return DataBlobSignature.FromReader(ref reader);
}
}
}
| using System;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Blob;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet.Serialized
{
/// <summary>
/// Represents a lazily initialized implementation of <see cref="Constant"/> that is read from a
/// .NET metadata image.
/// </summary>
public class SerializedConstant : Constant
{
private readonly ModuleReaderContext _context;
private readonly ConstantRow _row;
/// <summary>
/// Creates a constant from a constant metadata row.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="token">The token to initialize the constant for.</param>
/// <param name="row">The metadata table row to base the constant on.</param>
public SerializedConstant(
ModuleReaderContext context,
MetadataToken token,
in ConstantRow row)
: base(token)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_row = row;
Type = row.Type;
}
/// <inheritdoc />
protected override IHasConstant GetParent()
{
var token = _context.ParentModule.GetConstantOwner(MetadataToken.Rid);
return _context.ParentModule.TryLookupMember(token, out var member)
? member as IHasConstant
: null;
}
/// <inheritdoc />
protected override DataBlobSignature GetValue()
{
if (!_context.Image.DotNetDirectory.Metadata
.GetStream<BlobStream>()
.TryGetBlobReaderByIndex(_row.Value, out var reader))
{
// Don't report error. null constants are allowed (e.g. null strings).
return null;
}
return DataBlobSignature.FromReader(ref reader);
}
}
}
| mit | C# |
4abf3ee8ce22fca445fb89df288f13da1bf4b704 | Make the constructor public for usage in user custom widgets | mminns/xwt,iainx/xwt,hamekoz/xwt,antmicro/xwt,lytico/xwt,mono/xwt,residuum/xwt,sevoku/xwt,directhex/xwt,TheBrainTech/xwt,mminns/xwt,akrisiun/xwt,cra0zy/xwt,steffenWi/xwt,hwthomas/xwt | Xwt/Xwt/WidgetSpacing.cs | Xwt/Xwt/WidgetSpacing.cs | //
// WidgetSpacing.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Xwt.Backends;
using Xwt.Engine;
using Xwt.Drawing;
using System.Reflection;
using System.Xaml;
using System.Linq;
namespace Xwt
{
public class WidgetSpacing
{
ISpacingListener parent;
double top, left, right, bottom;
public WidgetSpacing (ISpacingListener parent)
{
this.parent = parent;
}
void NotifyChanged ()
{
parent.OnSpacingChanged (this);
}
public double Left {
get { return left; }
set { left = value; NotifyChanged (); }
}
public double Bottom {
get {
return this.bottom;
}
set {
bottom = value; NotifyChanged ();
}
}
public double Right {
get {
return this.right;
}
set {
right = value; NotifyChanged ();
}
}
public double Top {
get {
return this.top;
}
set {
top = value; NotifyChanged ();
}
}
public double HorizontalSpacing {
get { return left + right; }
}
public double VerticalSpacing {
get { return top + bottom; }
}
public void Set (double left, double top, double right, double bottom)
{
this.left = left;
this.top = top;
this.bottom = bottom;
this.right = right;
NotifyChanged ();
}
public void SetAll (double padding)
{
this.left = padding;
this.top = padding;
this.bottom = padding;
this.right = padding;
NotifyChanged ();
}
}
public interface ISpacingListener
{
void OnSpacingChanged (WidgetSpacing source);
}
}
| //
// WidgetSpacing.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Xwt.Backends;
using Xwt.Engine;
using Xwt.Drawing;
using System.Reflection;
using System.Xaml;
using System.Linq;
namespace Xwt
{
public class WidgetSpacing
{
ISpacingListener parent;
double top, left, right, bottom;
internal WidgetSpacing (ISpacingListener parent)
{
this.parent = parent;
}
void NotifyChanged ()
{
parent.OnSpacingChanged (this);
}
public double Left {
get { return left; }
set { left = value; NotifyChanged (); }
}
public double Bottom {
get {
return this.bottom;
}
set {
bottom = value; NotifyChanged ();
}
}
public double Right {
get {
return this.right;
}
set {
right = value; NotifyChanged ();
}
}
public double Top {
get {
return this.top;
}
set {
top = value; NotifyChanged ();
}
}
public double HorizontalSpacing {
get { return left + right; }
}
public double VerticalSpacing {
get { return top + bottom; }
}
public void Set (double left, double top, double right, double bottom)
{
this.left = left;
this.top = top;
this.bottom = bottom;
this.right = right;
NotifyChanged ();
}
public void SetAll (double padding)
{
this.left = padding;
this.top = padding;
this.bottom = padding;
this.right = padding;
NotifyChanged ();
}
}
public interface ISpacingListener
{
void OnSpacingChanged (WidgetSpacing source);
}
}
| mit | C# |
0e80182e45ffabc7891a74f41cf9f4828db02ca1 | Use Span to drop byte[1] allocations (dotnet/coreclr#15680) | ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,ravimeda/corefx,wtgodbe/corefx,ptoonen/corefx,BrennanConroy/corefx,ravimeda/corefx,ViktorHofer/corefx,zhenlan/corefx,Ermiar/corefx,mmitche/corefx,Ermiar/corefx,mmitche/corefx,ravimeda/corefx,zhenlan/corefx,Ermiar/corefx,BrennanConroy/corefx,ViktorHofer/corefx,zhenlan/corefx,ericstj/corefx,Jiayili1/corefx,shimingsg/corefx,ravimeda/corefx,wtgodbe/corefx,mmitche/corefx,Jiayili1/corefx,ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,ptoonen/corefx,Jiayili1/corefx,mmitche/corefx,BrennanConroy/corefx,Ermiar/corefx,mmitche/corefx,ericstj/corefx,shimingsg/corefx,zhenlan/corefx,wtgodbe/corefx,wtgodbe/corefx,Jiayili1/corefx,ravimeda/corefx,zhenlan/corefx,Ermiar/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,ravimeda/corefx,ravimeda/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx,zhenlan/corefx,ericstj/corefx,mmitche/corefx,Jiayili1/corefx,Ermiar/corefx,mmitche/corefx,zhenlan/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,ptoonen/corefx,ptoonen/corefx,ericstj/corefx,ptoonen/corefx,Ermiar/corefx,shimingsg/corefx | src/Common/src/CoreLib/System/IO/PinnedBufferMemoryStream.cs | src/Common/src/CoreLib/System/IO/PinnedBufferMemoryStream.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.
/*============================================================
**
**
**
**
**
** Purpose: Pins a byte[], exposing it as an unmanaged memory
** stream. Used in ResourceReader for corner cases.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.IO
{
internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
{
private byte[] _array;
private GCHandle _pinningHandle;
internal PinnedBufferMemoryStream(byte[] array)
{
Debug.Assert(array != null, "Array can't be null");
_array = array;
_pinningHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
int len = array.Length;
fixed (byte* ptr = &MemoryMarshal.GetReference((Span<byte>)array))
Initialize(ptr, len, len, FileAccess.Read);
}
public override int Read(Span<byte> destination) => ReadCore(destination);
public override void Write(ReadOnlySpan<byte> source) => WriteCore(source);
~PinnedBufferMemoryStream()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if (_pinningHandle.IsAllocated)
{
_pinningHandle.Free();
}
base.Dispose(disposing);
}
}
}
| // 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.
/*============================================================
**
**
**
**
**
** Purpose: Pins a byte[], exposing it as an unmanaged memory
** stream. Used in ResourceReader for corner cases.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.IO
{
internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
{
private byte[] _array;
private GCHandle _pinningHandle;
internal PinnedBufferMemoryStream(byte[] array)
{
Debug.Assert(array != null, "Array can't be null");
int len = array.Length;
// Handle 0 length byte arrays specially.
if (len == 0)
{
array = new byte[1];
len = 0;
}
_array = array;
_pinningHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
fixed (byte* ptr = &_array[0])
Initialize(ptr, len, len, FileAccess.Read);
}
public override int Read(Span<byte> destination) => ReadCore(destination);
public override void Write(ReadOnlySpan<byte> source) => WriteCore(source);
~PinnedBufferMemoryStream()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if (_pinningHandle.IsAllocated)
{
_pinningHandle.Free();
}
base.Dispose(disposing);
}
}
}
| mit | C# |
386c245e8b30692145d2a0d0259f2a45c15764af | fix parameter spelling | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/XPack/MachineLearning/Job/Config/DataDescription.cs | src/Nest/XPack/MachineLearning/Job/Config/DataDescription.cs | using System;
using System.Linq.Expressions;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// Defines the format of the input data when you send data to the machine learning job.
/// Note that when configure a datafeed, these properties are automatically set.
/// </summary>
[JsonConverter(typeof(ReadAsTypeJsonConverter<DataDescription>))]
public interface IDataDescription
{
/// <summary>
/// Only JSON format is supported at this time.
/// </summary>
[JsonProperty("format")]
string Format { get; set; }
/// <summary>
/// The name of the field that contains the timestamp. The default value is time.
/// </summary>
[JsonProperty("time_field")]
Field TimeField { get; set; }
/// <summary>
/// The time format, which can be epoch, epoch_ms, or a custom pattern.
/// </summary>
[JsonProperty("time_format")]
string TimeFormat { get; set; }
}
/// <inheritdoc />
public class DataDescription : IDataDescription
{
/// <inheritdoc />
public string Format { get; set; }
/// <inheritdoc />
public Field TimeField { get; set; }
/// <inheritdoc />
public string TimeFormat { get; set; }
}
/// <inheritdoc />
public class DataDescriptionDescriptor<T> : DescriptorBase<DataDescriptionDescriptor<T>, IDataDescription>, IDataDescription
{
string IDataDescription.Format { get; set; }
Field IDataDescription.TimeField { get; set; }
string IDataDescription.TimeFormat { get; set; }
/// <inheritdoc />
public DataDescriptionDescriptor<T> Format(string format) => Assign(a => a.Format = format);
/// <inheritdoc />
public DataDescriptionDescriptor<T> TimeField(Field timeField) => Assign(a => a.TimeField = timeField);
/// <inheritdoc />
public DataDescriptionDescriptor<T> TimeField(Expression<Func<T, object>> objectPath) => Assign(a => a.TimeField = objectPath);
/// <inheritdoc />
public DataDescriptionDescriptor<T> TimeFormat(string timeFormat) => Assign(a => a.TimeFormat = timeFormat);
}
}
| using System;
using System.Linq.Expressions;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// Defines the format of the input data when you send data to the machine learning job.
/// Note that when configure a datafeed, these properties are automatically set.
/// </summary>
[JsonConverter(typeof(ReadAsTypeJsonConverter<DataDescription>))]
public interface IDataDescription
{
/// <summary>
/// Only JSON format is supported at this time.
/// </summary>
[JsonProperty("format")]
string Format { get; set; }
/// <summary>
/// The name of the field that contains the timestamp. The default value is time.
/// </summary>
[JsonProperty("time_field")]
Field TimeField { get; set; }
/// <summary>
/// The time format, which can be epoch, epoch_ms, or a custom pattern.
/// </summary>
[JsonProperty("time_format")]
string TimeFormat { get; set; }
}
/// <inheritdoc />
public class DataDescription : IDataDescription
{
/// <inheritdoc />
public string Format { get; set; }
/// <inheritdoc />
public Field TimeField { get; set; }
/// <inheritdoc />
public string TimeFormat { get; set; }
}
/// <inheritdoc />
public class DataDescriptionDescriptor<T> : DescriptorBase<DataDescriptionDescriptor<T>, IDataDescription>, IDataDescription
{
string IDataDescription.Format { get; set; }
Field IDataDescription.TimeField { get; set; }
string IDataDescription.TimeFormat { get; set; }
/// <inheritdoc />
public DataDescriptionDescriptor<T> Format(string format) => Assign(a => a.Format = format);
/// <inheritdoc />
public DataDescriptionDescriptor<T> TimeField(Field timeField) => Assign(a => a.TimeField = timeField);
/// <inheritdoc />
public DataDescriptionDescriptor<T> TimeField(Expression<Func<T, object>> objectPath) => Assign(a => a.TimeField = objectPath);
/// <inheritdoc />
public DataDescriptionDescriptor<T> TimeFormat(string timeTormat) => Assign(a => a.TimeFormat = timeTormat);
}
}
| apache-2.0 | C# |
04a41908bd990228686dab67543f49931d8bb7a1 | Comment tweak to kick the CI build again. | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices/Debugging/CommandBreakpointDetails.cs | src/PowerShellEditorServices/Debugging/CommandBreakpointDetails.cs | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Management.Automation;
using Microsoft.PowerShell.EditorServices.Utility;
namespace Microsoft.PowerShell.EditorServices
{
/// <summary>
/// Provides details about a command breakpoint that is set in the PowerShell debugger.
/// </summary>
public class CommandBreakpointDetails : BreakpointDetailsBase
{
/// <summary>
/// Gets the name of the command on which the command breakpoint has been set.
/// </summary>
public string Name { get; private set; }
private CommandBreakpointDetails()
{
}
/// <summary>
/// Creates an instance of the <see cref="CommandBreakpointDetails"/> class from the individual
/// pieces of breakpoint information provided by the client.
/// </summary>
/// <param name="name">The name of the command to break on.</param>
/// <param name="condition">Condition string that would be applied to the breakpoint Action parameter.</param>
/// <returns></returns>
public static CommandBreakpointDetails Create(
string name,
string condition = null)
{
Validate.IsNotNull(nameof(name), name);
return new CommandBreakpointDetails {
Name = name,
Condition = condition
};
}
/// <summary>
/// Creates an instance of the <see cref="CommandBreakpointDetails"/> class from a
/// PowerShell CommandBreakpoint object.
/// </summary>
/// <param name="breakpoint">The Breakpoint instance from which details will be taken.</param>
/// <returns>A new instance of the BreakpointDetails class.</returns>
public static CommandBreakpointDetails Create(Breakpoint breakpoint)
{
Validate.IsNotNull("breakpoint", breakpoint);
CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint;
if (commandBreakpoint == null)
{
throw new ArgumentException(
"Unexpected breakpoint type: " + breakpoint.GetType().Name);
}
var breakpointDetails = new CommandBreakpointDetails {
Verified = true,
Name = commandBreakpoint.Command,
Condition = commandBreakpoint.Action?.ToString()
};
return breakpointDetails;
}
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Management.Automation;
using Microsoft.PowerShell.EditorServices.Utility;
namespace Microsoft.PowerShell.EditorServices
{
/// <summary>
/// Provides details about a command breakpoint that is set in the
/// PowerShell debugger.
/// </summary>
public class CommandBreakpointDetails : BreakpointDetailsBase
{
/// <summary>
/// Gets the name of the command on which the command breakpoint has been set.
/// </summary>
public string Name { get; private set; }
private CommandBreakpointDetails()
{
}
/// <summary>
/// Creates an instance of the <see cref="CommandBreakpointDetails"/> class from the individual
/// pieces of breakpoint information provided by the client.
/// </summary>
/// <param name="name">The name of the command to break on.</param>
/// <param name="condition">Condition string that would be applied to the breakpoint Action parameter.</param>
/// <returns></returns>
public static CommandBreakpointDetails Create(
string name,
string condition = null)
{
Validate.IsNotNull(nameof(name), name);
return new CommandBreakpointDetails {
Name = name,
Condition = condition
};
}
/// <summary>
/// Creates an instance of the <see cref="CommandBreakpointDetails"/> class from a
/// PowerShell CommandBreakpoint object.
/// </summary>
/// <param name="breakpoint">The Breakpoint instance from which details will be taken.</param>
/// <returns>A new instance of the BreakpointDetails class.</returns>
public static CommandBreakpointDetails Create(Breakpoint breakpoint)
{
Validate.IsNotNull("breakpoint", breakpoint);
CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint;
if (commandBreakpoint == null)
{
throw new ArgumentException(
"Unexpected breakpoint type: " + breakpoint.GetType().Name);
}
var breakpointDetails = new CommandBreakpointDetails {
Verified = true,
Name = commandBreakpoint.Command,
Condition = commandBreakpoint.Action?.ToString()
};
return breakpointDetails;
}
}
}
| mit | C# |
27755015c09bad91e9a708af57a9b32d3a6b5c50 | Fix using | binore/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli | src/Metrics.Integrations.Linters/Linters/eslint/Lint.cs | src/Metrics.Integrations.Linters/Linters/eslint/Lint.cs | namespace Metrics.Integrations.Linters.eslint
{
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Extensions;
public class Lint : Linter
{
public override ILinterResult Parse(Stream stream)
{
return new LintResult
{
FilesList = stream.DeserializeAsJson<List<File>>()
};
}
public override ILinterModel Map(ILinterResult result)
{
var model = new LinterFileModel
{
Files = ((LintResult)result).FilesList.Select(file => (LinterFileModel.File) new LinterFile
{
Path = file.FilePath,
ErrorCount = file.ErrorCount,
WarningCount = file.WarningCount,
Errors = file.Messages.Select(fileError => (LinterFileModel.Error) new LinterError
{
Line = fileError.Line,
Message = fileError.MessageError,
Column = new LinterFileModel.Interval
{
Start = fileError.Column
},
Rule = new LinterFileModel.Rule
{
Id = fileError.RuleId
},
Severity = LinterFileModel.Error.SeverityType.error,
NodeType = fileError.NodeType,
Evidence = fileError.Source
}).ToList()
}).ToList()
};
return model;
}
}
} | using System.Runtime.InteropServices.ComTypes;
using Metrics.Integrations.Linters.csslint;
namespace Metrics.Integrations.Linters.eslint
{
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Extensions;
public class Lint : Linter
{
public override ILinterResult Parse(Stream stream)
{
return new LintResult
{
FilesList = stream.DeserializeAsJson<List<File>>()
};
}
public override ILinterModel Map(ILinterResult result)
{
var model = new LinterFileModel
{
Files = ((LintResult)result).FilesList.Select(file => (LinterFileModel.File) new LinterFile
{
Path = file.FilePath,
ErrorCount = file.ErrorCount,
WarningCount = file.WarningCount,
Errors = file.Messages.Select(fileError => (LinterFileModel.Error) new LinterError
{
Line = fileError.Line,
Message = fileError.MessageError,
Column = new LinterFileModel.Interval
{
Start = fileError.Column
},
Rule = new LinterRule
{
Id = fileError.RuleId
},
Severity = LinterFileModel.Error.SeverityType.error,
NodeType = fileError.NodeType,
Evidence = fileError.Source
}).ToList()
}).ToList()
};
return model;
}
}
} | mit | C# |
fa8d0bdac22ee6bbb6fe2860cb7294ab2f98bf6e | Remove stale export | karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS | src/Package/Impl/Sql/Commands/AddDbConnectionCommand.cs | src/Package/Impl/Sql/Commands/AddDbConnectionCommand.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.ProjectSystem;
using Microsoft.VisualStudio.R.Package.ProjectSystem.Configuration;
using Microsoft.Common.Core;
using Microsoft.R.Components.Sql;
using Microsoft.R.Components.InteractiveWorkflow;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Utilities;
#endif
namespace Microsoft.VisualStudio.R.Package.Sql {
internal sealed class AddDbConnectionCommand : ConfigurationSettingCommand {
private readonly IDbConnectionService _dbcs;
public AddDbConnectionCommand(IDbConnectionService dbcs, IProjectSystemServices pss,
IProjectConfigurationSettingsProvider pcsp, IRInteractiveWorkflow workflow) :
base(RPackageCommandId.icmdAddDatabaseConnection, "dbConnection", pss, pcsp, workflow) {
_dbcs = dbcs;
}
protected override void Handle() {
var connString = _dbcs.EditConnectionString(null);
if (!string.IsNullOrWhiteSpace(connString)) {
SaveSetting(connString).DoNotWait();
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.ProjectSystem;
using Microsoft.VisualStudio.R.Package.ProjectSystem.Configuration;
using Microsoft.Common.Core;
using Microsoft.R.Components.Sql;
using Microsoft.R.Components.InteractiveWorkflow;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Utilities;
#endif
namespace Microsoft.VisualStudio.R.Package.Sql {
[ExportCommandGroup("AD87578C-B324-44DC-A12A-B01A6ED5C6E3")]
[AppliesTo(Constants.RtvsProjectCapability)]
internal sealed class AddDbConnectionCommand : ConfigurationSettingCommand {
private readonly IDbConnectionService _dbcs;
public AddDbConnectionCommand(IDbConnectionService dbcs, IProjectSystemServices pss,
IProjectConfigurationSettingsProvider pcsp, IRInteractiveWorkflow workflow) :
base(RPackageCommandId.icmdAddDatabaseConnection, "dbConnection", pss, pcsp, workflow) {
_dbcs = dbcs;
}
protected override void Handle() {
var connString = _dbcs.EditConnectionString(null);
if (!string.IsNullOrWhiteSpace(connString)) {
SaveSetting(connString).DoNotWait();
}
}
}
}
| mit | C# |
e57acb358a60f06ec721eca34853c84870777776 | Include logos as changed/added files in release note | red-gate/Library,red-gate/Library | tools/ReleaseNotesGenerator/ReleaseNotesGenerator.csx | tools/ReleaseNotesGenerator/ReleaseNotesGenerator.csx | var octokit = Require<OctokitPack>();
var client = octokit.Create("Octopus.Library.ReleaseNotesGenerator");
var owner = Env.ScriptArgs[0];
var repo = Env.ScriptArgs[1];
var milestone = Env.ScriptArgs[2];
var state = Env.ScriptArgs[3] != null ? (ItemStateFilter)Enum.Parse(typeof(ItemStateFilter), Env.ScriptArgs[3]) : ItemStateFilter.Open;
bool isTeamCity;
if(!bool.TryParse(Env.ScriptArgs[4], out isTeamCity))
{
isTeamCity = false;
}
async Task<string> BuildGitHubReleaseNotes()
{
var releaseNotesBuilder = new StringBuilder();
var milestones = await client.Issue.Milestone.GetAllForRepository(owner, repo);
var milestoneNumber = milestones.First(m => m.Title == milestone).Number;
var milestoneIssues = await client.Issue.GetAllForRepository(owner, repo, new Octokit.RepositoryIssueRequest { Milestone = milestoneNumber.ToString(), State = state });
if (milestoneIssues.Any())
{
Console.WriteLine($"Found {milestoneIssues.Count()} closed PRs in milestone {milestone}");
foreach (var issue in milestoneIssues)
{
var files = (await client.PullRequest.Files(owner, repo, issue.Number)).Where(f => f.FileName.EndsWith(".json") || f.FileName.EndsWith(".png")).ToList();
var status = "";
var fileNameFormat = "{0}";
if (files.Count() > 1)
{
fileNameFormat = $"[{fileNameFormat}]";
}
var fileNameList = string.Format(fileNameFormat, string.Join(", ", files.Select(f => $"`{f.FileName.Replace("step-templates/", "")}`").ToList()));
status = files.All(f => f.Deletions == 0) ? "New: " : "Improved: ";
releaseNotesBuilder.AppendLine($"- {status}[#{issue.Number}]({issue.HtmlUrl}) - {fileNameList} - {issue.Title} - via @{issue.User.Login}");
}
}
else
{
Console.WriteLine($"Well played sir! There are no closed PRs in milestone {milestone}. Woohoo!");
}
return releaseNotesBuilder.ToString();
}
Console.WriteLine($"Getting all {state} issues in milestone {milestone} of repository {owner}\\{repo}");
var releaseNotes = BuildGitHubReleaseNotes().Result;
if(!isTeamCity)
{
Console.WriteLine(releaseNotes);
}
else
{
var cwd = Directory.GetCurrentDirectory();
var releaseNotesFile = $"{cwd}\\Library_ReleaseNotes.txt";
File.WriteAllText(releaseNotesFile, releaseNotes);
Console.WriteLine($"##teamcity[setParameter name='Library.ReleaseNotesFile' value='{releaseNotesFile}']");
} | var octokit = Require<OctokitPack>();
var client = octokit.Create("Octopus.Library.ReleaseNotesGenerator");
var owner = Env.ScriptArgs[0];
var repo = Env.ScriptArgs[1];
var milestone = Env.ScriptArgs[2];
var state = Env.ScriptArgs[3] != null ? (ItemStateFilter)Enum.Parse(typeof(ItemStateFilter), Env.ScriptArgs[3]) : ItemStateFilter.Open;
bool isTeamCity;
if(!bool.TryParse(Env.ScriptArgs[4], out isTeamCity))
{
isTeamCity = false;
}
async Task<string> BuildGitHubReleaseNotes()
{
var releaseNotesBuilder = new StringBuilder();
var milestones = await client.Issue.Milestone.GetAllForRepository(owner, repo);
var milestoneNumber = milestones.First(m => m.Title == milestone).Number;
var milestoneIssues = await client.Issue.GetAllForRepository(owner, repo, new Octokit.RepositoryIssueRequest { Milestone = milestoneNumber.ToString(), State = state });
if (milestoneIssues.Any())
{
Console.WriteLine($"Found {milestoneIssues.Count()} closed PRs in milestone {milestone}");
foreach (var issue in milestoneIssues)
{
var files = (await client.PullRequest.Files(owner, repo, issue.Number)).Where(f => f.FileName.EndsWith(".json")).ToList();
var status = "";
var fileNameFormat = "{0}";
if (files.Count() > 1)
{
fileNameFormat = $"[{fileNameFormat}]";
}
var fileNameList = string.Format(fileNameFormat, string.Join(", ", files.Select(f => $"`{f.FileName.Replace("step-templates/", "")}`").ToList()));
status = files.All(f => f.Deletions == 0) ? "New: " : "Improved: ";
releaseNotesBuilder.AppendLine($"- {status}[#{issue.Number}]({issue.HtmlUrl}) - {fileNameList} - {issue.Title} - via @{issue.User.Login}");
}
}
else
{
Console.WriteLine($"Well played sir! There are no closed PRs in milestone {milestone}. Woohoo!");
}
return releaseNotesBuilder.ToString();
}
Console.WriteLine($"Getting all {state} issues in milestone {milestone} of repository {owner}\\{repo}");
var releaseNotes = BuildGitHubReleaseNotes().Result;
if(!isTeamCity)
{
Console.WriteLine(releaseNotes);
}
else
{
var cwd = Directory.GetCurrentDirectory();
var releaseNotesFile = $"{cwd}\\Library_ReleaseNotes.txt";
File.WriteAllText(releaseNotesFile, releaseNotes);
Console.WriteLine($"##teamcity[setParameter name='Library.ReleaseNotesFile' value='{releaseNotesFile}']");
} | apache-2.0 | C# |
b0eb5db9cb3e8abdcf7f304c8b9ec1d36e090826 | Edit page description | BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette,honestegg/cassette,andrewdavey/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,honestegg/cassette,damiensawyer/cassette,damiensawyer/cassette | src/Website/Views/Documentation/Configuration_AddFile.cshtml | src/Website/Views/Documentation/Configuration_AddFile.cshtml | @{
ViewBag.Title = "Cassette | Add File";
ViewBag.Description = "How to create a bundle from a single file.";
}
<h1>Add File</h1>
<p>A bundle can be added using a single file, for example, a .less with additional <span class="code-type">@import</span> statements. Each file set can then be a Cassette bundle.</p>
<p>Here's an example structure:</p>
<pre>Content/
- Libraries/
- primary.less
- reset.less
- variables.less
</pre>
<p>Inside of <code>primary.less</code> could exist an <span class="code-type">@import</span> structure:</p>
<pre><code><span class="tag">@import</span> "reset.less";
<span class="tag">@import</span> "variables.less";</code></pre>
<p>By explicitly specifying a file, Cassette only loads that file and the assets specified by that file.</p>
<pre><code><span class="keyword">public</span> <span class="keyword">class</span> <span class="code-type">CassetteConfiguration</span> : <span class="code-type">ICassetteConfiguration</span>
{
<span class="keyword">public</span> <span class="keyword">void</span> Configure(<span class="code-type">BundleCollection</span> bundles, <span class="code-type">CassetteSettings</span> settings)
{
bundles.Add<<span class="code-type">StylesheetBundle</span>>(<span class="string">"Content/Libraries/primary.less"</span>);
}
}</code></pre> | @{
ViewBag.Title = "Cassette | Add File";
ViewBag.Description = "How to add bundles a single file.";
}
<h1>Add File</h1>
<p>A bundle can be added using a single file, for example, a .less with additional <span class="code-type">@import</span> statements. Each file set can then be a Cassette bundle.</p>
<p>Here's an example structure:</p>
<pre>Content/
- Libraries/
- primary.less
- reset.less
- variables.less
</pre>
<p>Inside of <code>primary.less</code> could exist an <span class="code-type">@import</span> structure:</p>
<pre><code><span class="tag">@import</span> "reset.less";
<span class="tag">@import</span> "variables.less";</code></pre>
<p>By explicitly specifying a file, Cassette only loads that file and the assets specified by that file.</p>
<pre><code><span class="keyword">public</span> <span class="keyword">class</span> <span class="code-type">CassetteConfiguration</span> : <span class="code-type">ICassetteConfiguration</span>
{
<span class="keyword">public</span> <span class="keyword">void</span> Configure(<span class="code-type">BundleCollection</span> bundles, <span class="code-type">CassetteSettings</span> settings)
{
bundles.Add<<span class="code-type">StylesheetBundle</span>>(<span class="string">"Content/Libraries/primary.less"</span>);
}
}</code></pre> | mit | C# |
4083803253bc2e28b8c1eb8120fd9a03326839a5 | Update Alexa.NET/Response/Directive/VoicePlayerSpeakDirective.cs | stoiveyp/alexa-skills-dotnet,timheuer/alexa-skills-dotnet | Alexa.NET/Response/Directive/VoicePlayerSpeakDirective.cs | Alexa.NET/Response/Directive/VoicePlayerSpeakDirective.cs | using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Alexa.NET.Response.Directive
{
public class VoicePlayerSpeakDirective : IProgressiveResponseDirective
{
internal VoicePlayerSpeakDirective()
{
}
public VoicePlayerSpeakDirective(Ssml.Speech speech) : this(speech.ToXml())
{
}
public VoicePlayerSpeakDirective(string speech)
{
Speech = speech;
}
[JsonProperty("type")]
public string Type => "VoicePlayer.Speak";
[JsonProperty("speech")]
public string Speech { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Alexa.NET.Response.Directive
{
public class VoicePlayerSpeakDirective : IProgressiveResponseDirective
{
public VoicePlayerSpeakDirective()
{
}
public VoicePlayerSpeakDirective(Ssml.Speech speech) : this(speech.ToXml())
{
}
public VoicePlayerSpeakDirective(string speech)
{
Speech = speech;
}
[JsonProperty("type")]
public string Type => "VoicePlayer.Speak";
[JsonProperty("speech")]
public string Speech { get; }
}
} | mit | C# |
7a8d542478dd3fb1aa7f8bdc1fe3c33bac611602 | change pin | JuergenGutsch/dnc-iot-rpi-demos,JuergenGutsch/dnc-iot-rpi-demos,JuergenGutsch/dnc-iot-rpi-demos | ReadSensors/src/ReadSensors/Controllers/GpioController.cs | ReadSensors/src/ReadSensors/Controllers/GpioController.cs | using Microsoft.AspNet.Mvc;
using Raspberry.IO.GeneralPurpose;
using Raspberry.IO.GeneralPurpose.Behaviors;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace ReadSensors.Controllers
{
public class GpioController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Gpio11On()
{
var led1 = ConnectorPin.P1Pin11.Output();
var connection = new GpioConnection(led1);
connection.Open();
connection.Toggle(led1);
connection.Close();
return Json(new { Gpio11On = true });
}
[HttpPost]
public JsonResult Gpio11Off()
{
var led1 = ConnectorPin.P1Pin11.Output();
var connection = new GpioConnection(led1);
connection.Open();
connection.Toggle(led1);
connection.Close();
return Json(new { Gpio11On = false });
}
}
}
| using Microsoft.AspNet.Mvc;
using Raspberry.IO.GeneralPurpose;
using Raspberry.IO.GeneralPurpose.Behaviors;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace ReadSensors.Controllers
{
public class GpioController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Gpio11On()
{
var led1 = ConnectorPin.P1Pin11.Output();
using (var connection = new GpioConnection(led1))
{
connection.Toggle(led1);
}
return Json(new { Gpio11On = true});
}
[HttpPost]
public JsonResult Gpio11Off()
{
var led1 = ConnectorPin.P1Pin11.Output();
using (var connection = new GpioConnection(led1))
{
connection.Toggle(led1);
}
return Json(new { Gpio11On = false });
}
}
}
| mit | C# |
0dac376d10b7414febbbd06937ba0342f9d74d9d | Fix using statements | lou1306/CIV,lou1306/CIV | CIV.Formats/Caal.cs | CIV.Formats/Caal.cs | using System.Linq;
using System.IO;
using System.Collections.Generic;
using CIV.Ccs;
using CIV.Hml;
using Newtonsoft.Json.Linq;
namespace CIV.Formats
{
public class Caal
{
public string Extension => "caal";
public string Name { get; set; }
public IDictionary<string, CcsProcess> Processes { get; private set; }
public IDictionary<HmlFormula, CcsProcess> Formulae { get; private set; }
public Caal Load(string path)
{
var text = File.ReadAllText(path);
var json = JObject.Parse(text);
Name = (string)json["title"];
Processes = CcsFacade.ParseAll((string)json["ccs"]);
Formulae = json["properties"]
.Where(x => (string)x["className"] == "HML" &&
(string)x["options"]["definitions"] == "")
.ToDictionary(
x => HmlFacade.ParseAll((string)x["options"]["topFormula"]),
x => Processes[(string)x["options"]["process"]]
);
return this;
}
}
}
| using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using CIV.Ccs;
using CIV.Hml;
using Newtonsoft.Json.Linq;
namespace CIV.Formats
{
public class Caal
{
public string Extension => "caal";
public string Name { get; set; }
public IDictionary<string, CcsProcess> Processes { get; private set; }
public IDictionary<HmlFormula, CcsProcess> Formulae { get; private set; }
public Caal Load(string path)
{
var text = File.ReadAllText(path);
var json = JObject.Parse(text);
Name = (string)json["title"];
Processes = CcsFacade.ParseAll((string)json["ccs"]);
Formulae = json["properties"]
.Where(x => (string)x["className"] == "HML" &&
(string)x["options"]["definitions"] == "")
.ToDictionary(
x => HmlFacade.ParseAll((string)x["options"]["topFormula"]),
x => Processes[(string)x["options"]["process"]]
);
return this;
}
}
}
| mit | C# |
8cf35ded622930cf18cffee8d744b1402488acb3 | Add missing method | NinetailLabs/Cake.VersionReader | Cake.VersionReader/Cake.VersionReader/VersionReaderAliases.cs | Cake.VersionReader/Cake.VersionReader/VersionReaderAliases.cs | using System.Reflection;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.IO;
namespace Cake.VersionReader
{
/// <summary>
/// Version Reader Aliases
/// </summary>
[CakeAliasCategory("Version Reader")]
public static class VersionReaderAliases
{
/// <summary>
/// Get the version number from an assembly.
/// </summary>
/// <param name="context">The context</param>
/// <param name="file">The binary to read from</param>
/// <returns>Version number in the format '0.0.0.0'</returns>
[CakeMethodAlias]
public static string GetVersionNumber(this ICakeContext context, FilePath file)
{
var filePath = file.MakeAbsolute(context.Environment).FullPath;
var version = AssemblyName.GetAssemblyName(filePath).Version;
return $"{version.Major}.{version.Minor}.{version.Build}";
}
/// <summary>
/// Get the version number with the current build number appended.
/// This is based on the article found here: http://www.xavierdecoster.com/semantic-versioning-auto-incremented-nuget-package-versions
/// </summary>
/// <param name="context">The context</param>
/// <param name="file">The binary to read from</param>
/// <param name="buildNumber">The build number as provided by the build serveer</param>
/// <returns>Version number in the format '0.0.0.0-CI00000'</returns>
[CakeMethodAlias]
public static string GetVersionNumberWithContinuesIntegrationNumberAppended(this ICakeContext context, FilePath file, int buildNumber)
{
var filePath = file.MakeAbsolute(context.Environment).FullPath;
var version = AssemblyName.GetAssemblyName(filePath).Version;
var adjustedVersion = $"{version.Major}.{version.Minor}.{version.Build}-CI{buildNumber.ToString("00000")}";
return adjustedVersion;
}
}
} | using System.Reflection;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.IO;
namespace Cake.VersionReader
{
/// <summary>
/// Version Reader Aliases
/// </summary>
[CakeAliasCategory("Version Reader")]
public static class VersionReaderAliases
{
/// <summary>
/// Get the version number from an assembly.
/// </summary>
/// <param name="context">The context</param>
/// <param name="file">The binary to read from</param>
/// <returns>Version number in the format '0.0.0.0'</returns>
[CakeMethodAlias]
public static string GetVersionNumber(this ICakeContext context, FilePath file)
{
var filePath = file.MakeAbsolute(context.Environment).FullPath;
var version = AssemblyName.GetAssemblyName(filePath).Version;
return $"{version.Major}.{version.Minor}.{version.Build}";
}
/// <summary>
/// Get the version number with the current build number appended.
/// This is based on the article found here: http://www.xavierdecoster.com/semantic-versioning-auto-incremented-nuget-package-versions
/// </summary>
/// <param name="context">The context</param>
/// <param name="file">The binary to read from</param>
/// <param name="buildNumber">The build number as provided by the build serveer</param>
/// <returns>Version number in the format '0.0.0.0-CI00000'</returns>
public static string GetVersionNumberWithContinuesIntegrationNumberAppended(this ICakeContext context, FilePath file, int buildNumber)
{
var filePath = file.MakeAbsolute(context.Environment).FullPath;
var version = AssemblyName.GetAssemblyName(filePath).Version;
var adjustedVersion = $"{version.Major}.{version.Minor}.{version.Build}-CI{buildNumber.ToString("00000")}";
return adjustedVersion;
}
}
} | mit | C# |
8e133e47d80c62d6321b7c030c8b6f33f8e7710c | Add loading of .pll in NdapiModule.Open | felipebz/ndapi | Ndapi/NdapiModule.cs | Ndapi/NdapiModule.cs | using System.IO;
using Ndapi.Core.Handles;
namespace Ndapi
{
public abstract class NdapiModule : NdapiObject
{
internal NdapiModule()
{
}
internal NdapiModule(ObjectSafeHandle handle) : base(handle)
{
}
public static NdapiModule Open(string filename)
{
var extension = Path.GetExtension(filename).ToUpper(); ;
switch (extension)
{
case ".FMB":
return FormModule.Open(filename);
case ".OLB":
return ObjectLibrary.Open(filename);
case ".MMB":
return MenuModule.Open(filename);
case ".PLL":
return LibraryModule.Open(filename);
default:
throw new NdapiException(string.Format("The file {0} does not have a valid extension.", filename));
}
}
public abstract void Save(string path = null, bool saveInDatabase = false);
public abstract void CompileFile();
public abstract void CompileObjects();
}
}
| using System.IO;
using Ndapi.Core.Handles;
namespace Ndapi
{
public abstract class NdapiModule : NdapiObject
{
internal NdapiModule()
{
}
internal NdapiModule(ObjectSafeHandle handle) : base(handle)
{
}
public static NdapiModule Open(string filename)
{
var extension = Path.GetExtension(filename).ToUpper(); ;
switch (extension)
{
case ".FMB":
return FormModule.Open(filename);
case ".OLB":
return ObjectLibrary.Open(filename);
case ".MMB":
return MenuModule.Open(filename);
default:
throw new NdapiException(string.Format("The file {0} does not have a valid extension.", filename));
}
}
public abstract void Save(string path = null, bool saveInDatabase = false);
public abstract void CompileFile();
public abstract void CompileObjects();
}
}
| mit | C# |
7316b1eb18f3f2ff8b2f7d53f9b37586cecbde1b | Add the setting to skip Azure metrics for WASB in SharkNodeBase. Which solves the exception I always got when closing the connection. | mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee | Libraries/Microsoft.Experimental.Azure.Spark/SharkNodeBase.cs | Libraries/Microsoft.Experimental.Azure.Spark/SharkNodeBase.cs | using Microsoft.Experimental.Azure.JavaPlatform;
using Microsoft.Experimental.Azure.Spark;
using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Experimental.Azure.Spark
{
/// <summary>
/// The base class for a typical Azure Shark node.
/// </summary>
public abstract class SharkNodeBase : SharkSparkNodeBase
{
private SharkRunner _sharkRunner;
/// <summary>
/// Overrides the Run method to run Shark.
/// </summary>
protected sealed override void GuardedRun()
{
_sharkRunner.RunSharkServer2();
}
/// <summary>
/// Overrides initialization to setup Shark.
/// </summary>
protected sealed override void PostJavaInstallInitialize()
{
InstallShark();
}
/// <summary>
/// Configure the Hadoop-side properties of Shark, to e.g. give WASB keys.
/// </summary>
/// <returns>The properties.</returns>
protected abstract ImmutableDictionary<string, string> GetHadoopConfigProperties();
private void InstallShark()
{
var master = DiscoverMasterNode();
Trace.TraceInformation("Master node we'll use: " + master);
var metastore = DiscoverMetastoreNode();
Trace.TraceInformation("Metastore node we'll use: " + master);
var config = new SharkConfig(
serverPort: 8082,
metastoreUris: "thrift://" + metastore + ":9083",
sparkMaster: "spark://" + master + ":8081",
extraHiveConfig:
GetHadoopConfigProperties()
.Add( "fs.azure.skip.metrics", "true")
.Add("hive.exec.local.scratchdir", "C:/Resources/temp/HiveScratch")
.Add("hive.querylog.location", Path.Combine(InstallDirectory, "Shark", "QueryHistory")));
_sharkRunner = new SharkRunner(
resourceFileDirectory: SparkResourceDirectory,
sharkHome: Path.Combine(InstallDirectory, "Shark"),
javaHome: JavaHome,
config: config);
_sharkRunner.Setup();
}
/// <summary>
/// Get the IP address for the Spark master node.
/// </summary>
/// <returns>Default implementation returns the first instance in the "SparkMaster" role.</returns>
protected virtual string DiscoverMasterNode()
{
if (RoleEnvironment.IsEmulated)
{
return "localhost";
}
return RoleEnvironment.Roles["SparkMaster"].Instances
.Select(GetIPAddress)
.First();
}
/// <summary>
/// Get the IP address for the Hive metastore node.
/// </summary>
/// <returns>Default implementation returns the first instance in the "HiveMetastore" role.</returns>
protected virtual string DiscoverMetastoreNode()
{
if (RoleEnvironment.IsEmulated)
{
return "localhost";
}
return RoleEnvironment.Roles["HiveMetastore"].Instances
.Select(GetIPAddress)
.First();
}
}
}
| using Microsoft.Experimental.Azure.JavaPlatform;
using Microsoft.Experimental.Azure.Spark;
using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Experimental.Azure.Spark
{
/// <summary>
/// The base class for a typical Azure Shark node.
/// </summary>
public abstract class SharkNodeBase : SharkSparkNodeBase
{
private SharkRunner _sharkRunner;
/// <summary>
/// Overrides the Run method to run Shark.
/// </summary>
protected sealed override void GuardedRun()
{
_sharkRunner.RunSharkServer2();
}
/// <summary>
/// Overrides initialization to setup Shark.
/// </summary>
protected sealed override void PostJavaInstallInitialize()
{
InstallShark();
}
/// <summary>
/// Configure the Hadoop-side properties of Shark, to e.g. give WASB keys.
/// </summary>
/// <returns>The properties.</returns>
protected abstract ImmutableDictionary<string, string> GetHadoopConfigProperties();
private void InstallShark()
{
var master = DiscoverMasterNode();
Trace.TraceInformation("Master node we'll use: " + master);
var metastore = DiscoverMetastoreNode();
Trace.TraceInformation("Metastore node we'll use: " + master);
var config = new SharkConfig(
serverPort: 8082,
metastoreUris: "thrift://" + metastore + ":9083",
sparkMaster: "spark://" + master + ":8081",
extraHiveConfig:
GetHadoopConfigProperties()
.Add("hive.exec.local.scratchdir", "C:/Resources/temp/HiveScratch")
.Add("hive.querylog.location", Path.Combine(InstallDirectory, "Shark", "QueryHistory")));
_sharkRunner = new SharkRunner(
resourceFileDirectory: SparkResourceDirectory,
sharkHome: Path.Combine(InstallDirectory, "Shark"),
javaHome: JavaHome,
config: config);
_sharkRunner.Setup();
}
/// <summary>
/// Get the IP address for the Spark master node.
/// </summary>
/// <returns>Default implementation returns the first instance in the "SparkMaster" role.</returns>
protected virtual string DiscoverMasterNode()
{
if (RoleEnvironment.IsEmulated)
{
return "localhost";
}
return RoleEnvironment.Roles["SparkMaster"].Instances
.Select(GetIPAddress)
.First();
}
/// <summary>
/// Get the IP address for the Hive metastore node.
/// </summary>
/// <returns>Default implementation returns the first instance in the "HiveMetastore" role.</returns>
protected virtual string DiscoverMetastoreNode()
{
if (RoleEnvironment.IsEmulated)
{
return "localhost";
}
return RoleEnvironment.Roles["HiveMetastore"].Instances
.Select(GetIPAddress)
.First();
}
}
}
| mit | C# |
47390435ad51c85eec564e961f4f90bfc9159245 | fix yaml tests | aloneguid/config | src/Config.Net.Tests/Stores/YamlFileConfigStoreTest.cs | src/Config.Net.Tests/Stores/YamlFileConfigStoreTest.cs | using Config.Net.Stores;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace Config.Net.Tests.Stores
{
public class YamlFileConfigStoreTest : AbstractTestFixture
{
private YamlFileConfigStore _yaml;
public YamlFileConfigStoreTest()
{
var testFile = @"..\..\..\..\..\appveyor.yml";
_yaml = new YamlFileConfigStore(testFile);
}
[Fact]
public void Can_read_simple_property()
{
string image = _yaml.Read("image");
Assert.Equal("Visual Studio 2017", image);
}
[Fact]
public void Can_read_nested_node()
{
string project = _yaml.Read("build.project");
Assert.Equal("src/Config.Net.sln", project);
}
}
} | using Config.Net.Stores;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace Config.Net.Tests.Stores
{
public class YamlFileConfigStoreTest : AbstractTestFixture
{
private YamlFileConfigStore _yaml;
public YamlFileConfigStoreTest()
{
var testFile = @"..\..\..\..\..\appveyor.yml";
_yaml = new YamlFileConfigStore(testFile);
}
[Fact]
public void Can_read_simple_property()
{
string image = _yaml.Read("image");
Assert.Equal("Visual Studio 2017", image);
}
[Fact]
public void Can_read_nested_node()
{
string project = _yaml.Read("build.project");
Assert.Equal("src/Config.Net.sln", project);
}
[Fact]
public void Can_read_multiline()
{
string cmd = _yaml.Read("test_script.cmd");
Assert.Equal(@"cd src\Config.Net.Tests
dotnet test
cd ..\..", cmd, false, true, true);
}
}
} | mit | C# |
f052cdaa985fe2f33588816f9c7479f681d63fa1 | update version file. | Aaron-Liu/enode,tangxuehua/enode | src/Extensions/ENode.EQueue/Properties/AssemblyInfo.cs | src/Extensions/ENode.EQueue/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("ENode.EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ENode.EQueue")]
[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("e534ee24-4ea0-410e-847a-227e53faed7c")]
// 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.1.5")]
[assembly: AssemblyFileVersion("1.1.5")]
| 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("ENode.EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ENode.EQueue")]
[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("e534ee24-4ea0-410e-847a-227e53faed7c")]
// 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.1.2")]
[assembly: AssemblyFileVersion("1.1.2")]
| mit | C# |
8701377ef91cb119c858820ef12d33ed59140eed | Remove NotImplementedException from CreateTable() | lecaillon/foundation | src/Foundation/Migrations/Builders/MigrationBuilder.cs | src/Foundation/Migrations/Builders/MigrationBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Foundation.Metadata;
using Foundation.Migrations.Operations;
using Foundation.Utilities;
namespace Foundation.Migrations.Builders
{
public class MigrationBuilder
{
public virtual List<MigrationOperation> Operations { get; } = new List<MigrationOperation>();
protected virtual CreateTableBuilder CreateTable(Entity entity)
{
Check.NotNull(entity, nameof(entity));
string schema = string.Empty;
string name = string.Empty;
var createTableOperation = new CreateTableOperation
{
Schema = schema,
Name = name
};
var builder = new CreateTableBuilder(createTableOperation);
builder.PrimaryKey("", entity.FindDeclaredPrimaryKey());
Operations.Add(createTableOperation);
return builder;
}
protected virtual OperationBuilder<AlterTableOperation> AlterTable(string name, string schema = null)
{
Check.NotEmpty(name, nameof(name));
var operation = new AlterTableOperation
{
Schema = schema,
Name = name
};
Operations.Add(operation);
return new OperationBuilder<AlterTableOperation>(operation);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Foundation.Metadata;
using Foundation.Migrations.Operations;
using Foundation.Utilities;
namespace Foundation.Migrations.Builders
{
public class MigrationBuilder
{
public virtual List<MigrationOperation> Operations { get; } = new List<MigrationOperation>();
protected virtual CreateTableBuilder CreateTable(Entity entity)
{
Check.NotNull(entity, nameof(entity));
string schema = string.Empty;
string name = string.Empty;
var createTableOperation = new CreateTableOperation
{
Schema = schema,
Name = name
};
var builder = new CreateTableBuilder(createTableOperation);
builder.PrimaryKey("", entity.FindDeclaredPrimaryKey());
Operations.Add(createTableOperation);
throw new NotImplementedException();
}
protected virtual OperationBuilder<AlterTableOperation> AlterTable(string name, string schema = null)
{
Check.NotEmpty(name, nameof(name));
var operation = new AlterTableOperation
{
Schema = schema,
Name = name
};
Operations.Add(operation);
return new OperationBuilder<AlterTableOperation>(operation);
}
}
}
| mit | C# |
2acf4ee2ab65634bc05fabe5ad5e1e71181b8ea5 | Add TracingConfig to catch error | nandotech/NancyAzureFileUpload | src/NancyAzureFileUpload/Helpers/CustomBootstrapper.cs | src/NancyAzureFileUpload/Helpers/CustomBootstrapper.cs | using Microsoft.Extensions.Configuration;
using Nancy;
using Nancy.TinyIoc;
using NancyAzureFileUpload.Services;
namespace NancyAzureFileUpload.Helpers
{
public class CustomBootstrapper : DefaultNancyBootstrapper
{
public IConfigurationRoot Configuration;
public CustomBootstrapper()
{
var builder = new ConfigurationBuilder()
.SetBasePath(RootPathProvider.GetRootPath())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
var tracingConfig = new TraceConfiguration(true, true);
Configuration = builder.Build();
}
protected override void ConfigureApplicationContainer(TinyIoCContainer ctr)
{
ctr.Register<IConfiguration>(Configuration);
ctr.Register<IDispatchFileService, DispatchFileService>();
}
}
} | using Microsoft.Extensions.Configuration;
using Nancy;
using Nancy.TinyIoc;
using NancyAzureFileUpload.Services;
namespace NancyAzureFileUpload.Helpers
{
public class CustomBootstrapper : DefaultNancyBootstrapper
{
public IConfigurationRoot Configuration;
public CustomBootstrapper()
{
var builder = new ConfigurationBuilder()
.SetBasePath(RootPathProvider.GetRootPath())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
protected override void ConfigureApplicationContainer(TinyIoCContainer ctr)
{
ctr.Register<IConfiguration>(Configuration);
ctr.Register<IDispatchFileService, DispatchFileService>();
}
}
} | mit | C# |
4554236012c4dc19767f2f0efd56a00adf8184d2 | Update ActionCollection.cs | XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors | src/Avalonia.Xaml.Interactivity/ActionCollection.cs | src/Avalonia.Xaml.Interactivity/ActionCollection.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Specialized;
using Avalonia.Collections;
namespace Avalonia.Xaml.Interactivity
{
/// <summary>
/// Represents a collection of <see cref="IAction"/>'s.
/// </summary>
public sealed class ActionCollection : AvaloniaList<AvaloniaObject>
{
/// <summary>
/// Initializes a new instance of the <see cref="ActionCollection"/> class.
/// </summary>
public ActionCollection()
{
CollectionChanged += ActionCollection_CollectionChanged;
}
private void ActionCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs eventArgs)
{
NotifyCollectionChangedAction collectionChange = eventArgs.Action;
if (collectionChange == NotifyCollectionChangedAction.Reset)
{
foreach (AvaloniaObject item in this)
{
VerifyType(item);
}
}
else if (collectionChange == NotifyCollectionChangedAction.Add || collectionChange == NotifyCollectionChangedAction.Replace)
{
AvaloniaObject changedItem = (AvaloniaObject)eventArgs.NewItems[0];
VerifyType(changedItem);
}
}
private static void VerifyType(AvaloniaObject item)
{
if (!(item is IAction))
{
throw new InvalidOperationException("Only IAction types are supported in an ActionCollection.");
}
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Specialized;
using Avalonia.Collections;
namespace Avalonia.Xaml.Interactivity
{
/// <summary>
/// Represents a collection of <see cref="IAction"/>.
/// </summary>
public sealed class ActionCollection : AvaloniaList<AvaloniaObject>
{
/// <summary>
/// Initializes a new instance of the <see cref="ActionCollection"/> class.
/// </summary>
public ActionCollection()
{
CollectionChanged += ActionCollection_CollectionChanged;
}
private void ActionCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs eventArgs)
{
NotifyCollectionChangedAction collectionChange = eventArgs.Action;
if (collectionChange == NotifyCollectionChangedAction.Reset)
{
foreach (AvaloniaObject item in this)
{
VerifyType(item);
}
}
else if (collectionChange == NotifyCollectionChangedAction.Add || collectionChange == NotifyCollectionChangedAction.Replace)
{
AvaloniaObject changedItem = (AvaloniaObject)eventArgs.NewItems[0];
VerifyType(changedItem);
}
}
private static void VerifyType(AvaloniaObject item)
{
if (!(item is IAction))
{
throw new InvalidOperationException("Only IAction types are supported in an ActionCollection.");
}
}
}
}
| mit | C# |
c91ab16eecbedefefad6817e74e21c99b5c236b9 | add resolvebyname attribute to labels target property. | jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia | src/Avalonia.Controls/Label.cs | src/Avalonia.Controls/Label.cs | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace Avalonia.Controls
{
/// <summary>
/// Label control. Focuses <see cref="Target"/> on pointer click or access key press (Alt + accessKey)
/// </summary>
public class Label : ContentControl
{
/// <summary>
/// Defines the <see cref="Target"/> Direct property
/// </summary>
public static readonly DirectProperty<Label, IInputElement> TargetProperty =
AvaloniaProperty.RegisterDirect<Label, IInputElement>(nameof(Target), lbl => lbl.Target, (lbl, inp) => lbl.Target = inp);
/// <summary>
/// Label focus target storage field
/// </summary>
private IInputElement _target;
/// <summary>
/// Label focus Target
/// </summary>
[ResolveByName]
public IInputElement Target
{
get => _target;
set => SetAndRaise(TargetProperty, ref _target, value);
}
static Label()
{
AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Label>((lbl, args) => lbl.LabelActivated(args));
// IsTabStopProperty.OverrideDefaultValue<Label>(false)
FocusableProperty.OverrideDefaultValue<Label>(false);
}
/// <summary>
/// Initializes instance of <see cref="Label"/> control
/// </summary>
public Label()
{
}
/// <summary>
/// Method which focuses <see cref="Target"/> input element
/// </summary>
private void LabelActivated(RoutedEventArgs args)
{
Target?.Focus();
args.Handled = Target != null;
}
/// <summary>
/// Handler of <see cref="IInputElement.PointerPressed"/> event
/// </summary>
/// <param name="e">Event Arguments</param>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.PointerUpdateKind == PointerUpdateKind.LeftButtonPressed)
{
LabelActivated(e);
}
base.OnPointerPressed(e);
}
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace Avalonia.Controls
{
/// <summary>
/// Label control. Focuses <see cref="Target"/> on pointer click or access key press (Alt + accessKey)
/// </summary>
public class Label : ContentControl
{
/// <summary>
/// Defines the <see cref="Target"/> Direct property
/// </summary>
public static readonly DirectProperty<Label, IInputElement> TargetProperty =
AvaloniaProperty.RegisterDirect<Label, IInputElement>(nameof(Target), lbl => lbl.Target, (lbl, inp) => lbl.Target = inp);
/// <summary>
/// Label focus target storage field
/// </summary>
private IInputElement _target;
/// <summary>
/// Label focus Target
/// </summary>
public IInputElement Target
{
get => _target;
set => SetAndRaise(TargetProperty, ref _target, value);
}
static Label()
{
AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Label>((lbl, args) => lbl.LabelActivated(args));
// IsTabStopProperty.OverrideDefaultValue<Label>(false)
FocusableProperty.OverrideDefaultValue<Label>(false);
}
/// <summary>
/// Initializes instance of <see cref="Label"/> control
/// </summary>
public Label()
{
}
/// <summary>
/// Method which focuses <see cref="Target"/> input element
/// </summary>
private void LabelActivated(RoutedEventArgs args)
{
Target?.Focus();
args.Handled = Target != null;
}
/// <summary>
/// Handler of <see cref="IInputElement.PointerPressed"/> event
/// </summary>
/// <param name="e">Event Arguments</param>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (e.GetCurrentPoint(this).Properties.PointerUpdateKind == PointerUpdateKind.LeftButtonPressed)
{
LabelActivated(e);
}
base.OnPointerPressed(e);
}
}
}
| mit | C# |
a552e69e1b8c94bc6ca0150810425e3807171e06 | use command parameter to specify test name | Simply360/tSQLt.NET | TsqltNet/SqlTestExecutor.cs | TsqltNet/SqlTestExecutor.cs | using System.Data;
using System.Data.SqlClient;
namespace TsqltNet
{
public class SqlTestExecutor : ISqlTestExecutor
{
public void RunTest(SqlConnection sqlConnection, string testName)
{
using (var sqlCommand = CreateCommand(testName, sqlConnection))
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
protected virtual SqlCommand CreateCommand(string testName, SqlConnection sqlConnection)
{
const string sql = "exec tSQLt.Run @TestName";
var command = new SqlCommand(sql, sqlConnection);
var param = new SqlParameter("TestName", SqlDbType.NVarChar) {Value = testName};
command.Parameters.Add(param);
return command;
}
}
} | using System.Data;
using System.Data.SqlClient;
namespace TsqltNet
{
public class SqlTestExecutor : ISqlTestExecutor
{
public void RunTest(SqlConnection sqlConnection, string testName)
{
var sql = GetTestExecutionCommandSql(testName);
using (var sqlCommand = new SqlCommand(sql, sqlConnection))
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
protected virtual string GetTestExecutionCommandSql(string testName)
{
return $"exec tSQLt.Run '{testName}'";
}
}
} | mit | C# |
6ca33d54f645977ccfe00407a92ea4107fb796c6 | Update LoginForm.cs | redeqn/RedConn | RedConn/LoginForm.cs | RedConn/LoginForm.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace RedConn
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
IE.Navigate("https://150617-dot-starkappcloud.appspot.com/app/?api=1");
while (IE.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
public void ShowLogin()
{
IE.Refresh();
mShowAllowed = true;
this.ShowDialog();
}
private bool mShowAllowed = false;
protected override void SetVisibleCore(bool value)
{
if (!mShowAllowed) value = false;
base.SetVisibleCore(value);
}
public WebBrowser Explorer
{
get { return this.IE; }
}
private void Browser_Load(object sender, EventArgs e)
{
}
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
this.Hide();
e.Cancel = true;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace RedConn
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
IE.Navigate("https://150617-dot-starkappcloud.appspot.com/app/?api=1");
while (IE.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
public void ShowLogin()
{
IE.Refresh()
mShowAllowed = true;
this.ShowDialog();
}
private bool mShowAllowed = false;
protected override void SetVisibleCore(bool value)
{
if (!mShowAllowed) value = false;
base.SetVisibleCore(value);
}
public WebBrowser Explorer
{
get { return this.IE; }
}
private void Browser_Load(object sender, EventArgs e)
{
}
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
this.Hide();
e.Cancel = true;
}
}
}
}
| mit | C# |
f15684995b3bb0ca1e9929988c26c128379a50ba | add the hyphenated words instead of replacing. | sciolist/Lucene.Net.Analysis.Hyphenation | Lucene.Net.Analysis.Hyphenation/HyphenationTokenFilter.cs | Lucene.Net.Analysis.Hyphenation/HyphenationTokenFilter.cs | using System.Collections.Generic;
using Lucene.Net.Analysis.Tokenattributes;
namespace Lucene.Net.Analysis.Hyphenation
{
public class HyphenationTokenFilter : TokenFilter
{
private readonly Hyphenator _hyphenator;
private readonly TermAttribute _termAtt;
private readonly TypeAttribute _typeAtt;
private readonly OffsetAttribute _ofsAtt;
public HyphenationTokenFilter(TokenStream input, Hyphenator hyphenator)
: base(input)
{
_hyphenator = hyphenator;
_termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute));
_typeAtt = (TypeAttribute)AddAttribute(typeof(TypeAttribute));
_ofsAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute));
}
private readonly Queue<WordPart> _terms = new Queue<WordPart>();
private int _startOfs;
private bool SetNextTerm()
{
if (_terms.Count == 0) return false;
var nextTerm = _terms.Dequeue();
_termAtt.SetTermLength(nextTerm.Text.Length);
_termAtt.SetTermBuffer(nextTerm.Text);
_ofsAtt.SetOffset(_startOfs + nextTerm.Start, _startOfs + nextTerm.End);
_typeAtt.SetType("<ALPHANUM>");
return true;
}
public override bool IncrementToken()
{
if (SetNextTerm()) return true;
if (!input.IncrementToken()) return false;
_startOfs = _ofsAtt.StartOffset();
var term = _termAtt.Term();
foreach (var newWord in _hyphenator.HyphenateWord(term))
{
_terms.Enqueue(newWord);
}
return true;
}
}
} | using System.Collections.Generic;
using Lucene.Net.Analysis.Tokenattributes;
namespace Lucene.Net.Analysis.Hyphenation
{
public class HyphenationTokenFilter : TokenFilter
{
private readonly Hyphenator _hyphenator;
private readonly TermAttribute _termAtt;
private readonly TypeAttribute _typeAtt;
private readonly OffsetAttribute _ofsAtt;
public HyphenationTokenFilter(TokenStream input, Hyphenator hyphenator)
: base(input)
{
_hyphenator = hyphenator;
_termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute));
_typeAtt = (TypeAttribute)AddAttribute(typeof(TypeAttribute));
_ofsAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute));
}
private readonly Queue<WordPart> _terms = new Queue<WordPart>();
private int _startOfs;
private bool SetNextTerm()
{
if (_terms.Count == 0) return false;
var nextTerm = _terms.Dequeue();
_termAtt.SetTermLength(nextTerm.Text.Length);
_termAtt.SetTermBuffer(nextTerm.Text);
_ofsAtt.SetOffset(_startOfs + nextTerm.Start, _startOfs + nextTerm.End);
_typeAtt.SetType("<ALPHANUM>");
return true;
}
public override bool IncrementToken()
{
if (SetNextTerm()) return true;
if (!input.IncrementToken()) return false;
_startOfs = _ofsAtt.StartOffset();
var term = _termAtt.Term();
foreach (var newWord in _hyphenator.HyphenateWord(term))
{
_terms.Enqueue(newWord);
}
SetNextTerm();
return true;
}
}
} | mit | C# |
c7abc6eea9deb4ab4656b520fec29012f1bf1d5c | update assembly info | jobeland/GeneticAlgorithm | NeuralNetwork.GeneticAlgorithm/Properties/AssemblyInfo.cs | NeuralNetwork.GeneticAlgorithm/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("NeuralNetwork.GeneticAlgorithm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NeuralNetwork.GeneticAlgorithm")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb0c5189-7fc1-4d26-8f4d-5e66b1d0217d")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NeuralNetwork.GeneticAlgorithm")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NeuralNetwork.GeneticAlgorithm")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb0c5189-7fc1-4d26-8f4d-5e66b1d0217d")]
// 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.0.2.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
| mit | C# |
ba379bb1b9892397da40ac3430a5b415744d9062 | Update version number | eylvisaker/AgateLib | src/Properties/AssemblyInfo.cs | src/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AgateLib Game Programming Library")]
[assembly: AssemblyDescription("Platform Independent Game Programming Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ERY")]
[assembly: AssemblyProduct("AgateLib")]
[assembly: AssemblyCopyright("Copyright © 2006")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a671f4e2-e579-42b3-aae4-9beb962581ff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AgateLib Game Programming Library")]
[assembly: AssemblyDescription("Platform Independent Game Programming Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ERY")]
[assembly: AssemblyProduct("AgateLib")]
[assembly: AssemblyCopyright("Copyright © 2006")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a671f4e2-e579-42b3-aae4-9beb962581ff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.2.6.0")]
[assembly: AssemblyFileVersion("0.2.6.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| mit | C# |
e47d234416dd9734c317a1f5170b3bac0babeecc | Revert "Revert "LoginTest is completed"" | oleksandrp1/SeleniumTasks | SeleniumTasksProject1.1/SeleniumTasksProject1.1/Chrome.cs | SeleniumTasksProject1.1/SeleniumTasksProject1.1/Chrome.cs | using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
namespace SeleniumTasksProject1._1
{
[TestFixture]
public class Chrome
{
private IWebDriver driver;
private WebDriverWait wait;
[SetUp]
public void start()
{
driver = new ChromeDriver();
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
}
[Test]
public void LoginTestInChrome()
{
driver.Url = "http://localhost:8082/litecart/admin/";
driver.FindElement(By.Name("username")).SendKeys("admin");
driver.FindElement(By.Name("password")).SendKeys("admin");
driver.FindElement(By.Name("login")).Click();
//wait.Until(ExpectedConditions.TitleIs("My Store"));
}
[TearDown]
public void stop()
{
driver.Quit();
driver = null;
}
}
}
| using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
namespace SeleniumTasksProject1._1
{
[TestFixture]
public class Chrome
{
private IWebDriver driver;
private WebDriverWait wait;
[SetUp]
public void start()
{
driver = new ChromeDriver();
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
}
[Test]
public void LoginTestInChrome()
{
driver.Url = "http://localhost:8082/litecart/admin/";
}
[TearDown]
public void stop()
{
driver.Quit();
driver = null;
}
}
}
| apache-2.0 | C# |
8c5b95e8c7b19dc6773749da3a6d1554191d6aa3 | Modify to adapt to on/off change of adaptive brightness | emoacht/Monitorian | Source/Monitorian.Core/Models/Monitor/WmiMonitorItem.cs | Source/Monitorian.Core/Models/Monitor/WmiMonitorItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monitorian.Core.Helper;
namespace Monitorian.Core.Models.Monitor
{
/// <summary>
/// Physical monitor managed by WMI (internal monitor)
/// </summary>
internal class WmiMonitorItem : MonitorItem
{
private readonly byte[] _brightnessLevels;
private readonly bool _isRemovable;
public WmiMonitorItem(
string deviceInstanceId,
string description,
byte displayIndex,
byte monitorIndex,
byte[] brightnessLevels,
bool isRemovable) : base(
deviceInstanceId: deviceInstanceId,
description: description,
displayIndex: displayIndex,
monitorIndex: monitorIndex,
isAccessible: true)
{
this._brightnessLevels = brightnessLevels ?? throw new ArgumentNullException(nameof(brightnessLevels));
this._isRemovable = isRemovable;
}
private readonly object _lock = new object();
public override bool UpdateBrightness(int brightness = -1)
{
lock (_lock)
{
if (_isRemovable)
{
this.Brightness = (0 <= brightness)
? brightness
: MSMonitor.GetBrightness(DeviceInstanceId);
}
else
{
this.Brightness = PowerManagement.GetActiveSchemeBrightness();
this.BrightnessSystemAdjusted = !PowerManagement.IsAdaptiveBrightnessEnabled
? -1 // Default
: (0 <= brightness)
? brightness
: MSMonitor.GetBrightness(DeviceInstanceId);
}
return (0 <= this.Brightness);
}
}
public override bool SetBrightness(int brightness)
{
if ((brightness < 0) || (100 < brightness))
throw new ArgumentOutOfRangeException(nameof(brightness), brightness, "The brightness must be within 0 to 100.");
lock (_lock)
{
if (_isRemovable)
{
brightness = ArraySearch.GetNearest(_brightnessLevels, (byte)brightness);
if (MSMonitor.SetBrightness(DeviceInstanceId, brightness))
{
this.Brightness = brightness;
return true;
}
}
else
{
if (PowerManagement.SetActiveSchemeBrightness(brightness))
{
this.Brightness = brightness;
return true;
}
}
return false;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monitorian.Core.Helper;
namespace Monitorian.Core.Models.Monitor
{
/// <summary>
/// Physical monitor managed by WMI (internal monitor)
/// </summary>
internal class WmiMonitorItem : MonitorItem
{
private readonly byte[] _brightnessLevels;
private readonly bool _isRemovable;
public WmiMonitorItem(
string deviceInstanceId,
string description,
byte displayIndex,
byte monitorIndex,
byte[] brightnessLevels,
bool isRemovable) : base(
deviceInstanceId: deviceInstanceId,
description: description,
displayIndex: displayIndex,
monitorIndex: monitorIndex,
isAccessible: true)
{
this._brightnessLevels = brightnessLevels ?? throw new ArgumentNullException(nameof(brightnessLevels));
this._isRemovable = isRemovable;
}
private readonly object _lock = new object();
public override bool UpdateBrightness(int brightness = -1)
{
lock (_lock)
{
if (_isRemovable)
{
this.Brightness = (0 <= brightness)
? brightness
: MSMonitor.GetBrightness(DeviceInstanceId);
}
else
{
this.Brightness = PowerManagement.GetActiveSchemeBrightness();
if (LightSensor.AmbientLightSensorExists)
{
this.BrightnessSystemAdjusted = (0 <= brightness)
? brightness
: MSMonitor.GetBrightness(DeviceInstanceId);
}
}
return (0 <= this.Brightness);
}
}
public override bool SetBrightness(int brightness)
{
if ((brightness < 0) || (100 < brightness))
throw new ArgumentOutOfRangeException(nameof(brightness), brightness, "The brightness must be within 0 to 100.");
lock (_lock)
{
if (_isRemovable)
{
brightness = ArraySearch.GetNearest(_brightnessLevels, (byte)brightness);
if (MSMonitor.SetBrightness(DeviceInstanceId, brightness))
{
this.Brightness = brightness;
return true;
}
}
else
{
if (PowerManagement.SetActiveSchemeBrightness(brightness))
{
this.Brightness = brightness;
return true;
}
}
return false;
}
}
}
} | mit | C# |
1ae628e338b65fa1e93d5a9a1da8c5b4ad88c4c6 | Set S-Bahns to true by default | earalov/Skylines-VehicleConverter | VehicleConverter/Options.cs | VehicleConverter/Options.cs | using System.Xml.Serialization;
using VehicleConverter.OptionsFramework.Attibutes;
namespace VehicleConverter
{
[Options("TrainConverter-Options")]
public class Options
{
private const string MOM = "Trains to metro - Require Metro Overhaul Mod (MOM)";
private const string SNOWFALL = "Trains to trams - Require Snowfall DLC";
private const string STATIONS = "Train Stations to metro stations - Require Metro Overhaul Mod (MOM)";
public Options()
{
ConvertTrainsToTrams = true;
ConvertSubwayTrainsToMetros = true;
ConvertSBahnsToMetros = true;
ConvertPantographsToMetros = false;
ConvertModernStationsToMetroStations = true;
ConvertOldStationsToMetroStations = true;
ConvertTramStationsToMetroStations = false;
}
[XmlElement("convert-subway-trains-to-metros")]
[Checkbox("Convert subway trains to metros", null, null, MOM)]
public bool ConvertSubwayTrainsToMetros { set; get; }
[XmlElement("convert-s-bahn-trains-to-metros")]
[Checkbox("Convert S-Bahn/Overground trains to metros", null, null, MOM)]
public bool ConvertSBahnsToMetros { set; get; }
[XmlElement("convert-pantograph-trains-to-metros")]
[Checkbox("Convert pantograph trains to metros", null, null, MOM)]
public bool ConvertPantographsToMetros { set; get; }
[XmlElement("convert-tram-trains-to-trams")]
[Checkbox("Convert tram-trains to Snowfall trams", null, null, SNOWFALL)]
public bool ConvertTrainsToTrams { set; get; }
[XmlElement("convert-modern-train-stations-to-metro-stations")]
[Checkbox("Convert some Modern Style stations to metro stations", null, null, STATIONS)]
public bool ConvertModernStationsToMetroStations { set; get; }
[XmlElement("convert-old-train-stations-to-metro-stations")]
[Checkbox("Convert some Old Style stations to metro stations (Steel style used if enabled)", null, null, STATIONS)]
public bool ConvertOldStationsToMetroStations { set; get; }
[XmlElement("convert-tram-train-stations-to-metro-stations")]
[Checkbox("Convert some 'tram' stations to metro stations", null, null, STATIONS)]
public bool ConvertTramStationsToMetroStations { set; get; }
}
} | using System.Xml.Serialization;
using VehicleConverter.OptionsFramework.Attibutes;
namespace VehicleConverter
{
[Options("TrainConverter-Options")]
public class Options
{
private const string MOM = "Trains to metro - Require Metro Overhaul Mod (MOM)";
private const string SNOWFALL = "Trains to trams - Require Snowfall DLC";
private const string STATIONS = "Train Stations to metro stations - Require Metro Overhaul Mod (MOM)";
public Options()
{
ConvertTrainsToTrams = true;
ConvertSubwayTrainsToMetros = true;
ConvertSBahnsToMetros = false;
ConvertPantographsToMetros = false;
ConvertModernStationsToMetroStations = true;
ConvertOldStationsToMetroStations = true;
ConvertTramStationsToMetroStations = false;
}
[XmlElement("convert-subway-trains-to-metros")]
[Checkbox("Convert subway trains to metros", null, null, MOM)]
public bool ConvertSubwayTrainsToMetros { set; get; }
[XmlElement("convert-s-bahn-trains-to-metros")]
[Checkbox("Convert S-Bahn/Overground trains to metros", null, null, MOM)]
public bool ConvertSBahnsToMetros { set; get; }
[XmlElement("convert-pantograph-trains-to-metros")]
[Checkbox("Convert pantograph trains to metros", null, null, MOM)]
public bool ConvertPantographsToMetros { set; get; }
[XmlElement("convert-tram-trains-to-trams")]
[Checkbox("Convert tram-trains to Snowfall trams", null, null, SNOWFALL)]
public bool ConvertTrainsToTrams { set; get; }
[XmlElement("convert-modern-train-stations-to-metro-stations")]
[Checkbox("Convert some Modern Style stations to metro stations", null, null, STATIONS)]
public bool ConvertModernStationsToMetroStations { set; get; }
[XmlElement("convert-old-train-stations-to-metro-stations")]
[Checkbox("Convert some Old Style stations to metro stations (Steel style used if enabled)", null, null, STATIONS)]
public bool ConvertOldStationsToMetroStations { set; get; }
[XmlElement("convert-tram-train-stations-to-metro-stations")]
[Checkbox("Convert some 'tram' stations to metro stations", null, null, STATIONS)]
public bool ConvertTramStationsToMetroStations { set; get; }
}
} | mit | C# |
e770090530ada5527f0ae2dacc1cfb171b981695 | Package sin CS Banner. | jmirancid/TropicalNet.Topppro,jmirancid/TropicalNet.Topppro,jmirancid/TropicalNet.Topppro | Topppro.WebSite/Areas/Humanist/Views/Packs/Index.cshtml | Topppro.WebSite/Areas/Humanist/Views/Packs/Index.cshtml | @using Framework.MVC.Extensions
@using Topppro.WebSite.Areas.Humanist.Resources
@using Topppro.WebSite.Areas.Humanist.Extensions
@model IEnumerable<Topppro.Entities.Assn_CategorySerie>
@section Styles {
<link rel="Stylesheet" type="text/css" href="@Url.Content("~/Areas/Humanist/Content/Styles/m-icons.min.css")" />
<link rel="Stylesheet" type="text/css" href="@Url.Content("~/Areas/Humanist/Content/Styles/m-buttons.min.css")" />
}
<table width="1000" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF">
<tbody>
@*@Html.CsBanner()*@
<div style="margin-bottom:40px;"> </div>
@Html.DisplayForModel()
</tbody>
</table>
<div class="slide-panel left">
<h2><a href="javascript:$.panelslider.close();"><i class="m-icon-big-swapleft m-icon-white" style="margin:0px 3px;"></i></a> @Localization.Compare_Panel_Title</h2>
<ul class="compare-list"></ul>
<p class="controls">
<button id="btn-clear" class="m-btn black">@Localization.Compare_Panel_Clear_Button <i class="icon-refresh icon-white"></i></button>
<button id="btn-compare" class="m-btn green">@Localization.Compare_Panel_Compare_Button <i class="icon-share-alt icon-white"></i></button>
</p>
</div>
@section Scripts {
@Html.PreloadedImages()
<script type="text/javascript" src="@Url.Content("~/Areas/Humanist/Scripts/jquery-1.8.3.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Areas/Humanist/Scripts/jssor.slider-19.0/jssor.slider.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Areas/Humanist/Scripts/jquery.panelslider-0.1.1/jquery.panelslider.min.js")"></script>
@Html.Partial("_Slide")
}
| @using Framework.MVC.Extensions
@using Topppro.WebSite.Areas.Humanist.Resources
@using Topppro.WebSite.Areas.Humanist.Extensions
@model IEnumerable<Topppro.Entities.Assn_CategorySerie>
@section Styles {
<link rel="Stylesheet" type="text/css" href="@Url.Content("~/Areas/Humanist/Content/Styles/m-icons.min.css")" />
<link rel="Stylesheet" type="text/css" href="@Url.Content("~/Areas/Humanist/Content/Styles/m-buttons.min.css")" />
}
<table width="1000" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF">
<tbody>
@Html.CsBanner()
<div style="margin-bottom:40px;"> </div>
@Html.DisplayForModel()
</tbody>
</table>
<div class="slide-panel left">
<h2><a href="javascript:$.panelslider.close();"><i class="m-icon-big-swapleft m-icon-white" style="margin:0px 3px;"></i></a> @Localization.Compare_Panel_Title</h2>
<ul class="compare-list"></ul>
<p class="controls">
<button id="btn-clear" class="m-btn black">@Localization.Compare_Panel_Clear_Button <i class="icon-refresh icon-white"></i></button>
<button id="btn-compare" class="m-btn green">@Localization.Compare_Panel_Compare_Button <i class="icon-share-alt icon-white"></i></button>
</p>
</div>
@section Scripts {
@Html.PreloadedImages()
<script type="text/javascript" src="@Url.Content("~/Areas/Humanist/Scripts/jquery-1.8.3.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Areas/Humanist/Scripts/jssor.slider-19.0/jssor.slider.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Areas/Humanist/Scripts/jquery.panelslider-0.1.1/jquery.panelslider.min.js")"></script>
@Html.Partial("_Slide")
}
| mit | C# |
593e8659ee1a6d8cfe5635f89d85c4be39b3797e | Add missing call to base class | grokys/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.ReactiveUI/ReactiveUserControl.cs | src/Avalonia.ReactiveUI/ReactiveUserControl.cs | using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia;
using Avalonia.VisualTree;
using Avalonia.Controls;
using ReactiveUI;
namespace Avalonia.ReactiveUI
{
/// <summary>
/// A ReactiveUI <see cref="UserControl"/> that implements the <see cref="IViewFor{TViewModel}"/> interface and
/// will activate your ViewModel automatically if the view model implements <see cref="IActivatableViewModel"/>.
/// When the DataContext property changes, this class will update the ViewModel property with the new DataContext
/// value, and vice versa.
/// </summary>
/// <typeparam name="TViewModel">ViewModel type.</typeparam>
public class ReactiveUserControl<TViewModel> : UserControl, IViewFor<TViewModel> where TViewModel : class
{
public static readonly StyledProperty<TViewModel?> ViewModelProperty = AvaloniaProperty
.Register<ReactiveUserControl<TViewModel>, TViewModel?>(nameof(ViewModel));
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveUserControl{TViewModel}"/> class.
/// </summary>
public ReactiveUserControl()
{
// This WhenActivated block calls ViewModel's WhenActivated
// block if the ViewModel implements IActivatableViewModel.
this.WhenActivated(disposables => { });
this.GetObservable(ViewModelProperty).Subscribe(OnViewModelChanged);
}
/// <summary>
/// The ViewModel.
/// </summary>
public TViewModel? ViewModel
{
get => GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
object? IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (TViewModel?)value;
}
protected override void OnDataContextChanged(EventArgs e)
{
base.OnDataContextChanged(e);
ViewModel = DataContext as TViewModel;
}
private void OnViewModelChanged(object? value)
{
if (value == null)
{
ClearValue(DataContextProperty);
}
else if (DataContext != value)
{
DataContext = value;
}
}
}
}
| using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia;
using Avalonia.VisualTree;
using Avalonia.Controls;
using ReactiveUI;
namespace Avalonia.ReactiveUI
{
/// <summary>
/// A ReactiveUI <see cref="UserControl"/> that implements the <see cref="IViewFor{TViewModel}"/> interface and
/// will activate your ViewModel automatically if the view model implements <see cref="IActivatableViewModel"/>.
/// When the DataContext property changes, this class will update the ViewModel property with the new DataContext
/// value, and vice versa.
/// </summary>
/// <typeparam name="TViewModel">ViewModel type.</typeparam>
public class ReactiveUserControl<TViewModel> : UserControl, IViewFor<TViewModel> where TViewModel : class
{
public static readonly StyledProperty<TViewModel?> ViewModelProperty = AvaloniaProperty
.Register<ReactiveUserControl<TViewModel>, TViewModel?>(nameof(ViewModel));
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveUserControl{TViewModel}"/> class.
/// </summary>
public ReactiveUserControl()
{
// This WhenActivated block calls ViewModel's WhenActivated
// block if the ViewModel implements IActivatableViewModel.
this.WhenActivated(disposables => { });
this.GetObservable(ViewModelProperty).Subscribe(OnViewModelChanged);
}
/// <summary>
/// The ViewModel.
/// </summary>
public TViewModel? ViewModel
{
get => GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
object? IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (TViewModel?)value;
}
protected override void OnDataContextChanged(EventArgs e)
{
ViewModel = DataContext as TViewModel;
}
private void OnViewModelChanged(object? value)
{
if (value == null)
{
ClearValue(DataContextProperty);
}
else if (DataContext != value)
{
DataContext = value;
}
}
}
}
| mit | C# |
c0f7a83f6f3d4aaab9ce0d4d9ee2ae9674d238de | Fix featured stream item width | smoogipoo/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,peppy/osu,UselessToucan/osu | osu.Game/Overlays/Changelog/ChangelogUpdateStreamItem.cs | osu.Game/Overlays/Changelog/ChangelogUpdateStreamItem.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 Humanizer;
using osu.Game.Online.API.Requests.Responses;
using osuTK.Graphics;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogUpdateStreamItem : OverlayUpdateStreamItem<APIUpdateStream>
{
public ChangelogUpdateStreamItem(APIUpdateStream stream)
: base(stream)
{
}
protected override float GetWidth()
{
if (Value.IsFeatured)
return base.GetWidth() * 2;
return base.GetWidth();
}
protected override string GetMainText() => Value.DisplayName;
protected override string GetAdditionalText() => Value.LatestBuild.DisplayVersion;
protected override string GetInfoText() => Value.LatestBuild.Users > 0 ? $"{"user".ToQuantity(Value.LatestBuild.Users, "N0")} online" : null;
protected override Color4 GetBarColour() => Value.Colour;
}
}
| // 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 Humanizer;
using osu.Game.Online.API.Requests.Responses;
using osuTK.Graphics;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogUpdateStreamItem : OverlayUpdateStreamItem<APIUpdateStream>
{
public ChangelogUpdateStreamItem(APIUpdateStream stream)
: base(stream)
{
}
protected override string GetMainText() => Value.DisplayName;
protected override string GetAdditionalText() => Value.LatestBuild.DisplayVersion;
protected override string GetInfoText() => Value.LatestBuild.Users > 0 ? $"{"user".ToQuantity(Value.LatestBuild.Users, "N0")} online" : null;
protected override Color4 GetBarColour() => Value.Colour;
}
}
| mit | C# |
f03720cc61b27aa481dc40e7f9afb1bc77425340 | Document IDocument | lambdacasserole/sulfide | Sulfide/IDocument.cs | Sulfide/IDocument.cs | using WeifenLuo.WinFormsUI.Docking;
namespace Sulfide
{
/// <summary>
/// Represents a document that can be opened in the editor.
/// </summary>
public interface IDocument
{
/// <summary>
/// Gets the save strategy for the document.
/// </summary>
ISaveStrategy SaveStrategy { get; }
/// <summary>
/// Gets the clipboard strategy for the document.
/// </summary>
IClipboardStrategy ClipboardStrategy { get; }
/// <summary>
/// Gets the printing strategy for the document.
/// </summary>
IPrintingStrategy PrintingStrategy { get; }
/// <summary>
/// Gets the history strategy for the document.
/// </summary>
IHistoryStrategy HistoryStrategy { get; }
/// <summary>
/// Gets or sets the window title for the document.
/// </summary>
string Text { get; set; }
/// <summary>
/// Shows the document in the editor.
/// </summary>
/// <param name="dockPanel">The dock panel to show the document in.</param>
/// <param name="dockState">The initial dock state of the document.</param>
void Show(DockPanel dockPanel, DockState dockState);
/// <summary>
/// Closes the document in the editor.
/// </summary>
void Close();
}
}
| using WeifenLuo.WinFormsUI.Docking;
namespace Sulfide
{
/// <summary>
/// Represents a document that can be opened in the editor.
/// </summary>
public interface IDocument
{
ISaveStrategy SaveStrategy { get; }
IClipboardStrategy ClipboardStrategy { get; }
IPrintingStrategy PrintingStrategy { get; }
IHistoryStrategy HistoryStrategy { get; }
string Text { get; set; }
void Show(DockPanel dockPanel, DockState dockState);
void Close();
}
}
| mit | C# |
e5d50e4946f8b29a0713fb1a49e45e69869a0437 | Fix class name typo | MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS | src/R/Editor/Application.Test/Documentation/SelectionTest.cs | src/R/Editor/Application.Test/Documentation/SelectionTest.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.R.Components.ContentTypes;
using Microsoft.R.Editor.Application.Test.TestShell;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Editor.Application.Test.Selection {
[ExcludeFromCodeCoverage]
[Collection(CollectionNames.NonParallel)]
public class DocumentationTest {
[Test]
[Category.Interactive]
public void InsertRoxygenBlock() {
string content =
@"
x <- function(a,b,c) { }
";
string expected =
@"#' Title
#'
#' @param a
#' @param b
#' @param c
#'
#' @return
#' @export
#'
#' @examples
x <- function(a,b,c) { }
";
using (var script = new TestScript(content, RContentTypeDefinition.ContentType)) {
script.Type("###");
var actual = EditorWindow.TextBuffer.CurrentSnapshot.GetText();
actual.Should().Be(expected);
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.R.Components.ContentTypes;
using Microsoft.R.Editor.Application.Test.TestShell;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Editor.Application.Test.Selection {
[ExcludeFromCodeCoverage]
[Collection(CollectionNames.NonParallel)]
public class DocumentatonTest {
[Test]
[Category.Interactive]
public void InsertRoxygenBlock() {
string content =
@"
x <- function(a,b,c) { }
";
string expected =
@"#' Title
#'
#' @param a
#' @param b
#' @param c
#'
#' @return
#' @export
#'
#' @examples
x <- function(a,b,c) { }
";
using (var script = new TestScript(content, RContentTypeDefinition.ContentType)) {
script.Type("###");
var actual = EditorWindow.TextBuffer.CurrentSnapshot.GetText();
actual.Should().Be(expected);
}
}
}
}
| mit | C# |
05c35dd3ba74327f371b59f946f8e4a97e69ca28 | Add missing access modifier | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Mvc.Razor/RazorPageOfT.cs | src/Microsoft.AspNet.Mvc.Razor/RazorPageOfT.cs | // Copyright (c) Microsoft Open Technologies, Inc. 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.Linq.Expressions;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.Rendering.Expressions;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Mvc.Razor
{
/// <summary>
/// Represents the properties and methods that are needed in order to render a view that uses Razor syntax.
/// </summary>
/// <typeparam name="TModel">The type of the view data model.</typeparam>
public abstract class RazorPage<TModel> : RazorPage
{
private IModelMetadataProvider _provider;
public TModel Model
{
get
{
return ViewData == null ? default(TModel) : ViewData.Model;
}
}
[Activate]
public ViewDataDictionary<TModel> ViewData { get; set; }
/// <summary>
/// Returns a <see cref="ModelExpression"/> instance describing the given <paramref name="expression"/>.
/// </summary>
/// <typeparam name="TValue">The type of the <paramref name="expression"/> result.</typeparam>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <returns>A new <see cref="ModelExpression"/> instance describing the given <paramref name="expression"/>.
/// </returns>
/// <remarks>
/// Compiler normally infers <typeparamref name="TValue"/> from the given <paramref name="expression"/>.
/// </remarks>
public ModelExpression CreateModelExpression<TValue>([NotNull] Expression<Func<TModel, TValue>> expression)
{
if (_provider == null)
{
_provider = Context.RequestServices.GetService<IModelMetadataProvider>();
}
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, ViewData, _provider);
if (metadata == null)
{
throw new InvalidOperationException(
Resources.FormatRazorPage_NullModelMetadata(nameof(IModelMetadataProvider), name));
}
return new ModelExpression(name, metadata);
}
}
}
| // Copyright (c) Microsoft Open Technologies, Inc. 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.Linq.Expressions;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.Rendering.Expressions;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Mvc.Razor
{
/// <summary>
/// Represents the properties and methods that are needed in order to render a view that uses Razor syntax.
/// </summary>
/// <typeparam name="TModel">The type of the view data model.</typeparam>
public abstract class RazorPage<TModel> : RazorPage
{
IModelMetadataProvider _provider;
public TModel Model
{
get
{
return ViewData == null ? default(TModel) : ViewData.Model;
}
}
[Activate]
public ViewDataDictionary<TModel> ViewData { get; set; }
/// <summary>
/// Returns a <see cref="ModelExpression"/> instance describing the given <paramref name="expression"/>.
/// </summary>
/// <typeparam name="TValue">The type of the <paramref name="expression"/> result.</typeparam>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <returns>A new <see cref="ModelExpression"/> instance describing the given <paramref name="expression"/>.
/// </returns>
/// <remarks>
/// Compiler normally infers <typeparamref name="TValue"/> from the given <paramref name="expression"/>.
/// </remarks>
public ModelExpression CreateModelExpression<TValue>([NotNull] Expression<Func<TModel, TValue>> expression)
{
if (_provider == null)
{
_provider = Context.RequestServices.GetService<IModelMetadataProvider>();
}
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, ViewData, _provider);
if (metadata == null)
{
throw new InvalidOperationException(
Resources.FormatRazorPage_NullModelMetadata(nameof(IModelMetadataProvider), name));
}
return new ModelExpression(name, metadata);
}
}
}
| apache-2.0 | C# |
c1a4bc6876cf40cf993bb96a01f367f398d89432 | Fix UI bugs with time. | betrakiss/Tramline-5,betrakiss/Tramline-5 | src/TramlineFive/TramlineFive/ViewModels/ArrivalViewModel.cs | src/TramlineFive/TramlineFive/ViewModels/ArrivalViewModel.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TramlineFive.Common;
using TramlineFive.Common.Models;
using TramlineFive.Views.Dialogs;
namespace TramlineFive.ViewModels
{
public class ArrivalViewModel
{
public ObservableCollection<Arrival> Arrivals { get; set; }
public StringViewModel StopTitle { get; set; }
public StringViewModel AsOfTime { get; set; }
public ArrivalViewModel()
{
Arrivals = new ObservableCollection<Arrival>();
StopTitle = new StringViewModel();
AsOfTime = new StringViewModel();
}
public async Task<bool> GetByStopCode(string stopCode)
{
Arrivals.Clear();
StopTitle.Source = String.Empty;
AsOfTime.Source = String.Empty;
IEnumerable<Arrival> arrivals = await SumcManager.GetByStopAsync(stopCode, typeof(CaptchaDialog));
if (arrivals != null)
{
if (arrivals.Count() == 0)
return false;
foreach (Arrival arrival in arrivals)
Arrivals.Add(arrival);
StopTitle.Source = SumcParser.ParseStopTitle(Arrivals.FirstOrDefault().StopTitle);
AsOfTime.Source = "Данни от " + DateTime.Now.ToString("HH:mm");
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TramlineFive.Common;
using TramlineFive.Common.Models;
using TramlineFive.Views.Dialogs;
namespace TramlineFive.ViewModels
{
public class ArrivalViewModel
{
public ObservableCollection<Arrival> Arrivals { get; set; }
public StringViewModel StopTitle { get; set; }
public StringViewModel AsOfTime { get; set; }
public ArrivalViewModel()
{
Arrivals = new ObservableCollection<Arrival>();
StopTitle = new StringViewModel();
AsOfTime = new StringViewModel();
}
public async Task<bool> GetByStopCode(string stopCode)
{
Arrivals.Clear();
StopTitle.Source = String.Empty;
AsOfTime.Source = String.Empty;
IEnumerable<Arrival> arrivals = await SumcManager.GetByStopAsync(stopCode, typeof(CaptchaDialog));
if (arrivals?.Count() == 0)
return false;
foreach (Arrival arrival in arrivals ?? Enumerable.Empty<Arrival>())
Arrivals.Add(arrival);
StopTitle.Source = SumcParser.ParseStopTitle(Arrivals.FirstOrDefault()?.StopTitle);
AsOfTime.Source = "Данни от " + DateTime.Now.ToString("HH:mm");
return true;
}
}
}
| apache-2.0 | C# |
ddd97fed20f5e2f939b58900b061712a7d237662 | Fix for an empty AllowedContentTypes in the DocumentSetTemplate element. | OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core | Core/OfficeDevPnP.Core/Framework/Provisioning/Providers/Xml/Resolvers/V201705/DocumentSetTemplateAllowedContentTypesFromModelToSchemaTypeResolver.cs | Core/OfficeDevPnP.Core/Framework/Provisioning/Providers/Xml/Resolvers/V201705/DocumentSetTemplateAllowedContentTypesFromModelToSchemaTypeResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers
{
internal class DocumentSetTemplateAllowedContentTypesFromModelToSchemaTypeResolver : ITypeResolver
{
public string Name => this.GetType().Name;
public bool CustomCollectionResolver => false;
public DocumentSetTemplateAllowedContentTypesFromModelToSchemaTypeResolver()
{
}
public object Resolve(object source, Dictionary<String, IResolver> resolvers = null, Boolean recursive = false)
{
Object result = null;
var documentSetTemplate = source as Model.DocumentSetTemplate;
if (null != documentSetTemplate)
{
var allowedContentTypesTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.DocumentSetTemplateAllowedContentTypes, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}";
var allowedContentTypesType = Type.GetType(allowedContentTypesTypeName, true);
result = Activator.CreateInstance(allowedContentTypesType);
var allowedContentTypeTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.DocumentSetTemplateAllowedContentTypesAllowedContentType, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}";
var allowedContentTypeType = Type.GetType(allowedContentTypeTypeName, true);
var allowedContentTypesArray = Array.CreateInstance(allowedContentTypeType, documentSetTemplate.AllowedContentTypes.Count);
result.GetPublicInstanceProperty("RemoveExistingContentTypes").SetValue(result, documentSetTemplate.RemoveExistingContentTypes);
Int32 i = 0;
foreach (var ct in documentSetTemplate.AllowedContentTypes)
{
var item = Activator.CreateInstance(allowedContentTypeType);
item.SetPublicInstancePropertyValue("ContentTypeID", ct);
allowedContentTypesArray.SetValue(item, i);
i++;
}
if (allowedContentTypesArray.Length > 0)
{
result.SetPublicInstancePropertyValue("AllowedContentType", allowedContentTypesArray);
}
else
{
result = null;
}
}
return (result);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers
{
internal class DocumentSetTemplateAllowedContentTypesFromModelToSchemaTypeResolver : ITypeResolver
{
public string Name => this.GetType().Name;
public bool CustomCollectionResolver => false;
public DocumentSetTemplateAllowedContentTypesFromModelToSchemaTypeResolver()
{
}
public object Resolve(object source, Dictionary<String, IResolver> resolvers = null, Boolean recursive = false)
{
Object result = null;
var documentSetTemplate = source as Model.DocumentSetTemplate;
if (null != documentSetTemplate)
{
var allowedContentTypesTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.DocumentSetTemplateAllowedContentTypes, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}";
var allowedContentTypesType = Type.GetType(allowedContentTypesTypeName, true);
result = Activator.CreateInstance(allowedContentTypesType);
var allowedContentTypeTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.DocumentSetTemplateAllowedContentTypesAllowedContentType, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}";
var allowedContentTypeType = Type.GetType(allowedContentTypeTypeName, true);
var allowedContentTypesArray = Array.CreateInstance(allowedContentTypeType, documentSetTemplate.AllowedContentTypes.Count);
result.GetPublicInstanceProperty("RemoveExistingContentTypes").SetValue(result, documentSetTemplate.RemoveExistingContentTypes);
Int32 i = 0;
foreach (var ct in documentSetTemplate.AllowedContentTypes)
{
var item = Activator.CreateInstance(allowedContentTypeType);
item.SetPublicInstancePropertyValue("ContentTypeID", ct);
allowedContentTypesArray.SetValue(item, i);
i++;
}
result.SetPublicInstancePropertyValue("AllowedContentType", allowedContentTypesArray);
}
return (result);
}
}
}
| mit | C# |
69705ef22dff3eb1b08450d1e17c222afbe3807a | Introduce subject and subscribe | citizenmatt/ndc-london-2013 | rx/rx/Program.cs | rx/rx/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace rx
{
class Program
{
static void Main(string[] args)
{
var subject = new Subject<string>();
using (subject.Subscribe(result => Console.WriteLine(result)))
{
var wc = new WebClient();
var task = wc.DownloadStringTaskAsync("http://www.google.com/robots.txt");
task.ContinueWith(t => Console.WriteLine(t.Result));
// Wait for the async call
Console.ReadLine();
}
}
}
public class Subject<T>
{
private readonly IList<Action<T>> observers = new List<Action<T>>();
public IDisposable Subscribe(Action<T> observer)
{
observers.Add(observer);
return new Disposable(() => observers.Remove(observer));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace rx
{
class Program
{
static void Main(string[] args)
{
var wc = new WebClient();
var task = wc.DownloadStringTaskAsync("http://www.google.com/robots.txt");
task.ContinueWith(t => Console.WriteLine(t.Result));
// Wait for the async call
Console.ReadLine();
}
}
public class Subject<T>
{
private readonly IList<Action<T>> observers = new List<Action<T>>();
public IDisposable Subscribe(Action<T> observer)
{
observers.Add(observer);
return new Disposable(() => observers.Remove(observer));
}
}
}
| mit | C# |
1ca93bf07fb9a2e5e412b011506f167dc0c03342 | update version | ceee/PocketSharp | PocketSharp/Properties/AssemblyInfo.cs | PocketSharp/Properties/AssemblyInfo.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: AssemblyTitle("PocketSharp")]
[assembly: AssemblyDescription("PocketSharp is a .NET class library that integrates the Pocket API v3 (support a custom Article View API)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("cee")]
[assembly: AssemblyProduct("PocketSharp")]
[assembly: AssemblyCopyright("Copyright © cee 2014")]
[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("4.1.1")]
[assembly: AssemblyFileVersion("4.1.1")] | 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: AssemblyTitle("PocketSharp")]
[assembly: AssemblyDescription("PocketSharp is a .NET class library that integrates the Pocket API v3 (support a custom Article View API)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("cee")]
[assembly: AssemblyProduct("PocketSharp")]
[assembly: AssemblyCopyright("Copyright © cee 2014")]
[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("4.1.0")]
[assembly: AssemblyFileVersion("4.1.0")] | mit | C# |
42a9de501adba635a46bdf15ce29b43ed6925cc2 | Fix for some css not working on the server | iliantrifonov/Team-Guava,iliantrifonov/Team-Guava | ExamSystem.Backend/ExamSystem.Backend.Web/App_Start/BundleConfig.cs | ExamSystem.Backend/ExamSystem.Backend.Web/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace ExamSystem.Backend.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = false;
}
}
}
| using System.Web;
using System.Web.Optimization;
namespace ExamSystem.Backend.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = true;
}
}
}
| mit | C# |
f17e0d9de16eb1fb6af79e9e769634a58dcbc3a9 | Add period exposed to excel | cetusfinance/qwack,cetusfinance/qwack,cetusfinance/qwack,cetusfinance/qwack | src/Qwack.Excel/Dates/BusinessDateFunctions.cs | src/Qwack.Excel/Dates/BusinessDateFunctions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ExcelDna.Integration;
using Qwack.Dates;
using Qwack.Excel.Services;
namespace Qwack.Excel.Dates
{
public static class BusinessDateFunctions
{
[ExcelFunction(Description = "Checks if the given date is a holiday according to the specified calendars", Category = "QDates")]
public static object QDates_IsHoliday(
[ExcelArgument(Description = "The date to check")] DateTime DateToCheck,
[ExcelArgument(Description = "The calendar(s) to check against")]string Calendar)
{
return ExcelHelper.Execute(() =>
{
Calendar cal;
if (!StaticDataService.Instance.CalendarProvider.Collection.TryGetCalendar(Calendar, out cal))
return "Calendar not found in cache";
return cal.IsHoliday(DateToCheck);
});
}
[ExcelFunction(Description = "Adds a specified period to a date, adjusting for holidays", Category = "QDates")]
public static object QDates_AddPeriod(
[ExcelArgument(Description = "Starting date")] DateTime StartDate,
[ExcelArgument(Description = "Period specified as a string e.g. 1w")]string Period,
[ExcelArgument(Description = "Roll method")]string RollMethod,
[ExcelArgument(Description = "Calendar(s) to check against")]string Calendar)
{
return ExcelHelper.Execute(() =>
{
Calendar cal;
if (!StaticDataService.Instance.CalendarProvider.Collection.TryGetCalendar(Calendar, out cal))
return $"Calendar {Calendar} not found in cache";
RollType rollMethod;
if(!Enum.TryParse<RollType>(RollMethod,out rollMethod))
return $"Unknown roll method {RollMethod}";
Frequency period = new Frequency(Period);
return StartDate.AddPeriod(rollMethod, cal, period);
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ExcelDna.Integration;
using Qwack.Dates;
using Qwack.Excel.Services;
namespace Qwack.Excel.Dates
{
public static class BusinessDateFunctions
{
[ExcelFunction(Description = "Checks if the given date is a holiday according to the specified calendars", Category = "QDates")]
public static object QDates_IsHoliday(
[ExcelArgument(Description = "The date to check")] DateTime DateToCheck,
[ExcelArgument(Description = "The calendar(s) to check against")]string Calendar)
{
return ExcelHelper.Execute(() =>
{
Calendar cal;
if (!StaticDataService.Instance.CalendarProvider.Collection.TryGetCalendar(Calendar, out cal))
return "Calendar not found in cache";
return cal.IsHoliday(DateToCheck);
});
}
}
}
| mit | C# |
e08aafbd652641542921078a38be2f97e88cae5d | Fix RegisterUserModelValidator | senioroman4uk/PathFinder | PathFinder.Security.WebApi/Validation/RegisterUserModelValidator.cs | PathFinder.Security.WebApi/Validation/RegisterUserModelValidator.cs | using FluentValidation;
using PathFinder.Security.WebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PathFinder.Security.WebApi.Validation
{
public class RegisterUserModelValidator : AbstractValidator<RegisterUserModel>
{
public RegisterUserModelValidator()
{
RuleFor(model => model.Email).NotNull();
RuleFor(model => model.Password).NotNull();
RuleFor(model => model.RepeatPassword).NotNull();
RuleFor(model => model).Must(ArePasswordEquals).WithMessage("Passwords are not equals");
RuleFor(model => model.LastName).NotEmpty();
RuleFor(model => model.UserName).NotNull().NotEmpty();
RuleFor(model => model.PhoneNumber).NotEmpty();
}
private bool ArePasswordEquals(RegisterUserModel arg)
{
if (arg.Password == null) return false;
return arg.Password.Equals(arg.RepeatPassword);
}
}
}
| using FluentValidation;
using PathFinder.Security.WebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PathFinder.Security.WebApi.Validation
{
public class RegisterUserModelValidator : AbstractValidator<RegisterUserModel>
{
public RegisterUserModelValidator()
{
RuleFor(model => model.Email).NotEmpty();
RuleFor(model => model).Must(ArePasswordEquels);
RuleFor(model => model.LastName).NotEmpty();
RuleFor(model => model.UserName).NotEmpty();
RuleFor(model => model.PhoneNumber).NotEmpty();
}
private bool ArePasswordEquels(RegisterUserModel arg)
{
return arg.Password.Equals(arg.RepeatPassword);
}
}
}
| mit | C# |
f1696eae922d812ad41337d1e79ffa431530f78d | Use IEnumable instead of List | 2yangk23/osu,naoey/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new,naoey/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,peppy/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,NeoAdonis/osu,DrabWeb/osu,johnneijzen/osu,smoogipoo/osu,2yangk23/osu,DrabWeb/osu,EVAST9919/osu,ZLima12/osu,EVAST9919/osu,naoey/osu,NeoAdonis/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu | osu.Game/Online/API/Requests/GetChannelMessagesRequest.cs | osu.Game/Online/API/Requests/GetChannelMessagesRequest.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osu.Framework.IO.Network;
using osu.Game.Online.Chat;
namespace osu.Game.Online.API.Requests
{
public class GetChannelMessagesRequest : APIRequest<List<Message>>
{
private readonly IEnumerable<ChannelChat> channels;
private long? since;
public GetChannelMessagesRequest(IEnumerable<ChannelChat> channels, long? sinceId)
{
this.channels = channels;
since = sinceId;
}
protected override WebRequest CreateWebRequest()
{
string channelString = string.Join(",", channels.Select(x => x.Id));
var req = base.CreateWebRequest();
req.AddParameter(@"channels", channelString);
if (since.HasValue) req.AddParameter(@"since", since.Value.ToString());
return req;
}
protected override string Target => @"chat/messages";
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osu.Framework.IO.Network;
using osu.Game.Online.Chat;
namespace osu.Game.Online.API.Requests
{
public class GetChannelMessagesRequest : APIRequest<List<Message>>
{
private readonly List<ChannelChat> channels;
private long? since;
public GetChannelMessagesRequest(List<ChannelChat> channels, long? sinceId)
{
this.channels = channels;
since = sinceId;
}
protected override WebRequest CreateWebRequest()
{
string channelString = string.Join(",", channels.Select(x => x.Id));
var req = base.CreateWebRequest();
req.AddParameter(@"channels", channelString);
if (since.HasValue) req.AddParameter(@"since", since.Value.ToString());
return req;
}
protected override string Target => @"chat/messages";
}
}
| mit | C# |
c387c7ee383ed07c180693882d89ca6ac310da4d | Include max port | serilog/serilog-sinks-loggly | src/Serilog.Sinks.Loggly/Sinks/Loggly/LogglyConfigAdapter.cs | src/Serilog.Sinks.Loggly/Sinks/Loggly/LogglyConfigAdapter.cs | using System;
using Loggly.Config;
namespace Serilog.Sinks.Loggly
{
class LogglyConfigAdapter
{
public void ConfigureLogglyClient(LogglyConfiguration logglyConfiguration)
{
var config = LogglyConfig.Instance;
if (!string.IsNullOrWhiteSpace(logglyConfiguration.ApplicationName))
config.ApplicationName = logglyConfiguration.ApplicationName;
if (string.IsNullOrWhiteSpace(logglyConfiguration.CustomerToken))
throw new ArgumentNullException("CustomerToken", "CustomerToken is required");
config.CustomerToken = logglyConfiguration.CustomerToken;
config.IsEnabled = logglyConfiguration.IsEnabled;
foreach (var tag in logglyConfiguration.Tags)
{
config.TagConfig.Tags.Add(tag);
}
config.ThrowExceptions = logglyConfiguration.ThrowExceptions;
if (logglyConfiguration.LogTransport != TransportProtocol.Https)
config.Transport.LogTransport = (LogTransport)Enum.Parse(typeof(LogTransport), logglyConfiguration.LogTransport.ToString());
if (!string.IsNullOrWhiteSpace(logglyConfiguration.EndpointHostName))
config.Transport.EndpointHostname = logglyConfiguration.EndpointHostName;
if (logglyConfiguration.EndpointPort > 0 && logglyConfiguration.EndpointPort <= ushort.MaxValue)
config.Transport.EndpointPort = logglyConfiguration.EndpointPort;
config.Transport.IsOmitTimestamp = logglyConfiguration.OmitTimestamp;
config.Transport = config.Transport.GetCoercedToValidConfig();
}
}
}
| using System;
using Loggly.Config;
namespace Serilog.Sinks.Loggly
{
class LogglyConfigAdapter
{
public void ConfigureLogglyClient(LogglyConfiguration logglyConfiguration)
{
var config = LogglyConfig.Instance;
if (!string.IsNullOrWhiteSpace(logglyConfiguration.ApplicationName))
config.ApplicationName = logglyConfiguration.ApplicationName;
if (string.IsNullOrWhiteSpace(logglyConfiguration.CustomerToken))
throw new ArgumentNullException("CustomerToken", "CustomerToken is required");
config.CustomerToken = logglyConfiguration.CustomerToken;
config.IsEnabled = logglyConfiguration.IsEnabled;
foreach (var tag in logglyConfiguration.Tags)
{
config.TagConfig.Tags.Add(tag);
}
config.ThrowExceptions = logglyConfiguration.ThrowExceptions;
if (logglyConfiguration.LogTransport != TransportProtocol.Https)
config.Transport.LogTransport = (LogTransport)Enum.Parse(typeof(LogTransport), logglyConfiguration.LogTransport.ToString());
if (!string.IsNullOrWhiteSpace(logglyConfiguration.EndpointHostName))
config.Transport.EndpointHostname = logglyConfiguration.EndpointHostName;
if (logglyConfiguration.EndpointPort > 0 && logglyConfiguration.EndpointPort < ushort.MaxValue)
config.Transport.EndpointPort = logglyConfiguration.EndpointPort;
config.Transport.IsOmitTimestamp = logglyConfiguration.OmitTimestamp;
config.Transport = config.Transport.GetCoercedToValidConfig();
}
}
}
| apache-2.0 | C# |
543ed8a0874451e39732830a55b1a1db9cfcaa7e | Add support for updating a coupon's name | stripe/stripe-dotnet,richardlawley/stripe.net | src/Stripe.net/Services/Coupons/StripeCouponUpdateOptions.cs | src/Stripe.net/Services/Coupons/StripeCouponUpdateOptions.cs | using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripeCouponUpdateOptions : StripeBaseOptions, ISupportMetadata
{
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}
| using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripeCouponUpdateOptions : StripeBaseOptions, ISupportMetadata
{
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
}
}
| apache-2.0 | C# |
22aac6aaebf04189788f60b61f69a2ecde15cafc | Make EmptyReadOnlyCollection.Instance readonly. | nbarbettini/corefx,zhenlan/corefx,krk/corefx,Priya91/corefx-1,krk/corefx,alphonsekurian/corefx,Chrisboh/corefx,billwert/corefx,lggomez/corefx,alexperovich/corefx,iamjasonp/corefx,Ermiar/corefx,yizhang82/corefx,krk/corefx,cartermp/corefx,Petermarcu/corefx,nbarbettini/corefx,lggomez/corefx,twsouthwick/corefx,gkhanna79/corefx,alexperovich/corefx,mmitche/corefx,DnlHarvey/corefx,mmitche/corefx,YoupHulsebos/corefx,gkhanna79/corefx,cydhaselton/corefx,cydhaselton/corefx,iamjasonp/corefx,Petermarcu/corefx,cydhaselton/corefx,ravimeda/corefx,BrennanConroy/corefx,seanshpark/corefx,tijoytom/corefx,krk/corefx,ViktorHofer/corefx,ViktorHofer/corefx,Chrisboh/corefx,MaggieTsang/corefx,nchikanov/corefx,jhendrixMSFT/corefx,ViktorHofer/corefx,dotnet-bot/corefx,seanshpark/corefx,alphonsekurian/corefx,dhoehna/corefx,iamjasonp/corefx,lggomez/corefx,marksmeltzer/corefx,YoupHulsebos/corefx,zhenlan/corefx,mmitche/corefx,jhendrixMSFT/corefx,jlin177/corefx,DnlHarvey/corefx,wtgodbe/corefx,ericstj/corefx,wtgodbe/corefx,weltkante/corefx,stephenmichaelf/corefx,billwert/corefx,ericstj/corefx,Ermiar/corefx,JosephTremoulet/corefx,seanshpark/corefx,nbarbettini/corefx,nbarbettini/corefx,JosephTremoulet/corefx,tijoytom/corefx,MaggieTsang/corefx,alexperovich/corefx,JosephTremoulet/corefx,dsplaisted/corefx,wtgodbe/corefx,krytarowski/corefx,YoupHulsebos/corefx,parjong/corefx,the-dwyer/corefx,richlander/corefx,rahku/corefx,DnlHarvey/corefx,parjong/corefx,ptoonen/corefx,shmao/corefx,dotnet-bot/corefx,rahku/corefx,cartermp/corefx,ptoonen/corefx,axelheer/corefx,ericstj/corefx,weltkante/corefx,dhoehna/corefx,seanshpark/corefx,mazong1123/corefx,ellismg/corefx,mazong1123/corefx,jhendrixMSFT/corefx,nbarbettini/corefx,cartermp/corefx,weltkante/corefx,manu-silicon/corefx,gkhanna79/corefx,krk/corefx,nbarbettini/corefx,ellismg/corefx,rahku/corefx,dhoehna/corefx,jhendrixMSFT/corefx,rahku/corefx,iamjasonp/corefx,stephenmichaelf/corefx,shimingsg/corefx,khdang/corefx,mmitche/corefx,iamjasonp/corefx,tijoytom/corefx,ravimeda/corefx,ViktorHofer/corefx,jlin177/corefx,rubo/corefx,cartermp/corefx,JosephTremoulet/corefx,rahku/corefx,SGuyGe/corefx,khdang/corefx,axelheer/corefx,stephenmichaelf/corefx,stone-li/corefx,axelheer/corefx,krytarowski/corefx,billwert/corefx,zhenlan/corefx,khdang/corefx,shmao/corefx,shmao/corefx,gkhanna79/corefx,stephenmichaelf/corefx,weltkante/corefx,ellismg/corefx,alexperovich/corefx,parjong/corefx,iamjasonp/corefx,krytarowski/corefx,nchikanov/corefx,elijah6/corefx,lggomez/corefx,stone-li/corefx,Priya91/corefx-1,axelheer/corefx,ericstj/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,wtgodbe/corefx,shmao/corefx,jlin177/corefx,jlin177/corefx,Ermiar/corefx,cartermp/corefx,shimingsg/corefx,DnlHarvey/corefx,richlander/corefx,shimingsg/corefx,richlander/corefx,stone-li/corefx,rahku/corefx,khdang/corefx,YoupHulsebos/corefx,stone-li/corefx,stone-li/corefx,rjxby/corefx,seanshpark/corefx,alphonsekurian/corefx,ravimeda/corefx,tstringer/corefx,yizhang82/corefx,Priya91/corefx-1,ericstj/corefx,elijah6/corefx,stone-li/corefx,wtgodbe/corefx,rubo/corefx,rjxby/corefx,tijoytom/corefx,yizhang82/corefx,Ermiar/corefx,billwert/corefx,manu-silicon/corefx,ptoonen/corefx,YoupHulsebos/corefx,fgreinacher/corefx,stone-li/corefx,axelheer/corefx,wtgodbe/corefx,elijah6/corefx,Jiayili1/corefx,Chrisboh/corefx,billwert/corefx,ravimeda/corefx,jlin177/corefx,fgreinacher/corefx,elijah6/corefx,dotnet-bot/corefx,adamralph/corefx,twsouthwick/corefx,MaggieTsang/corefx,ravimeda/corefx,dotnet-bot/corefx,cydhaselton/corefx,manu-silicon/corefx,jlin177/corefx,ellismg/corefx,tijoytom/corefx,jhendrixMSFT/corefx,parjong/corefx,DnlHarvey/corefx,krytarowski/corefx,elijah6/corefx,parjong/corefx,mazong1123/corefx,ericstj/corefx,nbarbettini/corefx,twsouthwick/corefx,rubo/corefx,marksmeltzer/corefx,zhenlan/corefx,ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,cydhaselton/corefx,shimingsg/corefx,nchikanov/corefx,yizhang82/corefx,richlander/corefx,MaggieTsang/corefx,adamralph/corefx,stephenmichaelf/corefx,seanshpark/corefx,alexperovich/corefx,manu-silicon/corefx,the-dwyer/corefx,krytarowski/corefx,mazong1123/corefx,YoupHulsebos/corefx,ptoonen/corefx,gkhanna79/corefx,JosephTremoulet/corefx,ericstj/corefx,tstringer/corefx,parjong/corefx,JosephTremoulet/corefx,the-dwyer/corefx,alexperovich/corefx,alexperovich/corefx,ravimeda/corefx,Petermarcu/corefx,marksmeltzer/corefx,dsplaisted/corefx,dhoehna/corefx,rjxby/corefx,krytarowski/corefx,cydhaselton/corefx,dhoehna/corefx,billwert/corefx,fgreinacher/corefx,shimingsg/corefx,zhenlan/corefx,dhoehna/corefx,SGuyGe/corefx,seanshpark/corefx,lggomez/corefx,marksmeltzer/corefx,gkhanna79/corefx,yizhang82/corefx,Ermiar/corefx,tstringer/corefx,tstringer/corefx,mazong1123/corefx,richlander/corefx,gkhanna79/corefx,khdang/corefx,ptoonen/corefx,ViktorHofer/corefx,twsouthwick/corefx,JosephTremoulet/corefx,mmitche/corefx,ViktorHofer/corefx,Jiayili1/corefx,the-dwyer/corefx,Petermarcu/corefx,fgreinacher/corefx,dhoehna/corefx,krk/corefx,Petermarcu/corefx,Priya91/corefx-1,alphonsekurian/corefx,wtgodbe/corefx,jlin177/corefx,twsouthwick/corefx,rjxby/corefx,Jiayili1/corefx,nchikanov/corefx,mmitche/corefx,mazong1123/corefx,marksmeltzer/corefx,lggomez/corefx,weltkante/corefx,adamralph/corefx,mmitche/corefx,marksmeltzer/corefx,dotnet-bot/corefx,stephenmichaelf/corefx,khdang/corefx,zhenlan/corefx,rjxby/corefx,elijah6/corefx,Petermarcu/corefx,manu-silicon/corefx,Ermiar/corefx,ravimeda/corefx,Chrisboh/corefx,cydhaselton/corefx,manu-silicon/corefx,mazong1123/corefx,manu-silicon/corefx,richlander/corefx,the-dwyer/corefx,twsouthwick/corefx,rubo/corefx,rahku/corefx,Jiayili1/corefx,BrennanConroy/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,krytarowski/corefx,ptoonen/corefx,richlander/corefx,shmao/corefx,SGuyGe/corefx,the-dwyer/corefx,rjxby/corefx,tstringer/corefx,parjong/corefx,SGuyGe/corefx,Chrisboh/corefx,tstringer/corefx,MaggieTsang/corefx,Petermarcu/corefx,ellismg/corefx,dotnet-bot/corefx,jhendrixMSFT/corefx,nchikanov/corefx,lggomez/corefx,DnlHarvey/corefx,ellismg/corefx,the-dwyer/corefx,dsplaisted/corefx,Priya91/corefx-1,shimingsg/corefx,iamjasonp/corefx,elijah6/corefx,alphonsekurian/corefx,Priya91/corefx-1,yizhang82/corefx,alphonsekurian/corefx,zhenlan/corefx,shimingsg/corefx,tijoytom/corefx,shmao/corefx,billwert/corefx,twsouthwick/corefx,rubo/corefx,SGuyGe/corefx,dotnet-bot/corefx,shmao/corefx,tijoytom/corefx,SGuyGe/corefx,MaggieTsang/corefx,nchikanov/corefx,nchikanov/corefx,krk/corefx,alphonsekurian/corefx,cartermp/corefx,Jiayili1/corefx,jhendrixMSFT/corefx,marksmeltzer/corefx,Chrisboh/corefx,rjxby/corefx,weltkante/corefx,yizhang82/corefx,MaggieTsang/corefx,Ermiar/corefx,BrennanConroy/corefx,axelheer/corefx,weltkante/corefx | src/Common/src/System/Dynamic/Utils/EmptyReadOnlyCollection.cs | src/Common/src/System/Dynamic/Utils/EmptyReadOnlyCollection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
namespace System.Dynamic.Utils
{
internal static class EmptyReadOnlyCollection<T>
{
public readonly static ReadOnlyCollection<T> Instance = new TrueReadOnlyCollection<T>(Array.Empty<T>());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
namespace System.Dynamic.Utils
{
internal static class EmptyReadOnlyCollection<T>
{
public static ReadOnlyCollection<T> Instance = new TrueReadOnlyCollection<T>(Array.Empty<T>());
}
}
| mit | C# |
0384dab600b9b0cc1226d929bed1095e6f22ac22 | Add support for `OutOfBandAmount` on `CreditNote` creation | stripe/stripe-dotnet | src/Stripe.net/Services/CreditNotes/CreditNoteCreateOptions.cs | src/Stripe.net/Services/CreditNotes/CreditNoteCreateOptions.cs | namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class CreditNoteCreateOptions : BaseOptions, IHasMetadata
{
/// <summary>
/// Credit note amount.
/// </summary>
[JsonProperty("amount")]
public long? Amount { get; set; }
/// <summary>
/// Amount to credit the customer balance.
/// </summary>
[JsonProperty("credit_amount")]
public long? CreditAmount { get; set; }
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string Invoice { get; set; }
/// <summary>
/// Credit note memo.
/// </summary>
[JsonProperty("memo")]
public string Memo { get; set; }
/// <summary>
/// Set of key-value pairs that you can attach to an object. This can be useful for storing
/// additional information about the object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// The integer amount representing the amount that is credited outside of Stripe.
/// </summary>
[JsonProperty("out_of_band_amount")]
public long? OutOfBandAmount { get; set; }
/// <summary>
/// Reason for issuing this credit note, one of <c>duplicate</c>, <c>fraudulent</c>,
/// <c>order_change</c>, or <c>product_unsatisfactory</c>.
/// </summary>
[JsonProperty("reason")]
public string Reason { get; set; }
/// <summary>
/// ID of an existing refund to link this credit note to.
/// </summary>
[JsonProperty("refund")]
public string Refund { get; set; }
/// <summary>
/// Amount to refund. If set, a refund will be created for the charge associated with the
/// invoice.
/// </summary>
[JsonProperty("refund_amount")]
public long? RefundAmount { get; set; }
}
}
| namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class CreditNoteCreateOptions : BaseOptions, IHasMetadata
{
/// <summary>
/// Credit note amount.
/// </summary>
[JsonProperty("amount")]
public long? Amount { get; set; }
/// <summary>
/// Amount to credit the customer balance.
/// </summary>
[JsonProperty("credit_amount")]
public long? CreditAmount { get; set; }
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string Invoice { get; set; }
/// <summary>
/// Credit note memo.
/// </summary>
[JsonProperty("memo")]
public string Memo { get; set; }
/// <summary>
/// Set of key-value pairs that you can attach to an object. This can be useful for storing
/// additional information about the object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// Reason for issuing this credit note, one of <c>duplicate</c>, <c>fraudulent</c>,
/// <c>order_change</c>, or <c>product_unsatisfactory</c>.
/// </summary>
[JsonProperty("reason")]
public string Reason { get; set; }
/// <summary>
/// ID of an existing refund to link this credit note to.
/// </summary>
[JsonProperty("refund")]
public string Refund { get; set; }
/// <summary>
/// Amount to refund. If set, a refund will be created for the charge associated with the
/// invoice.
/// </summary>
[JsonProperty("refund_amount")]
public long? RefundAmount { get; set; }
}
}
| apache-2.0 | C# |
4571ae5635d1ae20b44683d8221515a8492b577b | add comment | bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL | CSharpGL/Scene/SceneNodes/RenderUnits/IBufferSource.cs | CSharpGL/Scene/SceneNodes/RenderUnits/IBufferSource.cs | using System.Collections.Generic;
namespace CSharpGL
{
/// <summary>
/// Data for CPU(model) -> Data for GPU(opengl buffer)
/// <para>从模型的数据格式转换为<see cref="GLBuffer"/></para>,
/// <see cref="GLBuffer"/>则可用于控制GPU的渲染操作。
/// </summary>
public interface IBufferSource
{
/// <summary>
/// Gets vertex buffer of some vertex attribute specified with <paramref name="bufferName"/>.
/// <para>The vertex buffer is sliced into blocks of same size(except the last one when the remainder is not 0.) I recommend 1024*1024*4 as block size, which is the block size in OVITO.</para>
/// </summary>
/// <param name="bufferName">CPU代码指定的buffer名字,用以区分各个用途的buffer。</param>
/// <returns></returns>
IEnumerable<VertexBuffer> GetVertexAttributeBuffer(string bufferName);
/// <summary>
/// </summary>
/// <returns></returns>
IEnumerable<IDrawCommand> GetDrawCommand();
}
} | using System.Collections.Generic;
namespace CSharpGL
{
/// <summary>
/// Data for CPU(model) -> Data for GPU(opengl buffer)
/// <para>从模型的数据格式转换为<see cref="GLBuffer"/></para>,
/// <see cref="GLBuffer"/>则可用于控制GPU的渲染操作。
/// </summary>
public interface IBufferSource
{
/// <summary>
/// 获取顶点某种属性的<see cref="VertexBuffer"/>。
/// </summary>
/// <param name="bufferName">CPU代码指定的buffer名字,用以区分各个用途的buffer。</param>
/// <returns></returns>
IEnumerable<VertexBuffer> GetVertexAttributeBuffer(string bufferName);
/// <summary>
/// </summary>
/// <returns></returns>
IEnumerable<IDrawCommand> GetDrawCommand();
}
} | mit | C# |
4103d8872be1ec6652a20e081ec477fb53727ee6 | update ilogger aware | CatLib/Framework,yb199478/catlib | CatLib.VS/CatLib/API/Debugger/Internal/ILoggerAware.cs | CatLib.VS/CatLib/API/Debugger/Internal/ILoggerAware.cs | /*
* This file is part of the CatLib package.
*
* (c) Yu Bin <support@catlib.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Document: http://catlib.io/
*/
namespace CatLib.API.Debugger
{
/// <summary>
/// 记录器实例接口
/// </summary>
public interface ILoggerAware
{
/// <summary>
/// 设定记录器实例接口
/// </summary>
/// <param name="logger">记录器</param>
void SetLogger(ILogger logger);
}
}
| /*
* This file is part of the CatLib package.
*
* (c) Yu Bin <support@catlib.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Document: http://catlib.io/
*/
namespace CatLib.API.Debugger
{
/// <summary>
/// 设定记录器实例接口
/// </summary>
public interface ILoggerAware
{
/// <summary>
/// 设定记录器实例接口
/// </summary>
/// <param name="logger">记录器</param>
void SetLogger(ILogger logger);
}
}
| unknown | C# |
51cc2cb3e4fbeddf8d998837e67ee8bd50d5204c | Unify Apache License headers in .Net code (Part #2) | jwang98052/reef,dongjoon-hyun/reef,dougmsft/reef,singlis/reef,singlis/reef,dongjoon-hyun/reef,jwang98052/incubator-reef,tcNickolas/reef,tcNickolas/incubator-reef,jsjason/incubator-reef,jsjason/incubator-reef,jwang98052/reef,apache/incubator-reef,dkm2110/Microsoft-cisl,jsjason/incubator-reef,nachocano/incubator-reef,dafrista/incubator-reef,jwang98052/incubator-reef,zerg-junior/incubator-reef,markusweimer/reef,shravanmn/reef,dafrista/incubator-reef,dafrista/incubator-reef,afchung/incubator-reef,nachocano/incubator-reef,dkm2110/Microsoft-cisl,motus/reef,markusweimer/incubator-reef,shulmanb/reef,apache/incubator-reef,dougmsft/reef,motus/reef,dougmsft/reef,shravanmn/reef,jwang98052/incubator-reef,nachocano/incubator-reef,shravanmn/reef,zerg-junior/incubator-reef,dkm2110/veyor,dongjoon-hyun/reef,dkm2110/veyor,dongjoon-hyun/incubator-reef,anupam128/reef,anupam128/reef,dougmsft/reef,apache/reef,afchung/incubator-reef,dougmsft/reef,markusweimer/incubator-reef,shulmanb/reef,dongjoon-hyun/incubator-reef,apache/incubator-reef,apache/reef,shulmanb/reef,markusweimer/reef,afchung/reef,dkm2110/veyor,nachocano/incubator-reef,dongjoon-hyun/incubator-reef,motus/reef,afchung/reef,markusweimer/incubator-reef,zerg-junior/incubator-reef,nachocano/incubator-reef,nachocano/incubator-reef,dafrista/incubator-reef,apache/reef,dougmsft/reef,singlis/reef,apache/incubator-reef,markusweimer/incubator-reef,markusweimer/reef,tcNickolas/reef,tcNickolas/incubator-reef,tcNickolas/reef,afchung/incubator-reef,shulmanb/reef,jsjason/incubator-reef,dongjoon-hyun/reef,anupam128/reef,dongjoon-hyun/incubator-reef,tcNickolas/reef,tcNickolas/incubator-reef,dkm2110/Microsoft-cisl,shulmanb/reef,jsjason/incubator-reef,nachocano/incubator-reef,jwang98052/reef,jsjason/incubator-reef,markusweimer/reef,dkm2110/veyor,dongjoon-hyun/reef,motus/reef,jwang98052/reef,afchung/incubator-reef,dkm2110/Microsoft-cisl,shulmanb/reef,afchung/reef,shravanmn/reef,anupam128/reef,apache/incubator-reef,dkm2110/Microsoft-cisl,shulmanb/reef,dongjoon-hyun/reef,shravanmn/reef,tcNickolas/reef,dafrista/incubator-reef,zerg-junior/incubator-reef,tcNickolas/incubator-reef,afchung/reef,tcNickolas/incubator-reef,dafrista/incubator-reef,jwang98052/incubator-reef,afchung/incubator-reef,markusweimer/reef,jwang98052/incubator-reef,jsjason/incubator-reef,anupam128/reef,apache/incubator-reef,afchung/incubator-reef,dongjoon-hyun/reef,dkm2110/veyor,shravanmn/reef,dafrista/incubator-reef,dkm2110/Microsoft-cisl,apache/reef,dongjoon-hyun/incubator-reef,dkm2110/veyor,zerg-junior/incubator-reef,apache/reef,jwang98052/incubator-reef,tcNickolas/incubator-reef,tcNickolas/incubator-reef,afchung/reef,zerg-junior/incubator-reef,afchung/reef,apache/reef,markusweimer/incubator-reef,apache/incubator-reef,markusweimer/reef,afchung/incubator-reef,tcNickolas/reef,dougmsft/reef,afchung/reef,tcNickolas/reef,dongjoon-hyun/incubator-reef,markusweimer/reef,dkm2110/veyor,singlis/reef,jwang98052/incubator-reef,jwang98052/reef,markusweimer/incubator-reef,jwang98052/reef,zerg-junior/incubator-reef,motus/reef,markusweimer/incubator-reef,singlis/reef,apache/reef,shravanmn/reef,motus/reef,singlis/reef,jwang98052/reef,singlis/reef,dkm2110/Microsoft-cisl,dongjoon-hyun/incubator-reef,motus/reef,anupam128/reef,anupam128/reef | lang/cs/Org.Apache.REEF.Wake.Tests/Properties/AssemblyInfo.cs | lang/cs/Org.Apache.REEF.Wake.Tests/Properties/AssemblyInfo.cs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
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("Org.Apache.REEF.Wake.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Org.Apache.REEF.Wake.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("68a2ef80-e51b-4abb-9ccc-81354e152758")]
// 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.14.0.0")]
[assembly: AssemblyFileVersion("0.14.0.0")]
| /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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("Org.Apache.REEF.Wake.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Org.Apache.REEF.Wake.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("68a2ef80-e51b-4abb-9ccc-81354e152758")]
// 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.14.0.0")]
[assembly: AssemblyFileVersion("0.14.0.0")]
| apache-2.0 | C# |
fbfe4e40ec98661e34a71e49fd1963bb1cd27113 | Add Shader as a shortcut type | intentor/shortcuter | src/Assets/Plugins/Editor/Shortcuter/Util/TypeUtils.cs | src/Assets/Plugins/Editor/Shortcuter/Util/TypeUtils.cs | using UnityEngine;
using UnityEditor.Animations;
using UnityEngine.Audio;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Intentor.Shortcuter.Util {
/// <summary>
/// Utility class for types.
/// </summary>
public static class TypeUtils {
/// <summary>
/// Gets all available shortcut types.
/// </summary>
/// <returns>The shortcut types.</returns>
public static Dictionary<string, System.Type> GetShortcutTypes() {
var types = new Dictionary<string, System.Type>();
types.Add("Scene", null);
types.Add("Prefab", typeof(UnityEngine.Object));
types.Add("Script", typeof(UnityEngine.Object));
types.Add("AnimatorController", typeof(AnimatorController));
types.Add("Animation", typeof(Animation));
types.Add("AudioMixer", typeof(AudioMixer));
types.Add("Material", typeof(Material));
types.Add("Shader", typeof(Shader));
var scriptableObjects = GetTypesDerivedOf(typeof(ScriptableObject));
for (var index = 0; index < scriptableObjects.Length; index++) {
var type = scriptableObjects[index];
types.Add(type.FullName, type);
}
return types;
}
/// <summary>
/// Gets a shortcut type from a type name.
/// </summary>
/// <param name="typeName">Type name.</param>
public static Type GetShortcutType(string typeName) {
var shortcutTypes = GetShortcutTypes();
return shortcutTypes[typeName];
}
/// <summary>
/// Gets all available types derived of a given type.
/// </summary>
/// <remarks>>
/// All types from Unity are not considered on the search.
/// </remarks>
/// <param name="baseType">Base type.</param>
/// <returns>The types derived of.</returns>
public static Type[] GetTypesDerivedOf(Type baseType) {
var types = new List<Type>();
//Looks for assignable types in all available assemblies.
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int assemblyIndex = 0; assemblyIndex < assemblies.Length; assemblyIndex++) {
var assembly = assemblies[assemblyIndex];
if (assembly.FullName.StartsWith("Unity") ||
assembly.FullName.StartsWith("Boo") ||
assembly.FullName.StartsWith("Mono") ||
assembly.FullName.StartsWith("System") ||
assembly.FullName.StartsWith("mscorlib")) {
continue;
}
try {
var allTypes = assemblies[assemblyIndex].GetTypes();
for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) {
var type = allTypes[typeIndex];
if (type.IsSubclassOf(baseType)) {
types.Add(type);
}
}
} catch (ReflectionTypeLoadException) {
//If the assembly can't be read, just continue.
continue;
}
}
return types.ToArray();
}
}
} | using UnityEngine;
using UnityEditor.Animations;
using UnityEngine.Audio;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Intentor.Shortcuter.Util {
/// <summary>
/// Utility class for types.
/// </summary>
public static class TypeUtils {
/// <summary>
/// Gets all available shortcut types.
/// </summary>
/// <returns>The shortcut types.</returns>
public static Dictionary<string, System.Type> GetShortcutTypes() {
var types = new Dictionary<string, System.Type>();
types.Add("Scene", null);
types.Add("Prefab", typeof(UnityEngine.Object));
types.Add("Script", typeof(UnityEngine.Object));
types.Add("AnimatorController", typeof(AnimatorController));
types.Add("Animation", typeof(Animation));
types.Add("AudioMixer", typeof(AudioMixer));
types.Add("Material", typeof(Material));
var scriptableObjects = GetTypesDerivedOf(typeof(ScriptableObject));
for (var index = 0; index < scriptableObjects.Length; index++) {
var type = scriptableObjects[index];
types.Add(type.FullName, type);
}
return types;
}
/// <summary>
/// Gets a shortcut type from a type name.
/// </summary>
/// <param name="typeName">Type name.</param>
public static Type GetShortcutType(string typeName) {
var shortcutTypes = GetShortcutTypes();
return shortcutTypes[typeName];
}
/// <summary>
/// Gets all available types derived of a given type.
/// </summary>
/// <remarks>>
/// All types from Unity are not considered on the search.
/// </remarks>
/// <param name="baseType">Base type.</param>
/// <returns>The types derived of.</returns>
public static Type[] GetTypesDerivedOf(Type baseType) {
var types = new List<Type>();
//Looks for assignable types in all available assemblies.
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int assemblyIndex = 0; assemblyIndex < assemblies.Length; assemblyIndex++) {
var assembly = assemblies[assemblyIndex];
if (assembly.FullName.StartsWith("Unity") ||
assembly.FullName.StartsWith("Boo") ||
assembly.FullName.StartsWith("Mono") ||
assembly.FullName.StartsWith("System") ||
assembly.FullName.StartsWith("mscorlib")) {
continue;
}
try {
var allTypes = assemblies[assemblyIndex].GetTypes();
for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) {
var type = allTypes[typeIndex];
if (type.IsSubclassOf(baseType)) {
types.Add(type);
}
}
} catch (ReflectionTypeLoadException) {
//If the assembly can't be read, just continue.
continue;
}
}
return types.ToArray();
}
}
} | mit | C# |
947f3bed84e4b9af2c75d57911714d06c0741cc6 | Use UpdateSourceTrigger.PropertyChanged for password controls | EdonGashi/WpfMaterialForms | src/MaterialForms/Controls/PasswordTextControl.xaml.cs | src/MaterialForms/Controls/PasswordTextControl.xaml.cs | using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace MaterialForms.Controls
{
/// <summary>
/// Interaction logic for SingleLineTextControl.xaml
/// </summary>
public partial class PasswordTextControl : UserControl
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password",
typeof(SecureString),
typeof(PasswordBox),
new PropertyMetadata(default(SecureString)));
public SecureString Password
{
get { return (SecureString)ValueHolderControl.GetValue(PasswordProperty); }
set { ValueHolderControl.SetValue(PasswordProperty, value); }
}
public PasswordTextControl()
{
InitializeComponent();
ValueHolderControl.PasswordChanged += (sender, args) =>
{
Password = ((PasswordBox)sender).SecurePassword;
};
var binding = new Binding("Value")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
ValueHolderControl.SetBinding(PasswordProperty, binding);
}
}
}
| using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace MaterialForms.Controls
{
/// <summary>
/// Interaction logic for SingleLineTextControl.xaml
/// </summary>
public partial class PasswordTextControl : UserControl
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.Register("Password",
typeof(SecureString),
typeof(PasswordBox),
new PropertyMetadata(default(SecureString)));
public SecureString Password
{
get { return (SecureString)ValueHolderControl.GetValue(PasswordProperty); }
set { ValueHolderControl.SetValue(PasswordProperty, value); }
}
public PasswordTextControl()
{
InitializeComponent();
ValueHolderControl.PasswordChanged += (sender, args) =>
{
Password = ((PasswordBox)sender).SecurePassword;
};
var binding = new Binding("Value")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus
};
ValueHolderControl.SetBinding(PasswordProperty, binding);
}
}
}
| mit | C# |
931183031795a23655d14cc4353aae53665fd3c7 | Fix for GetClientIpAddress in OWIN-hosting | andyshao/WebAPIContrib,yonglehou/WebAPIContrib,modulexcite/WebAPIContrib,WebApiContrib/WebAPIContrib,yonglehou/WebAPIContrib,andyshao/WebAPIContrib,TerraVenil/WebAPIContrib,modulexcite/WebAPIContrib,TerraVenil/WebAPIContrib,WebApiContrib/WebAPIContrib | src/WebApiContrib/Http/HttpRequestMessageExtensions.cs | src/WebApiContrib/Http/HttpRequestMessageExtensions.cs | using System;
using System.Net.Http;
namespace WebApiContrib.Http
{
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
private const string OwinContext = "MS_OwinContext";
public static bool IsLocal(this HttpRequestMessage request)
{
var localFlag = request.Properties["MS_IsLocal"] as Lazy<bool>;
return localFlag != null && localFlag.Value;
}
public static string GetClientIpAddress(this HttpRequestMessage request)
{
//Web-hosting
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
//Self-hosting
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
//Owin-hosting
if (request.Properties.ContainsKey(OwinContext))
{
dynamic ctx = request.Properties[OwinContext];
if (ctx != null)
{
return ctx.Request.RemoteIpAddress;
}
}
return null;
}
}
}
| using System;
using System.Net.Http;
namespace WebApiContrib.Http
{
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static bool IsLocal(this HttpRequestMessage request)
{
var localFlag = request.Properties["MS_IsLocal"] as Lazy<bool>;
return localFlag != null && localFlag.Value;
}
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
}
}
| mit | C# |
16001f42c3bb0aade68c2a3e3750305070aefe8d | Add a better message if the SimpleAssetService doesn't have an asset | KirillOsenkov/roslyn,nguerrera/roslyn,eriawan/roslyn,heejaechang/roslyn,wvdd007/roslyn,dotnet/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,weltkante/roslyn,eriawan/roslyn,physhi/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,davkean/roslyn,tannergooding/roslyn,physhi/roslyn,agocke/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,bartdesmet/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,weltkante/roslyn,brettfo/roslyn,mavasani/roslyn,reaction1989/roslyn,jmarolf/roslyn,AmadeusW/roslyn,reaction1989/roslyn,agocke/roslyn,abock/roslyn,KevinRansom/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,reaction1989/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,aelij/roslyn,tmat/roslyn,tmat/roslyn,genlu/roslyn,stephentoub/roslyn,bartdesmet/roslyn,weltkante/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,davkean/roslyn,abock/roslyn,davkean/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,mavasani/roslyn,bartdesmet/roslyn,brettfo/roslyn,abock/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,tmat/roslyn,gafter/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,nguerrera/roslyn,brettfo/roslyn,stephentoub/roslyn,dotnet/roslyn,nguerrera/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,gafter/roslyn,genlu/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,diryboy/roslyn,eriawan/roslyn,genlu/roslyn,agocke/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,sharwell/roslyn,physhi/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,aelij/roslyn | src/Workspaces/Remote/Core/Shared/SimpleAssetSource.cs | src/Workspaces/Remote/Core/Shared/SimpleAssetSource.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Serialization;
namespace Microsoft.CodeAnalysis.Remote.Shared
{
/// <summary>
/// provide asset from given map at the creation
/// </summary>
internal class SimpleAssetSource : AssetSource
{
private readonly IReadOnlyDictionary<Checksum, object> _map;
public SimpleAssetSource(AssetStorage assetStorage, IReadOnlyDictionary<Checksum, object> map) :
base(assetStorage)
{
_map = map;
}
public override Task<IList<(Checksum, object)>> RequestAssetsAsync(
int serviceId, ISet<Checksum> checksums, ISerializerService serializerService, CancellationToken cancellationToken)
{
var list = new List<(Checksum, object)>();
foreach (var checksum in checksums)
{
if (_map.TryGetValue(checksum, out var data))
{
list.Add(ValueTuple.Create(checksum, data));
}
else
{
Debug.Fail($"Unable to find asset for {checksum}");
}
}
return Task.FromResult<IList<(Checksum, object)>>(list);
}
}
}
| // 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.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Serialization;
namespace Microsoft.CodeAnalysis.Remote.Shared
{
/// <summary>
/// provide asset from given map at the creation
/// </summary>
internal class SimpleAssetSource : AssetSource
{
private readonly IReadOnlyDictionary<Checksum, object> _map;
public SimpleAssetSource(AssetStorage assetStorage, IReadOnlyDictionary<Checksum, object> map) :
base(assetStorage)
{
_map = map;
}
public override Task<IList<(Checksum, object)>> RequestAssetsAsync(
int serviceId, ISet<Checksum> checksums, ISerializerService serializerService, CancellationToken cancellationToken)
{
var list = new List<(Checksum, object)>();
foreach (var checksum in checksums)
{
if (_map.TryGetValue(checksum, out var data))
{
list.Add(ValueTuple.Create(checksum, data));
continue;
}
Debug.Fail("How?");
}
return Task.FromResult<IList<(Checksum, object)>>(list);
}
}
}
| mit | C# |
80af203e9646fadc18c4cefade5373457292bc90 | Update UrlTemplates.cs | RapidScada/scada,RapidScada/scada,RapidScada/scada,RapidScada/scada | ScadaWeb/ScadaWeb/ScadaWebCommon/Shell/UrlTemplates.cs | ScadaWeb/ScadaWeb/ScadaWebCommon/Shell/UrlTemplates.cs | /*
* Copyright 2018 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : ScadaWebCommon
* Summary : URL templates of the web application pages
*
* Author : Mikhail Shiryaev
* Created : 2016
* Modified : 2018
*/
namespace Scada.Web.Shell
{
/// <summary>
/// URL templates of the web application pages
/// <para>Шаблоны адресов страниц веб-приложения</para>
/// </summary>
public static class UrlTemplates
{
/// <summary>
/// Вход в систему с указанием ссылки для возврата
/// </summary>
public const string LoginWithReturn = "~/Login.aspx?return={0}";
/// <summary>
/// Вход в систему с указанием ссылки для возврата и выводом сообщения
/// </summary>
public const string LoginWithAlert = "~/Login.aspx?return={0}&alert={1}";
/// <summary>
/// Информация о пользователе
/// </summary>
public const string User = "~/User.aspx?userID={0}";
/// <summary>
/// Представление
/// </summary>
public const string View = "~/View.aspx?viewID={0}";
/// <summary>
/// Отсутствующее представление
/// </summary>
public const string NoView = "~/NoView.aspx";
/// <summary>
/// Сайт сбора статистики
/// </summary>
public const string Stats = "rapidscada.net/stats/?serverID={0}";
}
}
| /*
* Copyright 2018 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : ScadaWebCommon
* Summary : URL templates of the web application pages
*
* Author : Mikhail Shiryaev
* Created : 2016
* Modified : 2018
*/
namespace Scada.Web.Shell
{
/// <summary>
/// URL templates of the web application pages
/// <para>Шаблоны адресов страниц веб-приложения</para>
/// </summary>
public static class UrlTemplates
{
/// <summary>
/// Вход в систему с указанием ссылки для возврата
/// </summary>
public const string LoginWithReturn = "~/Login.aspx?return={0}";
/// <summary>
/// Вход в систему с указанием ссылки для возврата и выводом сообщения
/// </summary>
public const string LoginWithAlert = "~/Login.aspx?return={0}&alert={1}";
/// <summary>
/// Информация о пользователе
/// </summary>
public const string User = "~/User.aspx?userID={0}";
/// <summary>
/// Представление
/// </summary>
public const string View = "~/View.aspx?viewID={0}";
/// <summary>
/// Отсутствующее представление
/// </summary>
public const string NoView = "~/NoView.aspx";
/// <summary>
/// Сайт сбора статистики
/// </summary>
public const string Stats = "stats.rapidscada.net?serverID={0}";
}
}
| apache-2.0 | C# |
fe29b093365bdff0309893bd3a1db13c4fd2bb9c | Make a whitespace change to test the TeamCity upgrade. | ekyoung/contact-repository,ekyoung/contact-repository | Source/Web/Models/RelationshipModel.cs | Source/Web/Models/RelationshipModel.cs | using System.Runtime.Serialization;
namespace Web.Models
{
[DataContract]
public class RelationshipModel
{
[DataMember]
public string Name { get; set; }
}
} | using System.Runtime.Serialization;
namespace Web.Models
{
[DataContract]
public class RelationshipModel
{
[DataMember]
public string Name { get; set; }
}
} | mit | C# |
8ac4a4e73595dfd0dd8dba52f9d740683862580a | Fix unit test | holthe/AsyncAnalyzers,holthe/AsyncAnalyzers | AsyncAnalyzers.Test/AsyncMethodConfigureAwaitAnalyzerTests.cs | AsyncAnalyzers.Test/AsyncMethodConfigureAwaitAnalyzerTests.cs | using System.IO;
using AsyncAnalyzers.ConfigureAwait;
using AsyncAnalyzers.Test.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace AsyncAnalyzers.Test
{
public class AsyncMethodConfigureAwaitAnalyzerTests : TestBase
{
private DiagnosticResult _expectedDiagnosticResultForMissingConfigureAwait;
public AsyncMethodConfigureAwaitAnalyzerTests()
{
_expectedDiagnosticResultForMissingConfigureAwait = new DiagnosticResult
{
Id = ConfigureAwaitAnalyzer.DiagnosticId,
Message = string.Format(ConfigureAwaitAnalyzer.MessagForMissingConfigureAwait, "LibraryMethodAsync"),
Severity = DiagnosticSeverity.Warning
};
}
[Theory]
[InlineData("LibraryMethod.NoConfigureAwait.cs", 11, 20)]
[InlineData("LibraryMethod.ConfigureAwaitTrue.cs", 10, 20)]
public void LibraryMethod_NoConfigureAwaitFalse_DiagnosticFound_CanFix(string testFile, int diagnosticLine, int diagnosticColumn)
{
var test = File.ReadAllText(Path.Combine(TestDataInputDir, testFile));
_expectedDiagnosticResultForMissingConfigureAwait.Locations =
new[]
{
new DiagnosticResultLocation(DiagnosticLocationPath, diagnosticLine, diagnosticColumn)
};
VerifyCSharpDiagnostic(test, _expectedDiagnosticResultForMissingConfigureAwait);
var fixtest = File.ReadAllText(Path.Combine(TestDataOutputDir, testFile));
VerifyCSharpFix(test, fixtest);
}
[Fact]
public void LibraryMethod_ConfigureAwaitFalse_NoDiagnosticFound()
{
const string testFile = "LibraryMethod.ConfigureAwaitFalse.cs";
var test = File.ReadAllText(Path.Combine(TestDataInputDir, testFile));
VerifyCSharpDiagnostic(test);
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new ConfigureAwaitCodeFixProvider();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new ConfigureAwaitAnalyzer();
}
}
} | using System.IO;
using AsyncAnalyzers.ConfigureAwait;
using AsyncAnalyzers.Test.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace AsyncAnalyzers.Test
{
public class AsyncMethodConfigureAwaitAnalyzerTests : TestBase
{
private DiagnosticResult _expectedDiagnosticResultForMissingConfigureAwait;
public AsyncMethodConfigureAwaitAnalyzerTests()
{
_expectedDiagnosticResultForMissingConfigureAwait = new DiagnosticResult
{
Id = ConfigureAwaitAnalyzer.DiagnosticId,
Message = string.Format(ConfigureAwaitAnalyzer.MessagForMissingConfigureAwait, "LibraryMethodAsync"),
Severity = DiagnosticSeverity.Warning
};
}
[Theory]
[InlineData("LibraryMethod.NoConfigureAwait.cs")]
[InlineData("LibraryMethod.ConfigureAwaitTrue.cs")]
public void LibraryMethod_NoConfigureAwaitFalse_DiagnosticFound_CanFix(string testFile)
{
var test = File.ReadAllText(Path.Combine(TestDataInputDir, testFile));
_expectedDiagnosticResultForMissingConfigureAwait.Locations =
new[]
{
new DiagnosticResultLocation(DiagnosticLocationPath, 11, 20)
};
VerifyCSharpDiagnostic(test, _expectedDiagnosticResultForMissingConfigureAwait);
var fixtest = File.ReadAllText(Path.Combine(TestDataOutputDir, testFile));
VerifyCSharpFix(test, fixtest);
}
[Fact]
public void LibraryMethod_ConfigureAwaitFalse_NoDiagnosticFound()
{
const string testFile = "LibraryMethod.ConfigureAwaitFalse.cs";
var test = File.ReadAllText(Path.Combine(TestDataInputDir, testFile));
VerifyCSharpDiagnostic(test);
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new ConfigureAwaitCodeFixProvider();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new ConfigureAwaitAnalyzer();
}
}
} | mit | C# |
192bb73ac86d110db5ce309398d5ca41f7e0de5f | fix binary reader | lovewitty/Titanium,amitla/Titanium | Titanium.HTTPProxyServer/Utility/CustomBinaryReader.cs | Titanium.HTTPProxyServer/Utility/CustomBinaryReader.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Titanium.HTTPProxyServer
{
public class CustomBinaryReader : BinaryReader
{
public CustomBinaryReader(Stream stream, Encoding encoding)
: base(stream, encoding)
{
}
public string ReadLine()
{
char[] buf = new char[1];
StringBuilder _readBuffer = new StringBuilder();
try
{
var charsRead = 0;
char lastChar = new char();
while ((charsRead = base.Read(buf, 0, 1)) > 0)
{
if (lastChar == '\r' && buf[0] == '\n')
{
return _readBuffer.Remove(_readBuffer.Length - 1, 1).ToString();
}
else
if (buf[0] == '\0')
{
return _readBuffer.ToString();
}
else
_readBuffer.Append(buf[0]);
lastChar = buf[0];
}
return _readBuffer.ToString();
}
catch (IOException)
{ return _readBuffer.ToString(); }
catch (Exception e)
{ throw e; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Titanium.HTTPProxyServer
{
public class CustomBinaryReader : BinaryReader
{
public CustomBinaryReader(Stream stream, Encoding encoding)
: base(stream, encoding)
{
}
public string ReadLine()
{
try
{
char[] buf = new char[1];
StringBuilder _readBuffer = new StringBuilder();
var charsRead = 0;
char lastChar = new char();
while ((charsRead = base.Read(buf, 0, 1)) > 0)
{
if (lastChar == '\r' && buf[0] == '\n')
{
return _readBuffer.Remove(_readBuffer.Length - 1, 1).ToString();
}
else
if (buf[0] == '\0')
{
return _readBuffer.ToString();
}
else
_readBuffer.Append(buf[0]);
lastChar = buf[0];
}
return _readBuffer.ToString();
}
catch { throw new EndOfStreamException(); }
}
}
}
| mit | C# |
471c44334a322f2b8de8f0bca69decc6c3cc4e6a | Increase toleranceSeconds in SafeWait_PollingInterval_GreaterThanTimeout test | atata-framework/atata-webdriverextras,atata-framework/atata-webdriverextras | src/Atata.WebDriverExtras.Tests/SafeWaitTests.cs | src/Atata.WebDriverExtras.Tests/SafeWaitTests.cs | using System;
using System.Threading;
using NUnit.Framework;
namespace Atata.WebDriverExtras.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class SafeWaitTests
{
private SafeWait<object> wait;
[SetUp]
public void SetUp()
{
wait = new SafeWait<object>(new object())
{
Timeout = TimeSpan.FromSeconds(.3),
PollingInterval = TimeSpan.FromSeconds(.05)
};
}
[Test]
public void SafeWait_Success_Immediate()
{
using (StopwatchAsserter.Within(0, .01))
wait.Until(_ =>
{
return true;
});
}
[Test]
public void SafeWait_Timeout()
{
using (StopwatchAsserter.Within(.3, .01))
wait.Until(_ =>
{
return false;
});
}
[Test]
public void SafeWait_PollingInterval()
{
using (StopwatchAsserter.Within(.3, .2))
wait.Until(_ =>
{
Thread.Sleep(TimeSpan.FromSeconds(.1));
return false;
});
}
[Test]
public void SafeWait_PollingInterval_GreaterThanTimeout()
{
wait.PollingInterval = TimeSpan.FromSeconds(1);
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
}
}
| using System;
using System.Threading;
using NUnit.Framework;
namespace Atata.WebDriverExtras.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class SafeWaitTests
{
private SafeWait<object> wait;
[SetUp]
public void SetUp()
{
wait = new SafeWait<object>(new object())
{
Timeout = TimeSpan.FromSeconds(.3),
PollingInterval = TimeSpan.FromSeconds(.05)
};
}
[Test]
public void SafeWait_Success_Immediate()
{
using (StopwatchAsserter.Within(0, .01))
wait.Until(_ =>
{
return true;
});
}
[Test]
public void SafeWait_Timeout()
{
using (StopwatchAsserter.Within(.3, .01))
wait.Until(_ =>
{
return false;
});
}
[Test]
public void SafeWait_PollingInterval()
{
using (StopwatchAsserter.Within(.3, .2))
wait.Until(_ =>
{
Thread.Sleep(TimeSpan.FromSeconds(.1));
return false;
});
}
[Test]
public void SafeWait_PollingInterval_GreaterThanTimeout()
{
wait.PollingInterval = TimeSpan.FromSeconds(1);
using (StopwatchAsserter.Within(.3, .01))
wait.Until(_ =>
{
return false;
});
}
}
}
| apache-2.0 | C# |
caf0e3899910bf058e441b3dfdb8071f0f005033 | remove unused code | csMACnz/SeaOrDew | src/csMACnz.SeaOrDew/HandlerNotFoundException.cs | src/csMACnz.SeaOrDew/HandlerNotFoundException.cs | using System;
namespace csMACnz.SeaOrDew
{
public class HandlerNotFoundException : Exception
{
public HandlerNotFoundException(Type expectedType, string message)
: base(message)
{
ExpectedType = expectedType;
}
public Type ExpectedType { get; }
}
}
| using System;
namespace csMACnz.SeaOrDew
{
public class HandlerNotFoundException : Exception
{
public HandlerNotFoundException(Type expectedType, string message)
: base(message)
{
ExpectedType = expectedType;
}
public HandlerNotFoundException(Type expectedType, string message, Exception innerException)
: base(message, innerException)
{
ExpectedType = expectedType;
}
public Type ExpectedType { get; }
}
}
| mit | C# |
1ffc5fe9fa65bade16f592137b2b776fd0d9ccb6 | Fix Symbolic duplication bug (I think). It seems to be a bug in Boogie that IdentifierExprs can be cloned twice | symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix | symbooglix/symbooglix/Expr/NonSymbolicDuplicator.cs | symbooglix/symbooglix/Expr/NonSymbolicDuplicator.cs | using System;
using Microsoft.Boogie;
using System.Diagnostics;
namespace symbooglix
{
/// <summary>
/// This duplicates Expr accept the identifier expr attached to symbolics
/// </summary>
public class NonSymbolicDuplicator : Duplicator
{
public NonSymbolicDuplicator()
{
}
public override Expr VisitIdentifierExpr (IdentifierExpr node)
{
if (node.Decl is SymbolicVariable)
{
Debug.Assert(node == ( node.Decl as SymbolicVariable ).expr, "Mismatched Symbolic IdentifierExpr");
if (node != ( node.Decl as SymbolicVariable ).expr)
throw new Exception("FIXME");
return node;
}
else
return base.VisitIdentifierExpr (node);
}
// FIXME: I think this is a bug in boogie. IdentifierExpr get cloned twice!
// By also overriding this method we prevent IdentifierExpr belonging to symbolics getting cloned
public override Expr VisitExpr(Expr node)
{
if (node is IdentifierExpr && (node as IdentifierExpr).Decl is SymbolicVariable)
return (Expr) this.Visit(node); // Skip duplication
else
return base.VisitExpr(node); // Duplicate as normal
}
}
}
| using System;
using Microsoft.Boogie;
using System.Diagnostics;
namespace symbooglix
{
/// <summary>
/// This duplicates Expr accept the identifier expr attached to symbolics
/// </summary>
public class NonSymbolicDuplicator : Duplicator
{
public NonSymbolicDuplicator()
{
}
public override Expr VisitIdentifierExpr (IdentifierExpr node)
{
if (node.Decl is SymbolicVariable)
{
Debug.Assert(node == ( node.Decl as SymbolicVariable ).expr, "Mismatched Symbolic IdentifierExpr");
return node;
}
else
return base.VisitIdentifierExpr (node);
}
}
}
| bsd-2-clause | C# |
cab048b1ab518ef9ddfa968cfec760b211253771 | Update ExceptionlessTraceTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/ExceptionlessTraceTelemeter.cs | TIKSN.Core/Analytics/Telemetry/ExceptionlessTraceTelemeter.cs | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Exceptionless;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessTraceTelemeter : ExceptionlessTelemeterBase, ITraceTelemeter
{
public async Task TrackTrace(string message)
{
try
{
ExceptionlessClient.Default.CreateLog(message).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel)
{
try
{
ExceptionlessClient.Default.CreateLog(message).SetType(severityLevel.ToString()).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
| using Exceptionless;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessTraceTelemeter : ExceptionlessTelemeterBase, ITraceTelemeter
{
public async Task TrackTrace(string message)
{
try
{
ExceptionlessClient.Default.CreateLog(message).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel)
{
try
{
ExceptionlessClient.Default.CreateLog(message).SetType(severityLevel.ToString()).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
} | mit | C# |
28ef4229462ef09bb1eb4abe967e569e91c5c362 | fix build error | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Tests/UnitTests/BitcoinCore/NodeBuildingTests.cs | WalletWasabi.Tests/UnitTests/BitcoinCore/NodeBuildingTests.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore;
using WalletWasabi.Tests.Helpers;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BitcoinCore
{
public class NodeBuildingTests
{
[Fact]
public async Task CanBuildCoreNodeAsync()
{
CoreNode coreNode = null;
try
{
coreNode = await TestNodeBuilder.CreateAsync();
}
finally
{
await coreNode.TryStopAsync();
}
}
[Fact]
public async Task NodesDifferAsync()
{
var coreNodes = await Task.WhenAll(TestNodeBuilder.CreateAsync(additionalFolder: "0"), TestNodeBuilder.CreateAsync(additionalFolder: "1"));
CoreNode node1 = coreNodes[0];
CoreNode node2 = coreNodes[1];
try
{
Assert.NotEqual(node1.DataDir, node2.DataDir);
Assert.NotEqual(node1.P2pEndPoint, node2.P2pEndPoint);
Assert.NotEqual(node1.RpcEndPoint, node2.RpcEndPoint);
}
finally
{
await Task.WhenAll(node1.TryStopAsync(), node2.TryStopAsync());
}
}
[Fact]
public async Task RpcWorksAsync()
{
var coreNode = await TestNodeBuilder.CreateAsync();
try
{
var blockCount = await coreNode.RpcClient.GetBlockCountAsync();
Assert.Equal(0, blockCount);
}
finally
{
await coreNode.TryStopAsync();
}
}
[Fact]
public async Task P2pWorksAsync()
{
var coreNode = await TestNodeBuilder.CreateAsync();
using var node = await coreNode.CreateP2pNodeAsync();
try
{
var blocks = node.GetBlocks(new[] { Network.RegTest.GenesisHash });
var genesis = Assert.Single(blocks);
Assert.Equal(genesis.GetHash(), Network.RegTest.GenesisHash);
}
finally
{
node.Disconnect();
await coreNode.TryStopAsync();
}
}
[Fact]
public async Task GetVersionTestsAsync()
{
using var cts = new CancellationTokenSource(7000);
Version version = await CoreNode.GetVersionAsync(cts.Token);
Assert.Equal(WalletWasabi.Helpers.Constants.BitcoinCoreVersion, version);
}
}
}
| using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore;
using WalletWasabi.Tests.Helpers;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BitcoinCore
{
public class NodeBuildingTests
{
[Fact]
public async Task CanBuildCoreNodeAsync()
{
var coreNode = await TestNodeBuilder.CreateAsync();
try
{
Assert.False(coreNode.Process.HasExited);
}
finally
{
await coreNode.TryStopAsync();
}
}
[Fact]
public async Task NodesDifferAsync()
{
var coreNodes = await Task.WhenAll(TestNodeBuilder.CreateAsync(additionalFolder: "0"), TestNodeBuilder.CreateAsync(additionalFolder: "1"));
CoreNode node1 = coreNodes[0];
CoreNode node2 = coreNodes[1];
try
{
Assert.NotEqual(node1.DataDir, node2.DataDir);
Assert.NotEqual(node1.Process.Id, node2.Process.Id);
Assert.NotEqual(node1.P2pEndPoint, node2.P2pEndPoint);
Assert.NotEqual(node1.RpcEndPoint, node2.RpcEndPoint);
}
finally
{
await Task.WhenAll(node1.TryStopAsync(), node2.TryStopAsync());
}
}
[Fact]
public async Task RpcWorksAsync()
{
var coreNode = await TestNodeBuilder.CreateAsync();
try
{
var blockCount = await coreNode.RpcClient.GetBlockCountAsync();
Assert.Equal(0, blockCount);
}
finally
{
await coreNode.TryStopAsync();
}
}
[Fact]
public async Task P2pWorksAsync()
{
var coreNode = await TestNodeBuilder.CreateAsync();
using var node = await coreNode.CreateP2pNodeAsync();
try
{
var blocks = node.GetBlocks(new[] { Network.RegTest.GenesisHash });
var genesis = Assert.Single(blocks);
Assert.Equal(genesis.GetHash(), Network.RegTest.GenesisHash);
}
finally
{
node.Disconnect();
await coreNode.TryStopAsync();
}
}
[Fact]
public async Task GetVersionTestsAsync()
{
using var cts = new CancellationTokenSource(7000);
Version version = await CoreNode.GetVersionAsync(cts.Token);
Assert.Equal(WalletWasabi.Helpers.Constants.BitcoinCoreVersion, version);
}
}
}
| mit | C# |
2da9b3575efb8ca19054d38272a6af6d12737981 | Replace assembly file version by informational version | Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize | RestImageResize.EpiServer/Properties/AssemblyInfo.cs | RestImageResize.EpiServer/Properties/AssemblyInfo.cs | using System.Reflection;
// General info about the product
[assembly: AssemblyTitle("RestImageResize.EPiServer")]
[assembly: AssemblyProduct("RestImageResize")]
[assembly: AssemblyDescription("Includes required dependences and source code for easily start to use RestImageResize package in EPiServer CMS site.")]
[assembly: AssemblyCompany("Roman Mironets, Creuna Kharkiv office")]
[assembly: AssemblyCopyright("Copyright © Roman Mironets 2015")]
// Product version
[assembly: AssemblyVersion("1.1")]
[assembly: AssemblyInformationalVersion("1.1")] | using System.Reflection;
// General info about the product
[assembly: AssemblyTitle("RestImageResize.EPiServer")]
[assembly: AssemblyProduct("RestImageResize")]
[assembly: AssemblyDescription("Includes required dependences and source code for easily start to use RestImageResize package in EPiServer CMS site.")]
[assembly: AssemblyCompany("Roman Mironets, Creuna Kharkiv office")]
[assembly: AssemblyCopyright("Copyright © Roman Mironets 2015")]
// Product version
[assembly: AssemblyVersion("1.1")]
[assembly: AssemblyFileVersion("1.1")] | mit | C# |
f5b2fa21187acc5f6efa79bd2ef949d40c65b920 | Add unit test | fredatgithub/UsefulFunctions | UnitTestUsefullFunctions/UnitTestStringExtensions.cs | UnitTestUsefullFunctions/UnitTestStringExtensions.cs | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using StringFunc = FonctionsUtiles.Fred.Csharp.FunctionsString;
using dllFuncs = FonctionsUtiles.Fred.Csharp;
namespace UnitTestUsefullFunctions
{
[TestClass]
public class UnitTestStringExtensions
{
#region ToCamelCase
[TestMethod]
public void TestMethod_ToCamelCase()
{
const string source = "a long long time ago in a galaxy far far away";
const string expected = "A long long time ago in a galaxy far far away";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
[TestMethod]
public void TestMethod_ToCamelCase_Empty_string()
{
const string source = "";
const string expected = "";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
[TestMethod]
public void TestMethod_ToCamelCase_underscore()
{
const string source = "a_long_long_time_ago_in_a_galaxy_far_far_away";
const string expected = "ALongLongTimeAgoInAGalaxyFarFarAway";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
[TestMethod]
public void TestMethod_ToCamelCase_one_underscaore()
{
const string source = "a long long time ago_in a galaxy far far away";
const string expected = "A long long time agoIn a galaxy far far away";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
#endregion ToCamelCase
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using StringFunc = FonctionsUtiles.Fred.Csharp.FunctionsString;
using dllFuncs = FonctionsUtiles.Fred.Csharp;
namespace UnitTestUsefullFunctions
{
[TestClass]
public class UnitTestStringExtensions
{
#region ToCamelCase
[TestMethod]
public void TestMethod_ToCamelCase()
{
const string source = "a long long time ago in a galaxy far far away";
const string expected = "A long long time ago in a galaxy far far away";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
[TestMethod]
public void TestMethod_ToCamelCase_Empty_string()
{
const string source = "";
const string expected = "";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
[TestMethod]
public void TestMethod_ToCamelCase_underscore()
{
const string source = "a_long_long_time_ago_in_a_galaxy_far_far_away";
const string expected = "ALongLongTimeAgoInAGalaxyFarFarAway";
string result = dllFuncs.StringExtensions.ToCamelCase(source);
Assert.AreEqual(result, expected);
}
#endregion ToCamelCase
}
} | mit | C# |
1baec2802a6ee205f4e4c1593abbcf00404eff34 | Update EditRangesWorksheet.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Worksheets/Security/EditRangesWorksheet.cs | Examples/CSharp/Worksheets/Security/EditRangesWorksheet.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security
{
public class EditRangesWorksheet
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook
Workbook book = new Workbook();
//Get the first (default) worksheet
Worksheet sheet = book.Worksheets[0];
//Get the Allow Edit Ranges
ProtectedRangeCollection allowRanges = sheet.AllowEditRanges;
//Define ProtectedRange
ProtectedRange proteced_range;
//Create the range
int idx = allowRanges.Add("r2", 1, 1, 3, 3);
proteced_range = allowRanges[idx];
//Specify the passoword
proteced_range.Password = "123";
//Protect the sheet
sheet.Protect(ProtectionType.All);
//Save the Excel file
book.Save(dataDir + "protectedrange.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security
{
public class EditRangesWorksheet
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook
Workbook book = new Workbook();
//Get the first (default) worksheet
Worksheet sheet = book.Worksheets[0];
//Get the Allow Edit Ranges
ProtectedRangeCollection allowRanges = sheet.AllowEditRanges;
//Define ProtectedRange
ProtectedRange proteced_range;
//Create the range
int idx = allowRanges.Add("r2", 1, 1, 3, 3);
proteced_range = allowRanges[idx];
//Specify the passoword
proteced_range.Password = "123";
//Protect the sheet
sheet.Protect(ProtectionType.All);
//Save the Excel file
book.Save(dataDir + "protectedrange.out.xls");
}
}
} | mit | C# |
e4ff024cf5ba71b1e0ec66ba8aada005318a00ff | Build filters only for P2WPKH scripts | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | MagicalCryptoWallet/ClientSideFilter/BlockFilterBuilder.cs | MagicalCryptoWallet/ClientSideFilter/BlockFilterBuilder.cs | using System.Collections.Generic;
using NBitcoin;
namespace MagicalCryptoWallet.Backend
{
public class BlockFilterBuilder
{
private const int P = 20;
private static readonly PayToWitPubKeyHashTemplate P2wpkh = PayToWitPubKeyHashTemplate.Instance;
public GolombRiceFilter Build(Block block)
{
var key = block.GetHash().ToBytes();
var buffer = new List<byte[]>();
buffer.Add(key);
foreach (var tx in block.Transactions)
{
foreach (var txOutput in tx.Outputs)
{
var isValidPayToWitness = P2wpkh.CheckScriptPubKey(txOutput.ScriptPubKey);
if (isValidPayToWitness)
{
var witKeyId = P2wpkh.ExtractScriptPubKeyParameters(txOutput.ScriptPubKey);
buffer.Add(witKeyId.ToBytes());
}
}
}
return GolombRiceFilter.Build(key, P, buffer);
}
}
}
| using System.Collections.Generic;
using NBitcoin;
namespace MagicalCryptoWallet.Backend
{
public class BlockFilterBuilder
{
private const int P = 20;
public GolombRiceFilter Build(Block block)
{
var key = block.GetHash().ToBytes();
var buffer = new List<byte[]>();
buffer.Add(key);
foreach (var tx in block.Transactions)
{
foreach (var txOutput in tx.Outputs)
{
var witDestination = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters(txOutput.ScriptPubKey);
var isValidPayToWitness = witDestination != null;
if (isValidPayToWitness)
{
var scriptPubKeyBytes = txOutput.ScriptPubKey.ToBytes();
buffer.Add(scriptPubKeyBytes);
}
}
}
return GolombRiceFilter.Build(key, P, buffer);
}
}
}
| mit | C# |
a1874c3f6a1c60a372b9f7e2041ba07e47dae5d4 | Update ServiceProviderFixture.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/ServiceProviderFixture.cs | TIKSN.Framework.IntegrationTests/ServiceProviderFixture.cs | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using TIKSN.Data.Mongo;
using TIKSN.DependencyInjection;
using TIKSN.Framework.IntegrationTests.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests
{
public class ServiceProviderFixture : IDisposable
{
private readonly IHost host;
public ServiceProviderFixture()
{
host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddFrameworkPlatform();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<CoreModule>();
builder.RegisterModule<PlatformModule>();
builder.RegisterType<TestMongoRepository>().As<ITestMongoRepository>().InstancePerLifetimeScope();
builder.RegisterType<TestMongoDatabaseProviderBase>().As<IMongoDatabaseProvider>().SingleInstance();
builder.RegisterType<TestMongoClientProvider>().As<IMongoClientProvider>().SingleInstance();
})
.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(GetInMemoryConfiguration()); })
.Build();
static Dictionary<string, string> GetInMemoryConfiguration()
{
return new()
{
{"ConnectionStrings:Mongo", "mongodb://localhost:27017/TIKSN_Framework_IntegrationTests?w=majority"}
};
}
}
public IServiceProvider Services => host.Services;
public void Dispose()
{
host?.Dispose();
}
}
} | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using TIKSN.Data.Mongo;
using TIKSN.Framework.IntegrationTests.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests
{
public class ServiceProviderFixture : IDisposable
{
private readonly IHost host;
public ServiceProviderFixture()
{
host = Host.CreateDefaultBuilder()
.ConfigureServices(services => { })
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterType<TestMongoRepository>().As<ITestMongoRepository>().InstancePerLifetimeScope();
builder.RegisterType<TestMongoDatabaseProvider>().As<IMongoDatabaseProvider>().SingleInstance();
})
.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(GetInMemoryConfiguration()); })
.Build();
static Dictionary<string, string> GetInMemoryConfiguration()
{
return new()
{
{"ConnectionStrings:Mongo", "mongodb://root:0b6273775d@localhost:27017/TIKSN_Framework_IntegrationTests?authSource=admin"}
};
}
}
public IServiceProvider Services => host.Services;
public void Dispose()
{
host?.Dispose();
}
}
} | mit | C# |
eea1d4451ccbfca879370b07b1f845a0044658e2 | Fix broken auth when POSTing/PUTing data | Seronam/crunchdotnet | src/Crunch.DotNet/Authorization/OAuthTokensExtensions.cs | src/Crunch.DotNet/Authorization/OAuthTokensExtensions.cs | using OAuth;
namespace Crunch.DotNet.Authorization
{
public static class OAuthTokensExtensions
{
public static string GetAuthorisationHeader(this OAuthTokens tokens, string url, string restMethod, string realm = null)
{
var oauthClient = new OAuthRequest
{
Method = restMethod,
Type = OAuthRequestType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = tokens.ConsumerKey,
ConsumerSecret = tokens.ConsumerSecret,
Token = tokens.Token,
TokenSecret = tokens.TokenSecret,
RequestUrl = url,
Realm = realm
};
return oauthClient.GetAuthorizationHeader();
}
}
} | using OAuth;
namespace Crunch.DotNet.Authorization
{
public static class OAuthTokensExtensions
{
public static string GetAuthorisationHeader(this OAuthTokens tokens, string url, string restMethod, string realm = null)
{
var oauthClient = OAuthRequest.ForProtectedResource(restMethod, tokens.ConsumerKey, tokens.ConsumerSecret, tokens.Token, tokens.TokenSecret);
oauthClient.RequestUrl = url;
oauthClient.Realm = realm;
return oauthClient.GetAuthorizationHeader();
}
}
} | mit | C# |
92a3baed4c0f19da4218407a2fddcb3fc235e329 | Reformat for long lines | brentstineman/nether,vflorusso/nether,oliviak/nether,ankodu/nether,ankodu/nether,stuartleeks/nether,brentstineman/nether,stuartleeks/nether,ankodu/nether,stuartleeks/nether,ankodu/nether,brentstineman/nether,navalev/nether,navalev/nether,navalev/nether,vflorusso/nether,vflorusso/nether,brentstineman/nether,navalev/nether,krist00fer/nether,MicrosoftDX/nether,stuartleeks/nether,vflorusso/nether,vflorusso/nether,stuartleeks/nether,brentstineman/nether | src/Nether.Data.MongoDB/PlayerManagement/MongoDbGroup.cs | src/Nether.Data.MongoDB/PlayerManagement/MongoDbGroup.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using Nether.Data.PlayerManagement;
namespace Nether.Data.MongoDB.PlayerManagement
{
public class MongoDBGroup
{
// Implicit operator allows Group objects to be used as MongoDBGroup objects
public static implicit operator MongoDBGroup(Group value)
{
return new MongoDBGroup
{
Name = value.Name,
CustomType = value.CustomType,
Description = value.Description,
Image = value.Image,
Players = value.Players
};
}
[BsonId]
public ObjectId TestId { get; set; }
public string Name { get; set; }
public string CustomType { get; set; }
public string Description { get; set; }
public byte[] Image { get; set; }
public List<Player> Players { get; set; }
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using Nether.Data.PlayerManagement;
namespace Nether.Data.MongoDB.PlayerManagement
{
public class MongoDBGroup
{
// Implicit operator allows Group objects to be used as MongoDBGroup objects
public static implicit operator MongoDBGroup(Group value)
{
return new MongoDBGroup { Name = value.Name, CustomType = value.CustomType, Description = value.Description, Image = value.Image, Players = value.Players };
}
[BsonId]
public ObjectId TestId { get; set; }
public string Name { get; set; }
public string CustomType { get; set; }
public string Description { get; set; }
public byte[] Image { get; set; }
public List<Player> Players { get; set; }
}
}
| mit | C# |
6df0069d4cd560ff6c406701f63a03c21d352700 | Revert "add default no-param constructor for ShipStationItemWeight" | agileharbor/shipStationAccess | src/ShipStationAccess/V2/Models/ShipStationItemWeight.cs | src/ShipStationAccess/V2/Models/ShipStationItemWeight.cs | using System.Runtime.Serialization;
namespace ShipStationAccess.V2.Models
{
[ DataContract ]
public sealed class ShipStationItemWeight
{
[ DataMember( Name = "value" ) ]
public decimal Value{ get; set; }
[ DataMember( Name = "units" ) ]
public string Units{ get; set; }
public ShipStationItemWeight( decimal value, string units )
{
this.Value = value;
this.Units = units;
}
}
} | using System.Runtime.Serialization;
namespace ShipStationAccess.V2.Models
{
[ DataContract ]
public sealed class ShipStationItemWeight
{
[ DataMember( Name = "value" ) ]
public decimal Value{ get; set; }
[ DataMember( Name = "units" ) ]
public string Units{ get; set; }
public ShipStationItemWeight()
{
}
public ShipStationItemWeight( decimal value, string units )
{
this.Value = value;
this.Units = units;
}
}
} | bsd-3-clause | C# |
4966b6cc3d85117ab7fb0cdcbf1134be552f9a1d | Update WebApplicationFactoryClientOptions.cs (#40963) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Mvc/Mvc.Testing/src/WebApplicationFactoryClientOptions.cs | src/Mvc/Mvc.Testing/src/WebApplicationFactoryClientOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc.Testing.Handlers;
namespace Microsoft.AspNetCore.Mvc.Testing;
/// <summary>
/// The default options to use to when creating
/// <see cref="HttpClient"/> instances by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>.
/// </summary>
public class WebApplicationFactoryClientOptions
{
/// <summary>
/// Initializes a new instance of <see cref="WebApplicationFactoryClientOptions"/>.
/// </summary>
public WebApplicationFactoryClientOptions()
{
}
// Copy constructor
internal WebApplicationFactoryClientOptions(WebApplicationFactoryClientOptions clientOptions)
{
BaseAddress = clientOptions.BaseAddress;
AllowAutoRedirect = clientOptions.AllowAutoRedirect;
MaxAutomaticRedirections = clientOptions.MaxAutomaticRedirections;
HandleCookies = clientOptions.HandleCookies;
}
/// <summary>
/// Gets or sets the base address of <see cref="HttpClient"/> instances created by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>.
/// The default is <c>http://localhost</c>.
/// </summary>
public Uri BaseAddress { get; set; } = new Uri("http://localhost");
/// <summary>
/// Gets or sets whether or not <see cref="HttpClient"/> instances created by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>
/// should automatically follow redirect responses.
/// The default is <c>true</c>.
/// </summary>
public bool AllowAutoRedirect { get; set; } = true;
/// <summary>
/// Gets or sets the maximum number of redirect responses that <see cref="HttpClient"/> instances
/// created by calling <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>
/// should follow.
/// The default is <c>7</c>.
/// </summary>
public int MaxAutomaticRedirections { get; set; } = RedirectHandler.DefaultMaxRedirects;
/// <summary>
/// Gets or sets whether <see cref="HttpClient"/> instances created by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>
/// should handle cookies.
/// The default is <c>true</c>.
/// </summary>
public bool HandleCookies { get; set; } = true;
internal DelegatingHandler[] CreateHandlers()
{
return CreateHandlersCore().ToArray();
IEnumerable<DelegatingHandler> CreateHandlersCore()
{
if (AllowAutoRedirect)
{
yield return new RedirectHandler(MaxAutomaticRedirections);
}
if (HandleCookies)
{
yield return new CookieContainerHandler();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc.Testing.Handlers;
namespace Microsoft.AspNetCore.Mvc.Testing;
/// <summary>
/// The default options to use to when creating
/// <see cref="HttpClient"/> instances by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>.
/// </summary>
public class WebApplicationFactoryClientOptions
{
/// <summary>
/// Initializes a new instance of <see cref="WebApplicationFactoryClientOptions"/>.
/// </summary>
public WebApplicationFactoryClientOptions()
{
}
// Copy constructor
internal WebApplicationFactoryClientOptions(WebApplicationFactoryClientOptions clientOptions)
{
BaseAddress = clientOptions.BaseAddress;
AllowAutoRedirect = clientOptions.AllowAutoRedirect;
MaxAutomaticRedirections = clientOptions.MaxAutomaticRedirections;
HandleCookies = clientOptions.HandleCookies;
}
/// <summary>
/// Gets or sets the base address of <see cref="HttpClient"/> instances created by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>.
/// The default is <c>http://localhost</c>.
/// </summary>
public Uri BaseAddress { get; set; } = new Uri("http://localhost");
/// <summary>
/// Gets or sets whether or not <see cref="HttpClient"/> instances created by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>
/// should automatically follow redirect responses.
/// The default is <c>true</c>.
/// /// </summary>
public bool AllowAutoRedirect { get; set; } = true;
/// <summary>
/// Gets or sets the maximum number of redirect responses that <see cref="HttpClient"/> instances
/// created by calling <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>
/// should follow.
/// The default is <c>7</c>.
/// </summary>
public int MaxAutomaticRedirections { get; set; } = RedirectHandler.DefaultMaxRedirects;
/// <summary>
/// Gets or sets whether <see cref="HttpClient"/> instances created by calling
/// <see cref="WebApplicationFactory{TEntryPoint}.CreateClient(WebApplicationFactoryClientOptions)"/>
/// should handle cookies.
/// The default is <c>true</c>.
/// </summary>
public bool HandleCookies { get; set; } = true;
internal DelegatingHandler[] CreateHandlers()
{
return CreateHandlersCore().ToArray();
IEnumerable<DelegatingHandler> CreateHandlersCore()
{
if (AllowAutoRedirect)
{
yield return new RedirectHandler(MaxAutomaticRedirections);
}
if (HandleCookies)
{
yield return new CookieContainerHandler();
}
}
}
}
| apache-2.0 | C# |
19ab973bb99bdcfc0cb0ff25bc64fcf0875d417d | Add second layer to test scene | peppy/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu | osu.Game.Tests/Visual/UserInterface/TestSceneHueAnimation.cs | osu.Game.Tests/Visual/UserInterface/TestSceneHueAnimation.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneHueAnimation : OsuTestScene
{
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
HueAnimation anim2;
Add(anim2 = new HueAnimation
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
Texture = textures.Get("Intro/Triangles/logo-highlight"),
Colour = Colour4.White,
});
HueAnimation anim;
Add(anim = new HueAnimation
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
Texture = textures.Get("Intro/Triangles/logo-background"),
Colour = OsuColour.Gray(0.6f),
});
AddSliderStep("Progress", 0f, 1f, 0f, newValue =>
{
anim2.AnimationProgress = newValue;
anim.AnimationProgress = newValue;
});
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneHueAnimation : OsuTestScene
{
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
HueAnimation anim;
Add(anim = new HueAnimation
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
Texture = textures.Get("Intro/Triangles/logo-background"),
Colour = Colour4.White,
});
AddSliderStep("Progress", 0f, 1f, 0f, newValue => anim.AnimationProgress = newValue);
}
}
}
| mit | C# |
18bfcd7b222d9e13d9b6c07fdd20fed2aa30d8d0 | add hover colour to OsuMarkdownLinkText | peppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.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 Markdig.Syntax.Inlines;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownLinkText : MarkdownLinkText
{
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
private SpriteText spriteText;
public OsuMarkdownLinkText(string text, LinkInline linkInline)
: base(text, linkInline)
{
}
[BackgroundDependencyLoader]
private void load()
{
spriteText.Colour = colourProvider.Light2;
}
public override SpriteText CreateSpriteText()
{
return spriteText = base.CreateSpriteText();
}
protected override bool OnHover(HoverEvent e)
{
spriteText.Colour = colourProvider.Light1;
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
spriteText.Colour = colourProvider.Light2;
base.OnHoverLost(e);
}
}
}
| // 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 Markdig.Syntax.Inlines;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Sprites;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownLinkText : MarkdownLinkText
{
private SpriteText spriteText;
public OsuMarkdownLinkText(string text, LinkInline linkInline)
: base(text, linkInline)
{
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
spriteText.Colour = colourProvider.Light2;
}
public override SpriteText CreateSpriteText()
{
return spriteText = base.CreateSpriteText();
}
}
}
| mit | C# |
7192d1d1b67b0461ff91a4280a7a981786dc63ca | resolve CA1062 warning | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | server/src/FilterLists.Data/Seed/Extensions/SeedExtension.cs | server/src/FilterLists.Data/Seed/Extensions/SeedExtension.cs | using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Ardalis.GuardClauses;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace FilterLists.Data.Seed.Extensions
{
public static class SeedExtension
{
public static void HasDataJsonFile<TEntity>(this EntityTypeBuilder entityTypeBuilder)
{
Guard.Against.Null(entityTypeBuilder, nameof(entityTypeBuilder));
var path = Path.Combine("../../../data", $"{typeof(TEntity).Name}.json");
if (!File.Exists(path)) return;
var entitiesJson = File.ReadAllText(path);
var entities = JsonSerializer.Deserialize<IEnumerable<TEntity>>(entitiesJson, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
entityTypeBuilder.HasData((IEnumerable<object>)entities);
}
}
} | using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace FilterLists.Data.Seed.Extensions
{
public static class SeedExtension
{
public static void HasDataJsonFile<TEntity>(this EntityTypeBuilder entityTypeBuilder)
{
string path = Path.Combine("../../../data", $"{typeof(TEntity).Name}.json");
if (File.Exists(path))
{
var entitiesJson = File.ReadAllText(path);
var entities = JsonSerializer.Deserialize<IEnumerable<TEntity>>(entitiesJson, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
entityTypeBuilder.HasData((IEnumerable<object>)entities);
}
}
}
} | mit | C# |
3d1b3b4cc43a40e39a78b9418aa99b0e68e166e3 | Add AutomaticDownload option | Unity-Technologies/debugger-libs,Unity-Technologies/debugger-libs,mono/debugger-libs,mono/debugger-libs | Mono.Debugging/Mono.Debugging.Client/DebuggerSessionOptions.cs | Mono.Debugging/Mono.Debugging.Client/DebuggerSessionOptions.cs | //
// DebuggerSessionOptions.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Mono.Debugging.Client
{
[Serializable]
public enum AutomaticSourceDownload
{
Ask,
Always,
Never
}
[Serializable]
public class DebuggerSessionOptions
{
public EvaluationOptions EvaluationOptions { get; set; }
public bool StepOverPropertiesAndOperators { get; set; }
public bool ProjectAssembliesOnly { get; set; }
public AutomaticSourceDownload AutomaticSourceLinkDownload { get; set; }
}
}
| //
// DebuggerSessionOptions.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Mono.Debugging.Client
{
[Serializable]
public class DebuggerSessionOptions
{
public EvaluationOptions EvaluationOptions { get; set; }
public bool StepOverPropertiesAndOperators { get; set; }
public bool ProjectAssembliesOnly { get; set; }
}
}
| mit | C# |
ddc7fa6ac06cb7c3cbcd678801120c2ae28dd03d | update FadeVolume function | punker76/simple-music-player | SimpleMusicPlayer/SimpleMusicPlayer/Core/Player/ChannelInfo.cs | SimpleMusicPlayer/SimpleMusicPlayer/Core/Player/ChannelInfo.cs | using System;
using FMOD;
using SimpleMusicPlayer.Core.Interfaces;
using SimpleMusicPlayer.FMODStudio;
namespace SimpleMusicPlayer.Core.Player
{
internal class ChannelInfo
{
public FMOD.Channel Channel { get; set; }
public IMediaFile File { get; set; }
public bool FadeVolume(float startVol, float endVol, float startPoint, float fadeLength, float currentTime)
{
if ((fadeLength > 0f) && (currentTime >= startPoint) && (currentTime <= startPoint + fadeLength))
{
var calcVolume = Math.Abs(((endVol - startVol) / fadeLength) * (currentTime - startPoint));
if (startVol < endVol)
{
this.Volume = calcVolume + startVol;
}
else
{
this.Volume = startVol - calcVolume;
}
return true;
}
return false;
}
private float volume = -1f;
public float Volume
{
get { return this.volume; }
set
{
if (this.Channel == null || Equals(value, this.volume))
{
return;
}
this.volume = value;
this.Channel.setVolume(value).ERRCHECK();
}
}
public void CleanUp()
{
if (this.Channel != null)
{
this.Channel.setVolume(0f).ERRCHECK(RESULT.ERR_INVALID_HANDLE);
this.Channel.setCallback(null).ERRCHECK(RESULT.ERR_INVALID_HANDLE);
this.Channel = null;
}
this.File.State = PlayerState.Stop;
this.File = null;
}
}
} | using System;
using FMOD;
using SimpleMusicPlayer.Core.Interfaces;
using SimpleMusicPlayer.FMODStudio;
namespace SimpleMusicPlayer.Core.Player
{
internal class ChannelInfo
{
public FMOD.Channel Channel { get; set; }
public IMediaFile File { get; set; }
public bool FadeVolume(float startVol, float endVol, float startPoint, float fadeLength, float currentTime)
{
if ((currentTime >= startPoint) && (currentTime <= startPoint + fadeLength))
{
var chVolume = 1.0f;
if (startVol < endVol)
{
chVolume = ((endVol - startVol) / fadeLength) * (currentTime - startPoint) + startVol;
}
else
{
chVolume = Math.Abs(Math.Abs(((endVol - startVol) / fadeLength) * (currentTime - startPoint)) - 1.0f);
}
this.Volume = chVolume;
return true;
}
return false;
}
private float volume = -1f;
public float Volume
{
get { return this.volume; }
set
{
if (this.Channel == null || Equals(value, this.volume))
{
return;
}
this.volume = value;
this.Channel.setVolume(value).ERRCHECK();
}
}
public void CleanUp()
{
if (this.Channel != null)
{
this.Channel.setVolume(0f).ERRCHECK(RESULT.ERR_INVALID_HANDLE);
this.Channel.setCallback(null).ERRCHECK(RESULT.ERR_INVALID_HANDLE);
this.Channel = null;
}
this.File.State = PlayerState.Stop;
this.File = null;
}
}
} | mit | C# |
76387f350346b560243f6108718f9c19f9d09182 | support refresh tokens | mika-f/Sagitta | Source/PixivNet.Tests/Clients/Auth/AuthenticationClientTest.cs | Source/PixivNet.Tests/Clients/Auth/AuthenticationClientTest.cs | using System.Threading.Tasks;
using Xunit;
namespace Pixiv.Tests.Clients.Auth
{
public class AuthenticationClientTest : PixivTestAPiClient
{
[Fact]
public async Task Login_ShouldExtendsIsNullObject()
{
await ShouldExtendsIsNullObject(w => w.Authentication.LoginAsync("**", "**", "ad11f91d202e79b1e1bd1e63df42b85f"));
}
[Fact]
public void Login_ShouldHaveAttributes()
{
ShouldHaveAttributes(w => w.Authentication.LoginAsync("", "", ""));
}
[Fact]
public async Task Refresh_ShouldExtendsIsNullObject()
{
await ShouldExtendsIsNullObject(w => w.Authentication.RefreshAsync());
}
[Fact]
public void Refresh_ShouldHaveAttributes()
{
ShouldHaveAttributes(w => w.Authentication.RefreshAsync());
}
}
} | using System.Threading.Tasks;
using Xunit;
namespace Pixiv.Tests.Clients.Auth
{
public class AuthenticationClientTest : PixivTestAPiClient
{
[Fact]
public async Task Login_ShouldExtendsIsNullObject()
{
await ShouldExtendsIsNullObject(w => w.Authentication.LoginAsync("**", "**", "ad11f91d202e79b1e1bd1e63df42b85f"));
}
[Fact]
public void Login_ShouldHaveAttributes()
{
ShouldHaveAttributes(w => w.Authentication.LoginAsync("", "", ""));
}
}
} | mit | C# |
52c55af4149d9b781cd0793823e0f56fcc897dad | implement GET and POST in controller implement bad request for PUT and DELETE | MCeddy/IoT-core | IoT-Core/Controllers/ValuesController.cs | IoT-Core/Controllers/ValuesController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using IoT_Core.Models;
namespace IoT_Core.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
private SensorValueContext _dbContext;
public ValuesController(SensorValueContext dbContext)
{
this._dbContext = dbContext;
}
// GET api/values
[HttpGet]
public IActionResult Get()
{
var results = _dbContext.SensorValues
.OrderBy(sv => sv.Id)
.ToList();
return Ok(results);
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var sensorValues = _dbContext.SensorValues
.FirstOrDefault(value => value.Id == id);
if (sensorValues == null)
{
return NotFound();
}
return Ok(sensorValues);
}
// POST api/values
[HttpPost]
public async Task<IActionResult> Post([FromBody]SensorValues values)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_dbContext.SensorValues.Add(values);
await _dbContext.SaveChangesAsync();
return CreatedAtAction("Get", values.Id);
}
// PUT api/values/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]string value)
{
return Forbid();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
return Forbid();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace IoT_Core.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| mit | C# |
c5250527c7e29f639c68e4fa30b84eb743ef6ad3 | Implement implicit operators | sakapon/Samples-2017 | MathSample/DecimalConsole/RealDecimal.cs | MathSample/DecimalConsole/RealDecimal.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace DecimalConsole
{
public struct RealDecimal
{
public static RealDecimal Zero { get; } = default(RealDecimal);
public URealDecimal AbsoluteValue { get; }
public bool? IsPositive { get; }
public int? Degree => AbsoluteValue.Degree;
public bool IsZero => AbsoluteValue.IsZero;
public byte this[int index] => AbsoluteValue[index];
internal RealDecimal(URealDecimal absoluteValue, bool? isPositive)
{
if (absoluteValue.IsZero ^ !isPositive.HasValue) throw new ArgumentException("");
AbsoluteValue = absoluteValue;
IsPositive = isPositive;
}
public override string ToString() =>
$"{(IsPositive == false ? "-" : "")}{AbsoluteValue}";
static RealDecimal FromString(string value)
{
var hasMinus = value?.StartsWith("-") ?? throw new ArgumentNullException();
URealDecimal ud = value.TrimStart('-');
var isPositive = ud.IsZero ? default(bool?) : !hasMinus;
return new RealDecimal(ud, isPositive);
}
static RealDecimal FromInt32(int value) => value.ToString();
static RealDecimal FromDouble(double value) => value.ToString();
public static implicit operator RealDecimal(string value) => FromString(value);
public static implicit operator RealDecimal(int value) => FromInt32(value);
public static implicit operator RealDecimal(double value) => FromDouble(value);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace DecimalConsole
{
public struct RealDecimal
{
public static RealDecimal Zero { get; } = default(RealDecimal);
public URealDecimal AbsoluteValue { get; }
public bool? IsPositive { get; }
public int? Degree => AbsoluteValue.Degree;
public bool IsZero => AbsoluteValue.IsZero;
public byte this[int index] => AbsoluteValue[index];
internal RealDecimal(URealDecimal absoluteValue, bool? isPositive)
{
if (absoluteValue.IsZero ^ !isPositive.HasValue) throw new ArgumentException("");
AbsoluteValue = absoluteValue;
IsPositive = isPositive;
}
public override string ToString()
{
return base.ToString();
}
}
}
| mit | C# |
5f47351b6fcbead8b6ab9d1b26dda31d4ff61343 | Delete some unused code | wvdd007/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,jmarolf/roslyn,gafter/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,bartdesmet/roslyn,sharwell/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,heejaechang/roslyn,gafter/roslyn,brettfo/roslyn,gafter/roslyn,AmadeusW/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,dotnet/roslyn,dotnet/roslyn,jmarolf/roslyn,diryboy/roslyn,diryboy/roslyn,stephentoub/roslyn,physhi/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,brettfo/roslyn,tmat/roslyn,KevinRansom/roslyn,genlu/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,genlu/roslyn,stephentoub/roslyn,tmat/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,mavasani/roslyn,genlu/roslyn,brettfo/roslyn,aelij/roslyn,heejaechang/roslyn,jmarolf/roslyn,physhi/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,tmat/roslyn,eriawan/roslyn,bartdesmet/roslyn | src/Features/Core/Portable/RQName/Nodes/RQTypeOrNamespace.cs | src/Features/Core/Portable/RQName/Nodes/RQTypeOrNamespace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQTypeOrNamespace<ResolvedType> : RQNode<ResolvedType>
{
public readonly ReadOnlyCollection<string> NamespaceNames;
protected RQTypeOrNamespace(IList<string> namespaceNames)
=> NamespaceNames = new ReadOnlyCollection<string>(namespaceNames);
protected override void AppendChildren(List<SimpleTreeNode> childList)
=> childList.AddRange(NamespaceNames.Select(name => (SimpleTreeNode)new SimpleGroupNode(RQNameStrings.NsName, name)));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQTypeOrNamespace<ResolvedType> : RQNode<ResolvedType>
{
public readonly ReadOnlyCollection<string> NamespaceNames;
protected RQTypeOrNamespace(IList<string> namespaceNames)
=> NamespaceNames = new ReadOnlyCollection<string>(namespaceNames);
public static INamespaceSymbol NamespaceIdentifier
{
// TODO: C# Specific?
get { return null; /*new CSharpNamespaceIdentifier(NamespaceNames);*/ }
}
protected override void AppendChildren(List<SimpleTreeNode> childList)
=> childList.AddRange(NamespaceNames.Select(name => (SimpleTreeNode)new SimpleGroupNode(RQNameStrings.NsName, name)));
}
}
| mit | C# |
416c51491f726c39d0ac59aff7871f3d28fc43a9 | update Interceptor | caoxk/OrchardEF,nicholaspei/OrchardNoCMS,caoxk/OrchardEF,jango2015/OrchardNoCMS,caoxk/OrchardEF,luchaoshuai/OrchardNoCMS,caoxk/OrchardEF,vebin/OrchardNoCMS,MetSystem/OrchardNoCMS | src/Orchard.Web/Modules/Orchard.Car/AOP/SimpleInterceptor.cs | src/Orchard.Web/Modules/Orchard.Car/AOP/SimpleInterceptor.cs | using Castle.Core.Interceptor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Orchard.Car.AOP
{
public class SimpleInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "CreateCar")
{
invocation.Proceed();
invocation.ReturnValue = true;
}
else {
invocation.Proceed();
}
}
}
} | using Castle.Core.Interceptor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Orchard.Car.AOP
{
public class SimpleInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "CreateCar")
{
invocation.ReturnValue = true;
}
else {
invocation.Proceed();
}
}
}
} | bsd-3-clause | C# |
49436e0aaaff5dd045ca71fe37d944a5c7266329 | add equality check unit test | ceee/PocketSharp | PocketSharp.Tests/MiscTests.cs | PocketSharp.Tests/MiscTests.cs | using PocketSharp.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using System.Linq;
namespace PocketSharp.Tests
{
public class MiscTests : TestsBase
{
private int Incrementor = 0;
public MiscTests()
: base()
{
client.PreRequest = method => Incrementor++;
}
[Fact]
public async Task CheckPreRequestAction()
{
IEnumerable<PocketItem> items = await client.Get(count: 1);
PocketItem item = items.First();
await client.Favorite(item);
await client.Unfavorite(item);
Assert.True(Incrementor >= 3);
}
[Fact]
public void ItemEqualityChecks()
{
PocketItem item1 = new PocketItem() { ID = "12872" };
PocketItem item2 = new PocketItem() { ID = "12872" };
PocketItem item3 = new PocketItem() { ID = "12800" };
Assert.True(item1.Equals(item2));
Assert.False(item1.Equals(item3));
Assert.False(item1.Equals(null));
Assert.True(item1 == item2);
Assert.False(item1 == item3);
Assert.False(item1 == null);
Assert.False(item1 != item2);
Assert.True(item1 != item3);
Assert.True(item1 != null);
Assert.True(new List<PocketItem>() { item1 }.IndexOf(item2) > -1);
}
}
}
| using PocketSharp.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using System.Linq;
namespace PocketSharp.Tests
{
public class MiscTests : TestsBase
{
private int Incrementor = 0;
public MiscTests()
: base()
{
client.PreRequest = method => Incrementor++;
}
[Fact]
public async Task CheckPreRequestAction()
{
IEnumerable<PocketItem> items = await client.Get(count: 1);
PocketItem item = items.First();
await client.Favorite(item);
await client.Unfavorite(item);
Assert.True(Incrementor >= 3);
}
}
}
| mit | C# |
defbbe9663ea430c8a48faaade360504e05a5b3a | Allow Descriptons on classes, fix syntax | mirhagk/PowerCommandParser | PowerCommandParser/HelpText.cs | PowerCommandParser/HelpText.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace PowerCommandParser
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)]
public class DescriptionAttribute : Attribute
{
public string Text { get; set; }
public string Summary { get; set; }
public DescriptionAttribute() { }
public DescriptionAttribute(string summary)
{
Summary = summary;
}
public DescriptionAttribute(string summary, string text)
{
Summary = summary;
Text = text;
}
}
public class HelpText<T>
{
public string Name { get; set; }
private DescriptionAttribute Description => typeof(T).GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
public string ProgramName => typeof(T).Assembly.GetName().Name;
public string Synopsis => Description?.Summary ?? ProgramName;
public string LongDescription => Description?.Text;
private IEnumerable<PropertyInfo> OrderedProperties => typeof(T).GetProperties().OrderBy(p => p.GetCustomAttributes().Min(a => (a as PositionAttribute)?.Position) ?? int.MaxValue);
public string GetSyntax()
{
var result = Name;
foreach (var parameter in OrderedProperties)
{
var positioned = parameter.GetCustomAttribute(typeof(PositionAttribute)) != null;
var required = parameter.GetCustomAttribute(typeof(RequiredAttribute)) != null;
var parameterType = parameter.PropertyType.ToString();
var parameterText = parameter.Name;
if (positioned)
parameterText = $"[{parameterText}]";
parameterText += $" {parameterType}";
if (!required)
parameterText = $"[{parameterText}]";
result += " " + parameterText;
}
return result;
}
public string GetParameterHelp()
{
return string.Join("\n\n", OrderedProperties
.Select(p => new { p, d = p.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute })
.Where(x => x.d != null)
.Select(x => $"{x.p.Name}:\n {x.d.Summary}"));
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace PowerCommandParser
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DescriptionAttribute : Attribute
{
public string Text { get; set; }
public string Summary { get; set; }
public DescriptionAttribute(){}
public DescriptionAttribute(string summary)
{
Summary = summary;
}
public DescriptionAttribute(string summary, string text)
{
Summary = summary;
Text = text;
}
}
public class HelpText<T>
{
public string Name { get; set; }
private DescriptionAttribute Description => typeof(T).GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
public string ProgramName => typeof(T).Assembly.GetName().Name;
public string Synopsis => Description?.Summary ?? ProgramName;
public string LongDescription => Description?.Text;
private IEnumerable<PropertyInfo> OrderedProperties => typeof(T).GetProperties().OrderBy(p=>p.GetCustomAttributes().Min(a=>(a as PositionAttribute)?.Position) ?? int.MaxValue);
public string GetSyntax()
{
var result = Name;
foreach (var parameter in OrderedProperties)
{
var positioned = parameter.GetCustomAttribute(typeof(PositionAttribute)) != null;
var required = parameter.GetCustomAttribute(typeof(RequiredAttribute)) != null;
var parameterType = parameter.PropertyType.ToString();
var parameterText = parameter.Name;
if (positioned)
parameterText = $"[{parameterText}]";
parameterText+=$" [{parameterType}]";
if (!required)
parameterText = $"[{parameterText}]";
result += " " + parameterText;
}
return result;
}
public string GetParameterHelp()
{
return string.Join("\n\n", OrderedProperties
.Select(p=>new {p,d = p.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute})
.Where(x=>x.d!=null)
.Select(x=>$"{x.p.Name}:\n {x.d.Summary}"));
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.