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 |
|---|---|---|---|---|---|---|---|---|
6d3e4aaa78f3ddbd4c71ce69d3c25e68d5822b02 | Make ActionDelete.ActionAlias public again | abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS | src/Umbraco.Core/Actions/ActionDelete.cs | src/Umbraco.Core/Actions/ActionDelete.cs | // Copyright (c) Umbraco.
// See LICENSE for more details.
namespace Umbraco.Cms.Core.Actions
{
/// <summary>
/// This action is invoked when a document, media, member is deleted
/// </summary>
public class ActionDelete : IAction
{
/// <summary>
/// The unique action alias
/// </summary>
public const string ActionAlias = "delete";
/// <summary>
/// The unique action letter
/// </summary>
public const char ActionLetter = 'D';
/// <inheritdoc/>
public char Letter => ActionLetter;
/// <inheritdoc/>
public string Alias => ActionAlias;
/// <inheritdoc/>
public string Category => Constants.Conventions.PermissionCategories.ContentCategory;
/// <inheritdoc/>
public string Icon => "delete";
/// <inheritdoc/>
public bool ShowInNotifier => true;
/// <inheritdoc/>
public bool CanBePermissionAssigned => true;
}
}
| // Copyright (c) Umbraco.
// See LICENSE for more details.
namespace Umbraco.Cms.Core.Actions
{
/// <summary>
/// This action is invoked when a document, media, member is deleted
/// </summary>
public class ActionDelete : IAction
{
/// <summary>
/// The unique action alias
/// </summary>
private const string ActionAlias = "delete";
/// <summary>
/// The unique action letter
/// </summary>
public const char ActionLetter = 'D';
/// <inheritdoc/>
public char Letter => ActionLetter;
/// <inheritdoc/>
public string Alias => ActionAlias;
/// <inheritdoc/>
public string Category => Constants.Conventions.PermissionCategories.ContentCategory;
/// <inheritdoc/>
public string Icon => "delete";
/// <inheritdoc/>
public bool ShowInNotifier => true;
/// <inheritdoc/>
public bool CanBePermissionAssigned => true;
}
}
| mit | C# |
1a34e8447159be99524f156d9167bd29e0fa83c7 | Update interface test | jonathanvdc/ecsc | tests/cs/interface/Interface.cs | tests/cs/interface/Interface.cs | using System;
interface IFlyable
{
void Fly();
string Name { get; }
}
class Bird : IFlyable
{
public Bird() { }
public string Name => "Bird";
public void Fly()
{
Console.WriteLine("Chirp");
}
}
class Plane : IFlyable
{
public Plane() { }
public string Name => "Plane";
public void Fly()
{
Console.WriteLine("Nnneeaoowww");
}
}
static class Program
{
public static IFlyable[] GetBirdInstancesAndPlaneInstancesMixed()
{
return new IFlyable[]
{
new Bird(),
new Plane()
};
}
public static void Main(string[] Args)
{
var items = GetBirdInstancesAndPlaneInstancesMixed();
for (int i = 0; i < items.Length; i++)
{
Console.Write(items[i].Name + ": ");
items[i].Fly();
}
}
}
| using System;
interface IFlyable
{
void Fly();
}
class Bird : IFlyable
{
public Bird() { }
public void Fly()
{
Console.WriteLine("Chirp");
}
}
class Plane : IFlyable
{
public Plane() { }
public void Fly()
{
Console.WriteLine("Nnneeaoowww");
}
}
static class Program
{
public static IFlyable[] GetBirdInstancesAndPlaneInstancesMixed()
{
return new IFlyable[]
{
new Bird(),
new Plane()
};
}
public static void Main(string[] Args)
{
var items = GetBirdInstancesAndPlaneInstancesMixed();
for (int i = 0; i < items.Length; i++)
{
items[i].Fly();
}
}
}
| mit | C# |
35f7c96437da5f0fdd577a26a1a2317683c6d7b4 | fix Auth | kiraacorsac/dotvvm,kiraacorsac/dotvvm,darilek/dotvvm,riganti/dotvvm,darilek/dotvvm,darilek/dotvvm,riganti/dotvvm,kiraacorsac/dotvvm,riganti/dotvvm,riganti/dotvvm | src/DotVVM.Samples.Tests/Complex/AuthTests.cs | src/DotVVM.Samples.Tests/Complex/AuthTests.cs | using Dotvvm.Samples.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Riganti.Utils.Testing.SeleniumCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotVVM.Samples.Tests.Complex
{
[TestClass]
public class AuthTests : SeleniumTestBase
{
[TestMethod]
public void Complex_Auth()
{
RunInAllBrowsers(browser =>
{
browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login);
browser.SendKeys("input[type=text]", "user");
browser.First("input[type=button]").Click();
browser.Wait();
browser.Refresh();
//browser.FindElements("a").ThrowIfDifferentCountThan(2);
browser.Wait();
browser.Last("a").Click();
browser.SendKeys("input[type=text]", "message");
browser.First("input[type=button]").Click();
browser.ElementAt("h1",1)
.CheckIfInnerText(
s =>
s.Contains("DotVVM Debugger: Error 401: Unauthorized")
);
browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login);
//browser.SendKeys("input[type=text]", "user");
browser.First("input#adminRole").Click();
browser.Wait();
browser.First("input[type=button]").Click();
browser.Wait();
browser.Last("a").Click();
browser.SendKeys("input[type=text]", "message");
browser.First("input[type=button]");
browser.Wait();
browser.First("span").CheckIfInnerText(s => s.Contains("user: message"));
});
}
}
}
| using Dotvvm.Samples.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Riganti.Utils.Testing.SeleniumCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotVVM.Samples.Tests.Complex
{
[TestClass]
public class AuthTests : SeleniumTestBase
{
[TestMethod]
public void Complex_Auth()
{
RunInAllBrowsers(browser =>
{
browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login);
browser.SendKeys("input[type=text]", "user");
browser.First("input[type=button]").Click();
browser.Wait();
browser.Refresh();
//browser.FindElements("a").ThrowIfDifferentCountThan(2);
browser.Wait();
browser.Last("a").Click();
browser.SendKeys("input[type=text]", "message");
browser.ElementAt("input[type=button]", 0).Click();
browser.ElementAt("h1",1)
.CheckIfInnerText(
s =>
s.Contains("DotVVM Debugger: Error 401: Unauthorized")
);
browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login);
//browser.SendKeys("input[type=text]", "user");
browser.First("input#adminRole").Click();
browser.Wait();
browser.First("input[type=button]").Click();
browser.Wait();
browser.Last("a").Click();
browser.SendKeys("input[type=text]", "message");
browser.ElementAt("input[type=button]", 0).Click();
browser.Wait();
browser.First("span").CheckIfInnerText(s => s.Contains("user: message"));
});
}
}
}
| apache-2.0 | C# |
bfc328c5ab94eda41bfb5b81e84c66ca975373c0 | change font weight for bold text | peppy/osu-new,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownTextFlowContainer.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownTextFlowContainer.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.Game.Graphics.Sprites;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownTextFlowContainer : MarkdownTextFlowContainer
{
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
protected override SpriteText CreateSpriteText() => new OsuSpriteText
{
Font = OsuFont.GetFont(size: 14),
};
protected override void AddLinkText(string text, LinkInline linkInline)
=> AddDrawable(new OsuMarkdownLinkText(text, linkInline));
// TODO : Add background (colour B6) and change font to monospace
protected override void AddCodeInLine(CodeInline codeInline)
=> AddText(codeInline.Content, t => { t.Colour = colourProvider.Light1; });
protected override SpriteText CreateEmphasisedSpriteText(bool bold, bool italic)
{
var spriteText = CreateSpriteText();
spriteText.Font = spriteText.Font.With(weight: bold ? FontWeight.Bold : FontWeight.Regular, italics: italic);
return spriteText;
}
}
}
| // 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.Graphics.Sprites;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownTextFlowContainer : MarkdownTextFlowContainer
{
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
protected override SpriteText CreateSpriteText() => new OsuSpriteText
{
Font = OsuFont.GetFont(size: 14),
};
protected override void AddLinkText(string text, LinkInline linkInline)
=> AddDrawable(new OsuMarkdownLinkText(text, linkInline));
// TODO : Add background (colour B6) and change font to monospace
protected override void AddCodeInLine(CodeInline codeInline)
=> AddText(codeInline.Content, t => { t.Colour = colourProvider.Light1; });
}
}
| mit | C# |
0202b5b969aa76263422e3976f31b30f5f3bd003 | バージョン番号更新。 | YKSoftware/YKToolkit.Controls | YKToolkit.Controls/Properties/AssemblyInfo.cs | YKToolkit.Controls/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyTitle("YKToolkit.Controls")]
#if NET4
[assembly: AssemblyDescription(".NET Framework 4.0 用 の WPF カスタムコントロールライブラリです。")]
#else
[assembly: AssemblyDescription("WPF カスタムコントロールライブラリです。")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("YKSoftware")]
[assembly: AssemblyProduct("YKToolkit.Controls")]
[assembly: AssemblyCopyright("Copyright © 2015 YKSoftware")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("2.3.8.1")]
| using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyTitle("YKToolkit.Controls")]
#if NET4
[assembly: AssemblyDescription(".NET Framework 4.0 用 の WPF カスタムコントロールライブラリです。")]
#else
[assembly: AssemblyDescription("WPF カスタムコントロールライブラリです。")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("YKSoftware")]
[assembly: AssemblyProduct("YKToolkit.Controls")]
[assembly: AssemblyCopyright("Copyright © 2015 YKSoftware")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("2.3.8.0")]
| mit | C# |
8b6d2525e437c8e5e477dbb44d3bb74a829d9805 | Implement ViewModelTest | mweibel/mste-testat | AutoReservation.Ui.Testing/ViewModelTest.cs | AutoReservation.Ui.Testing/ViewModelTest.cs | using System.Threading;
using System.Windows.Input;
using AutoReservation.Testing;
using AutoReservation.Ui.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AutoReservation.Ui.Testing
{
[TestClass]
public class ViewModelTest
{
[TestInitialize]
public void InitializeTestData()
{
TestEnvironmentHelper.InitializeTestData();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}
[TestMethod]
public void AutosLoadTest()
{
var autoViewModel = new AutoViewModel();
var cmd = autoViewModel.LoadCommand;
Assert.IsTrue(cmd.CanExecute(this));
cmd.Execute(this);
Assert.IsNotNull(autoViewModel.Autos);
}
[TestMethod]
public void KundenLoadTest()
{
var kundeViewModel = new KundeViewModel();
var cmd = kundeViewModel.LoadCommand;
Assert.IsTrue(cmd.CanExecute(this));
cmd.Execute(this);
Assert.IsNotNull(kundeViewModel.Kunden);
}
[TestMethod]
public void ReservationenLoadTest()
{
var reservationViewModel = new ReservationViewModel();
var cmd = reservationViewModel.LoadCommand;
Assert.IsTrue(cmd.CanExecute(this));
cmd.Execute(this);
Assert.IsNotNull(reservationViewModel.Reservationen);
}
}
} | using System.Windows.Input;
using AutoReservation.Testing;
using AutoReservation.Ui.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AutoReservation.Ui.Testing
{
[TestClass]
public class ViewModelTest
{
[TestInitialize]
public void InitializeTestData()
{
TestEnvironmentHelper.InitializeTestData();
}
[TestMethod]
public void AutosLoadTest()
{
Assert.Inconclusive("Test wurde noch nicht implementiert!");
}
[TestMethod]
public void KundenLoadTest()
{
Assert.Inconclusive("Test wurde noch nicht implementiert!");
}
[TestMethod]
public void ReservationenLoadTest()
{
Assert.Inconclusive("Test wurde noch nicht implementiert!");
}
}
} | mit | C# |
23d8b92f9403adb7591e464d804bd79e31af09f2 | Implement updates to containers for ContainerSlot. | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content | Content.Server/GameObjects/ContainerSlot.cs | Content.Server/GameObjects/ContainerSlot.cs | using Robust.Server.GameObjects.Components.Container;
using Robust.Server.Interfaces.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using System.Collections.Generic;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects
{
public class ContainerSlot : BaseContainer
{
[ViewVariables]
public IEntity ContainedEntity { get; private set; } = null;
/// <inheritdoc />
public override IReadOnlyCollection<IEntity> ContainedEntities => new List<IEntity> { ContainedEntity }.AsReadOnly();
public ContainerSlot(string id, IContainerManager manager) : base(id, manager)
{
}
/// <inheritdoc />
public override bool CanInsert(IEntity toinsert)
{
if (ContainedEntity != null)
return false;
return base.CanInsert(toinsert);
}
/// <inheritdoc />
public override bool Contains(IEntity contained)
{
if (contained != null && contained == ContainedEntity)
return true;
return false;
}
/// <inheritdoc />
protected override void InternalInsert(IEntity toinsert)
{
ContainedEntity = toinsert;
base.InternalInsert(toinsert);
}
/// <inheritdoc />
protected override void InternalRemove(IEntity toremove)
{
ContainedEntity = null;
base.InternalRemove(toremove);
}
public override void Shutdown()
{
base.Shutdown();
ContainedEntity?.Delete();
}
}
}
| using Robust.Server.GameObjects.Components.Container;
using Robust.Server.Interfaces.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using System.Collections.Generic;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects
{
public class ContainerSlot : BaseContainer
{
[ViewVariables]
public IEntity ContainedEntity { get; private set; } = null;
/// <inheritdoc />
public override IReadOnlyCollection<IEntity> ContainedEntities => new List<IEntity> { ContainedEntity }.AsReadOnly();
public ContainerSlot(string id, IContainerManager manager) : base(id, manager)
{
}
/// <inheritdoc />
public override bool CanInsert(IEntity toinsert)
{
if (ContainedEntity != null)
return false;
return base.CanInsert(toinsert);
}
/// <inheritdoc />
public override bool Contains(IEntity contained)
{
if (contained != null && contained == ContainedEntity)
return true;
return false;
}
/// <inheritdoc />
protected override void InternalInsert(IEntity toinsert)
{
ContainedEntity = toinsert;
}
/// <inheritdoc />
protected override void InternalRemove(IEntity toremove)
{
ContainedEntity = null;
}
public override void Shutdown()
{
base.Shutdown();
ContainedEntity?.Delete();
}
}
}
| mit | C# |
f2f180090ee723979d15f624f1b5f11204f87a07 | Add sample code to get the authenticated user from the site. | AlexGhiondea/SmugMug.NET | src/SmugMugTest.v2/Program.cs | src/SmugMugTest.v2/Program.cs | using SmugMug.v2.Authentication;
using SmugMug.v2.Authentication.Tokens;
using SmugMug.v2.Types;
using System.Diagnostics;
namespace SmugMugTest
{
class Program
{
private static OAuthToken s_oauthToken;
static void Main(string[] args)
{
s_oauthToken = ConsoleAuthentication.GetOAuthTokenFromProvider(new FileTokenProvider());
Debug.Assert(!s_oauthToken.Equals(OAuthToken.Invalid));
SiteEntity site = new SiteEntity(s_oauthToken);
var user = site.GetAuthenticatedUserAsync().Result;
}
}
}
| using SmugMug.v2.Authentication;
using SmugMug.v2.Authentication.Tokens;
using System.Diagnostics;
namespace SmugMugTest
{
class Program
{
private static OAuthToken s_oauthToken;
static void Main(string[] args)
{
s_oauthToken = ConsoleAuthentication.GetOAuthTokenFromProvider(new FileTokenProvider());
Debug.Assert(!s_oauthToken.Equals(OAuthToken.Invalid));
}
}
}
| mit | C# |
9bc264055e89ec267b20d4869062ccbae78a4b87 | use the more modern Test attribute | splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net | IPTables.Net.Tests/ConntrackLibraryTests.cs | IPTables.Net.Tests/ConntrackLibraryTests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using IPTables.Net.Conntrack;
using IPTables.Net.Iptables.NativeLibrary;
using NUnit.Framework;
namespace IPTables.Net.Tests
{
[TestFixture]
class ConntrackLibraryTests
{
public static bool IsLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
[Test]
public void TestStructureSize()
{
Assert.AreEqual(16, Marshal.SizeOf(typeof(ConntrackQueryFilter)));
}
[Test]
public void TestDump()
{
if (IsLinux)
{
ConntrackSystem cts = new ConntrackSystem();
List<byte[]> list = new List<byte[]>();
cts.Dump(false,list.Add);
}
}
[Test]
public void TestDumpFiltered()
{
if (IsLinux)
{
ConntrackSystem cts = new ConntrackSystem();
ConntrackQueryFilter[] qf = new ConntrackQueryFilter[]
{
new ConntrackQueryFilter{Key = cts.GetConstant("CTA_TUPLE_ORIG"), Max = cts.GetConstant("CTA_TUPLE_MAX"), CompareLength = 0},
new ConntrackQueryFilter{Key = cts.GetConstant("CTA_TUPLE_IP"), Max = cts.GetConstant("CTA_IP_MAX"), CompareLength = 0},
new ConntrackQueryFilter{Key = cts.GetConstant("CTA_IP_V4_DST"), Max = 0, CompareLength = 4},
};
List<byte[]> list = new List<byte[]>();
cts.Dump(false, list.Add);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using IPTables.Net.Conntrack;
using IPTables.Net.Iptables.NativeLibrary;
using NUnit.Framework;
namespace IPTables.Net.Tests
{
[TestFixture]
class ConntrackLibraryTests
{
public static bool IsLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
[TestCase]
public void TestStructureSize()
{
Assert.AreEqual(16, Marshal.SizeOf(typeof(ConntrackQueryFilter)));
}
[TestCase]
public void TestDump()
{
if (IsLinux)
{
ConntrackSystem cts = new ConntrackSystem();
List<byte[]> list = new List<byte[]>();
cts.Dump(false,list.Add);
}
}
[TestCase]
public void TestDumpFiltered()
{
if (IsLinux)
{
ConntrackSystem cts = new ConntrackSystem();
ConntrackQueryFilter[] qf = new ConntrackQueryFilter[]
{
new ConntrackQueryFilter{Key = cts.GetConstant("CTA_TUPLE_ORIG"), Max = cts.GetConstant("CTA_TUPLE_MAX"), CompareLength = 0},
new ConntrackQueryFilter{Key = cts.GetConstant("CTA_TUPLE_IP"), Max = cts.GetConstant("CTA_IP_MAX"), CompareLength = 0},
new ConntrackQueryFilter{Key = cts.GetConstant("CTA_IP_V4_DST"), Max = 0, CompareLength = 4},
};
List<byte[]> list = new List<byte[]>();
cts.Dump(false, list.Add);
}
}
}
}
| apache-2.0 | C# |
bc00b0ca37769844667633c189d3058e6af158cc | add initial seed method | Deepikajovy/Meal-Planner,Deepikajovy/Meal-Planner,Deepikajovy/Meal-Planner | Backend/Backend/Migrations/Configuration.cs | Backend/Backend/Migrations/Configuration.cs | using System.Collections.Generic;
using Backend.Models;
namespace Backend.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Backend.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Backend.Models.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },uit
// new Person { FullName = "Rowan Miller" }
// );
//
context.Ingredients.AddOrUpdate(
p => p.Name,
new Ingredient { Name = "Pasta",Measurement = "grams"},
new Ingredient { Name = "Cheese", Measurement = "grams"},
new Ingredient { Name = "Bacon", Measurement = "grams"}
);
context.SaveChanges();
context.Meals.AddOrUpdate(
p => p.Name,
new Meal { Name = "Lasagne",
Ingredients = context.Ingredients.Where(w => w.Name == "Pasta" || w.Name == "Cheese").ToList(),
Description = "Big Beef lasagne for the win",
ImageUrl = "http://mangiarebuono.it/wp-content/uploads/2013/11/lasagna.jpg",
},
new Meal { Name = "Bolognaise",},
new Meal { Name = "Chocolate Moose" }
);
context.SaveChanges();
context.MealPlans.AddOrUpdate(
p => p.Name,
new MealPlan { Name = "Lasagne", Meals = context.Meals.Where(w => w.Name == "Lasagne").ToList()}
);
}
}
}
| namespace Backend.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Backend.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Backend.Models.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },uit
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
| apache-2.0 | C# |
68b2c461b5f0dae4d2b9c891c3b5fd0696c8066a | Remove unused references | Livit/CefSharp,twxstar/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,dga711/CefSharp,gregmartinhtc/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,rlmcneary2/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,dga711/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,twxstar/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp | CefSharp.BrowserSubprocess/CefSubProcess.cs | CefSharp.BrowserSubprocess/CefSubProcess.cs | // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Collections.Generic;
namespace CefSharp.BrowserSubprocess
{
public class CefSubProcess : CefAppWrapper
{
public CefSubProcess(IEnumerable<string> args) : base(args)
{
}
public override void OnBrowserCreated(CefBrowserWrapper cefBrowserWrapper)
{
}
public override void OnBrowserDestroyed(CefBrowserWrapper cefBrowserWrapper)
{
}
}
} | // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Collections.Generic;
using System.Linq;
using CefSharp.Internals;
namespace CefSharp.BrowserSubprocess
{
public class CefSubProcess : CefAppWrapper
{
public CefSubProcess(IEnumerable<string> args) : base(args)
{
}
public override void OnBrowserCreated(CefBrowserWrapper cefBrowserWrapper)
{
}
public override void OnBrowserDestroyed(CefBrowserWrapper cefBrowserWrapper)
{
}
}
} | bsd-3-clause | C# |
377a294ebd674cca84d6f858dd5ff0888139cc3f | Add a Matrix room link | codingteam/codingteam.org.ru,codingteam/codingteam.org.ru | Codingteam.Site/Views/Home/Resources.cshtml | Codingteam.Site/Views/Home/Resources.cshtml | <h1>Resources</h1>
<p>Here is a list of codingteam affiliated online resources:</p>
<ul class="fa-ul">
<li>
<a href="https://github.com/codingteam/">
<i class="fa-li fa fa-github"></i> GitHub organization
</a>
</li>
<li>
<a href="xmpp:codingteam@conference.jabber.ru?join">
<i class="fa-li fa fa-lightbulb-o"></i> XMPP conference
</a>
</li>
<li>
<a href="xmpp:codingteam@conference.codingteam.org.ru?join">
<i class="fa-li fa fa-lightbulb-o"></i> XMPP conference (backup channel)
</a>
</li>
<li>
<a href="https://gitter.im/codingteam">
<i class="fa-li fa fa-users"></i> Gitter room
</a>
</li>
<li>
<a href="https://bitbucket.org/codingteam">
<i class="fa-li fa fa-bitbucket"></i> Bitbucket team
</a>
</li>
<li>
<a href="https://gitlab.com/groups/codingteam">
<i class="fa-li fa fa-code-fork"></i> GitLab team
</a>
</li>
<li>
<a href="https://loglist.xyz/">
<i class="fa-li fa fa-ambulance"></i> LogList
</a>
</li>
<li>
<a href="https://t.me/codingteam">
<i class="fa-li fa fa-envelope-o"></i> Telegram group
</a>
</li>
<li>
<a href="https://matrix.to/#/#codingteam:matrix.org">
<i class="fa-li fa fa-compress"></i> Matrix room
</a>
</li>
</ul>
| <h1>Resources</h1>
<p>Here is a list of codingteam affiliated online resources:</p>
<ul class="fa-ul">
<li>
<a href="https://github.com/codingteam/">
<i class="fa-li fa fa-github"></i> GitHub organization
</a>
</li>
<li>
<a href="xmpp:codingteam@conference.jabber.ru?join">
<i class="fa-li fa fa-lightbulb-o"></i> XMPP conference
</a>
</li>
<li>
<a href="xmpp:codingteam@conference.codingteam.org.ru?join">
<i class="fa-li fa fa-lightbulb-o"></i> XMPP conference (backup channel)
</a>
</li>
<li>
<a href="https://gitter.im/codingteam">
<i class="fa-li fa fa-users"></i> Gitter room
</a>
</li>
<li>
<a href="https://bitbucket.org/codingteam">
<i class="fa-li fa fa-bitbucket"></i> Bitbucket team
</a>
</li>
<li>
<a href="https://gitlab.com/groups/codingteam">
<i class="fa-li fa fa-code-fork"></i> GitLab team
</a>
</li>
<li>
<a href="https://loglist.xyz/">
<i class="fa-li fa fa-ambulance"></i> LogList
</a>
</li>
<li>
<a href="https://t.me/codingteam">
<i class="fa-li fa fa-envelope-o"></i> Telegram group
</a>
</li>
</ul>
| mit | C# |
bb078e298cf42077a7814ffa7181e41db440659d | Remove reusable channel code from Publisher | pardahlman/RawRabbit,northspb/RawRabbit | src/RawRabbit/Operations/Publisher.cs | src/RawRabbit/Operations/Publisher.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
using RawRabbit.Common;
using RawRabbit.Configuration.Publish;
using RawRabbit.Context;
using RawRabbit.Context.Provider;
using RawRabbit.Logging;
using RawRabbit.Operations.Contracts;
using RawRabbit.Serialization;
namespace RawRabbit.Operations
{
public class Publisher<TMessageContext> : OperatorBase, IPublisher where TMessageContext : IMessageContext
{
private readonly IMessageContextProvider<TMessageContext> _contextProvider;
private readonly ThreadLocal<Timer> _timer;
private readonly ILogger _logger = LogManager.GetLogger<Publisher<TMessageContext>>();
public Publisher(IChannelFactory channelFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider)
: base(channelFactory, serializer)
{
_contextProvider = contextProvider;
_timer = new ThreadLocal<Timer>();
}
public Task PublishAsync<T>(T message, Guid globalMessageId, PublishConfiguration config)
{
return _contextProvider
.GetMessageContextAsync(globalMessageId)
.ContinueWith(ctxTask =>
{
var channel = ChannelFactory.GetChannel();
DeclareQueue(config.Queue, channel);
DeclareExchange(config.Exchange, channel);
var properties = new BasicProperties
{
MessageId = Guid.NewGuid().ToString(),
Headers = new Dictionary<string, object>
{
[_contextProvider.ContextHeaderName] = ctxTask.Result
}
};
channel.BasicPublish(
exchange: config.Exchange.ExchangeName,
routingKey: config.RoutingKey,
basicProperties: properties,
body: Serializer.Serialize(message)
);
channel.Dispose();
});
}
public override void Dispose()
{
_logger.LogDebug("Disposing Publisher");
base.Dispose();
_timer.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
using RawRabbit.Common;
using RawRabbit.Configuration.Publish;
using RawRabbit.Context;
using RawRabbit.Context.Provider;
using RawRabbit.Logging;
using RawRabbit.Operations.Contracts;
using RawRabbit.Serialization;
namespace RawRabbit.Operations
{
public class Publisher<TMessageContext> : OperatorBase, IPublisher where TMessageContext : IMessageContext
{
private readonly IMessageContextProvider<TMessageContext> _contextProvider;
private readonly ThreadLocal<Timer> _timer;
private readonly ILogger _logger = LogManager.GetLogger<Publisher<TMessageContext>>();
public Publisher(IChannelFactory channelFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider)
: base(channelFactory, serializer)
{
_contextProvider = contextProvider;
_timer = new ThreadLocal<Timer>();
}
public Task PublishAsync<T>(T message, Guid globalMessageId, PublishConfiguration config)
{
return _contextProvider
.GetMessageContextAsync(globalMessageId)
.ContinueWith(ctxTask =>
{
var channel = GetChannel();
DeclareQueue(config.Queue, channel);
DeclareExchange(config.Exchange, channel);
var properties = new BasicProperties
{
MessageId = Guid.NewGuid().ToString(),
Headers = new Dictionary<string, object>
{
[_contextProvider.ContextHeaderName] = ctxTask.Result
}
};
channel.BasicPublish(
exchange: config.Exchange.ExchangeName,
routingKey: config.RoutingKey,
basicProperties: properties,
body: Serializer.Serialize(message)
);
channel.Dispose();
});
}
private IModel GetChannel()
{
if (_timer.IsValueCreated)
{
return ChannelFactory.GetChannel();
}
var channel = ChannelFactory.GetChannel();
Timer closeChannel = null;
closeChannel = new Timer(state =>
{
closeChannel?.Dispose();
channel.Dispose();
}, null, TimeSpan.FromSeconds(1), new TimeSpan(-1));
_timer.Value = closeChannel;
return channel;
}
public override void Dispose()
{
_logger.LogDebug("Disposing Publisher");
base.Dispose();
_timer.Dispose();
}
}
}
| mit | C# |
320688652c586cfd5016efca50f06da7a625a0a3 | Remove redundant wrapping | ericstj/core-setup,vivmishra/core-setup,rakeshsinghranchi/core-setup,vivmishra/core-setup,steveharter/core-setup,chcosta/core-setup,weshaggard/core-setup,zamont/core-setup,ramarag/core-setup,crummel/dotnet_core-setup,rakeshsinghranchi/core-setup,MichaelSimons/core-setup,joperezr/core-setup,ramarag/core-setup,vivmishra/core-setup,crummel/dotnet_core-setup,ravimeda/core-setup,chcosta/core-setup,chcosta/core-setup,ericstj/core-setup,weshaggard/core-setup,ramarag/core-setup,wtgodbe/core-setup,steveharter/core-setup,chcosta/core-setup,joperezr/core-setup,vivmishra/core-setup,wtgodbe/core-setup,ericstj/core-setup,janvorli/core-setup,crummel/dotnet_core-setup,ravimeda/core-setup,steveharter/core-setup,chcosta/core-setup,MichaelSimons/core-setup,ravimeda/core-setup,rakeshsinghranchi/core-setup,janvorli/core-setup,weshaggard/core-setup,joperezr/core-setup,zamont/core-setup,ramarag/core-setup,janvorli/core-setup,joperezr/core-setup,wtgodbe/core-setup,rakeshsinghranchi/core-setup,ramarag/core-setup,zamont/core-setup,MichaelSimons/core-setup,vivmishra/core-setup,MichaelSimons/core-setup,vivmishra/core-setup,weshaggard/core-setup,ericstj/core-setup,gkhanna79/core-setup,joperezr/core-setup,crummel/dotnet_core-setup,janvorli/core-setup,janvorli/core-setup,ravimeda/core-setup,rakeshsinghranchi/core-setup,zamont/core-setup,MichaelSimons/core-setup,rakeshsinghranchi/core-setup,wtgodbe/core-setup,gkhanna79/core-setup,crummel/dotnet_core-setup,ramarag/core-setup,zamont/core-setup,joperezr/core-setup,gkhanna79/core-setup,steveharter/core-setup,weshaggard/core-setup,MichaelSimons/core-setup,ericstj/core-setup,wtgodbe/core-setup,gkhanna79/core-setup,weshaggard/core-setup,wtgodbe/core-setup,gkhanna79/core-setup,zamont/core-setup,steveharter/core-setup,ravimeda/core-setup,ravimeda/core-setup,janvorli/core-setup,ericstj/core-setup,chcosta/core-setup,steveharter/core-setup,crummel/dotnet_core-setup,gkhanna79/core-setup | build_projects/dotnet-host-build/NugetUtil.cs | build_projects/dotnet-host-build/NugetUtil.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.DotNet.Cli.Build.Framework;
using NugetProgram = NuGet.CommandLine.XPlat.Program;
namespace Microsoft.DotNet.Cli.Build
{
public static class NuGetUtil
{
[Flags]
public enum NuGetIncludePackageType
{
Standard = 1,
Symbols = 2
}
public static void PushPackages(
string packageDirPath,
string destinationUrl,
string apiKey,
NuGetIncludePackageType includePackageTypes)
{
List<string> paths = new List<string>();
if (includePackageTypes.HasFlag(NuGetIncludePackageType.Standard))
{
paths.AddRange(Directory.GetFiles(packageDirPath, "*.nupkg").Where(p => !p.EndsWith(".symbols.nupkg")));
}
if (includePackageTypes.HasFlag(NuGetIncludePackageType.Symbols))
{
paths.AddRange(Directory.GetFiles(packageDirPath, "*.symbols.nupkg"));
}
foreach (var path in paths)
{
int result = RunNuGetCommand(
"push",
"-s", destinationUrl,
"-k", apiKey,
"--timeout", "3600",
path);
if (result != 0)
{
throw new BuildFailureException($"NuGet Push failed with exit code '{result}'.");
}
}
}
private static int RunNuGetCommand(params string[] nugetArgs)
{
var nugetAssembly = typeof(NugetProgram).GetTypeInfo().Assembly;
var mainMethod = nugetAssembly.EntryPoint;
return (int)mainMethod.Invoke(null, new object[] { nugetArgs });
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.DotNet.Cli.Build.Framework;
using NugetProgram = NuGet.CommandLine.XPlat.Program;
namespace Microsoft.DotNet.Cli.Build
{
public static class NuGetUtil
{
[Flags]
public enum NuGetIncludePackageType
{
Standard = 1,
Symbols = 2
}
public static void PushPackages(
string packageDirPath,
string destinationUrl,
string apiKey,
NuGetIncludePackageType includePackageTypes)
{
List<string> paths = new List<string>();
if ((includePackageTypes.HasFlag(NuGetIncludePackageType.Standard)))
{
paths.AddRange(Directory.GetFiles(packageDirPath, "*.nupkg").Where(p => !p.EndsWith(".symbols.nupkg")));
}
if ((includePackageTypes.HasFlag(NuGetIncludePackageType.Symbols)))
{
paths.AddRange(Directory.GetFiles(packageDirPath, "*.symbols.nupkg"));
}
foreach (var path in paths)
{
int result = RunNuGetCommand(
"push",
"-s", destinationUrl,
"-k", apiKey,
"--timeout", "3600",
path);
if (result != 0)
{
throw new BuildFailureException($"NuGet Push failed with exit code '{result}'.");
}
}
}
private static int RunNuGetCommand(params string[] nugetArgs)
{
var nugetAssembly = typeof(NugetProgram).GetTypeInfo().Assembly;
var mainMethod = nugetAssembly.EntryPoint;
return (int)mainMethod.Invoke(null, new object[] { nugetArgs });
}
}
}
| mit | C# |
f7e9e6e42065646197db8edec91c8b5747e4a18f | Change warning colour. | endjin/Endjin.Cancelable,endjin/Endjin.Cancelable | Solutions/Endjin.Cancelable.Demo/Program.cs | Solutions/Endjin.Cancelable.Demo/Program.cs | namespace Endjin.Cancelable.Demo
{
#region Using Directives
using System;
using System.Threading;
using System.Threading.Tasks;
using Endjin.Contracts;
using Endjin.Core.Composition;
using Endjin.Core.Container;
#endregion
public class Program
{
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Ensure you are running the Azure Storage Emulator!");
Console.ResetColor();
ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait();
var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>();
var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045";
cancelable.CreateToken(cancellationToken);
cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait();
Console.WriteLine("Press Any Key to Exit!");
Console.ReadKey();
}
private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken)
{
int counter = 0;
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T"));
await Task.Delay(TimeSpan.FromSeconds(1));
counter++;
if (counter == 15)
{
Console.WriteLine("Long Running Process Ran to Completion!");
break;
}
}
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Long Running Process was Cancelled!");
}
}
}
} | namespace Endjin.Cancelable.Demo
{
#region Using Directives
using System;
using System.Threading;
using System.Threading.Tasks;
using Endjin.Contracts;
using Endjin.Core.Composition;
using Endjin.Core.Container;
#endregion
public class Program
{
public static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Ensure you are running the Azure Storage Emulator!");
Console.ResetColor();
ApplicationServiceLocator.InitializeAsync(new Container(), new DesktopBootstrapper()).Wait();
var cancelable = ApplicationServiceLocator.Container.Resolve<ICancelable>();
var cancellationToken = "E75FF4F5-755E-4FB9-ABE0-24BD81F4D045";
cancelable.CreateToken(cancellationToken);
cancelable.RunUntilCompleteOrCancelledAsync(DoSomethingLongRunningAsync, cancellationToken).Wait();
Console.WriteLine("Press Any Key to Exit!");
Console.ReadKey();
}
private static async Task DoSomethingLongRunningAsync(CancellationToken cancellationToken)
{
int counter = 0;
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Doing something {0}", DateTime.Now.ToString("T"));
await Task.Delay(TimeSpan.FromSeconds(1));
counter++;
if (counter == 15)
{
Console.WriteLine("Long Running Process Ran to Completion!");
break;
}
}
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Long Running Process was Cancelled!");
}
}
}
} | mit | C# |
04cb099429cf054535e63dfa6c93df481826dbf0 | Make it work with any number of arguments | sfinnie/concomp,sfinnie/concomp,sfinnie/concomp,sfinnie/concomp,sfinnie/concomp | csharp/Program.cs | csharp/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ConComp
{
internal class Program
{
private static void Main(string[] args)
{
var tasks = new Dictionary<string, Task<long>>();
foreach (var arg in args)
{
var task = Task<long>.Factory.StartNew(() => new FileInfo(arg).Length);
tasks.Add(arg, task);
}
Task.WaitAll(tasks.Values.Cast<Task>().ToArray());
var maxFileSize = tasks.Max(t => t.Value.Result);
var biggests = tasks.Where(t => t.Value.Result == maxFileSize).ToList();
if (biggests.Count == tasks.Count)
{
Console.WriteLine("All files are even");
}
else if (biggests.Count > 1)
{
var all = string.Join(", ", biggests.Select(b => b.Key));
Console.WriteLine($"{all} are the biggest");
}
else
{
var biggest = biggests.Single();
Console.WriteLine($"{biggest.Key} is the biggest");
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConComp
{
class Program
{
static void Main(string[] args)
{
var fname1 = args[0];
var fname2 = args[1];
var task1 = Task<long>.Factory.StartNew(() => new FileInfo(fname1).Length);
var task2 = Task<long>.Factory.StartNew(() => new FileInfo(fname2).Length);
Task.WaitAll(task1, task2);
if (task1.Result > task2.Result)
{
Console.WriteLine($"{fname1} is bigger");
}
else if (task2.Result > task1.Result)
{
Console.WriteLine($"{fname2} is bigger");
}
else
{
Console.WriteLine("The files are the same size");
}
}
}
} | apache-2.0 | C# |
8a61b641cb6302595ecdf6dce648360123e159b3 | fix a virtual keyword | hazzik/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core | src/NHibernate/Mapping/Any.cs | src/NHibernate/Mapping/Any.cs | using System;
using NHibernate.Type;
namespace NHibernate.Mapping
{
public class Any : Value
{
private IType identifierType;
private IType metaType = NHibernate.Class;
public Any(Table table) : base(table){
}
public override bool IsAny {
get {
return true;
}
}
/// <summary>
/// Get or set the identifier type
/// </summary>
public virtual IType IdentifierType {
get {
return identifierType;
}
set {
this.identifierType = value;
}
}
public override IType Type {
get {
return new ObjectType(metaType, identifierType);
}
set {
throw new NotSupportedException("cannot set type of an Any");
}
}
public override void SetTypeByReflection(System.Type propertyClass, string propertyName) {}
/// <summary>
/// Get or set the metatype
/// </summary>
public virtual IType MetaType {
get {
return metaType;
}
set {
metaType = value;
}
}
}
} | using System;
using NHibernate.Type;
namespace NHibernate.Mapping
{
public class Any : Value
{
private IType identifierType;
private IType metaType = NHibernate.Class;
public Any(Table table) : base(table){
}
public override bool IsAny {
get {
return true;
}
}
/// <summary>
/// Get or set the identifier type
/// </summary>
public virtual IType IdentifierType {
get {
return identifierType;
}
set {
this.identifierType = value;
}
}
public override IType Type {
get {
return new ObjectType(metaType, identifierType);
}
set {
throw new NotSupportedException("cannot set type of an Any");
}
}
public override void SetTypeByReflection(System.Type propertyClass, string propertyName) {}
/// <summary>
/// Get or set the metatype
/// </summary>
public IType MetaType {
get {
return metaType;
}
set {
metaType = value;
}
}
}
} | lgpl-2.1 | C# |
85395a6555945b4018405a4415f7f853761dac1e | Add a method to create an instance of the applicable path element type to resolver | Domysee/Pather.CSharp | src/Pather.CSharp/Resolver.cs | src/Pather.CSharp/Resolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Pather.CSharp.PathElements;
namespace Pather.CSharp
{
public class Resolver
{
private IList<Type> pathElementTypes;
public Resolver()
{
pathElementTypes = new List<Type>();
pathElementTypes.Add(typeof(Property));
}
public object Resolve(object target, string path)
{
var pathElements = path.Split('.');
var tempResult = target;
foreach(var pathElement in pathElements)
{
PropertyInfo p = tempResult.GetType().GetProperty(pathElement);
if (p == null)
throw new ArgumentException($"The property {pathElement} could not be found.");
tempResult = p.GetValue(tempResult);
}
var result = tempResult;
return result;
}
private object createPathElement(string pathElement)
{
//get the first applicable path element type
var pathElementType = pathElementTypes.Where(t =>
{
MethodInfo applicableMethod = t.GetMethod("IsApplicable", BindingFlags.Static | BindingFlags.Public);
if (applicableMethod == null)
throw new InvalidOperationException($"The type {t.Name} does not have a static method IsApplicable");
bool? applicable = applicableMethod.Invoke(null, new[] { pathElement }) as bool?;
if (applicable == null)
throw new InvalidOperationException($"IsApplicable of type {t.Name} does not return bool");
return applicable.Value;
}).FirstOrDefault();
if (pathElementType == null)
throw new InvalidOperationException($"There is no applicable path element type for {pathElement}");
var result = Activator.CreateInstance(pathElementType, pathElement); //each path element type must have a constructor that takes a string parameter
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Pather.CSharp.PathElements;
namespace Pather.CSharp
{
public class Resolver
{
private IList<Type> pathElementTypes;
public Resolver()
{
pathElementTypes = new List<Type>();
pathElementTypes.Add(typeof(Property));
}
public object Resolve(object target, string path)
{
var pathElements = path.Split('.');
var tempResult = target;
foreach(var pathElement in pathElements)
{
PropertyInfo p = tempResult.GetType().GetProperty(pathElement);
if (p == null)
throw new ArgumentException($"The property {pathElement} could not be found.");
tempResult = p.GetValue(tempResult);
}
var result = tempResult;
return result;
}
}
}
| mit | C# |
ff9f6192390338de9187acf102d6763c0e5fc79b | Bring back the LoadFrom method. | SparkPost/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost | src/SparkPost/Transmission.cs | src/SparkPost/Transmission.cs | using System.Collections.Generic;
using System.Net.Mail;
using SparkPost.Utilities;
namespace SparkPost
{
public class Transmission
{
public Transmission()
{
Recipients = new List<Recipient>();
Metadata = new Dictionary<string, object>();
SubstitutionData = new Dictionary<string, object>();
Content = new Content();
Options = new Options();
}
public Transmission(MailMessage message) : this()
{
MailMessageMapping.ToTransmission(message, this);
}
public string Id { get; set; }
public string State { get; set; }
public Options Options { get; set; }
public IList<Recipient> Recipients { get; set; }
public string ListId { get; set; }
public string CampaignId { get; set; }
public string Description { get; set; }
public IDictionary<string, object> Metadata { get; set; }
public IDictionary<string, object> SubstitutionData { get; set; }
public string ReturnPath { get; set; }
public Content Content { get; set; }
public int TotalRecipients { get; set; }
public int NumGenerated { get; set; }
public int NumFailedGeneration { get; set; }
public int NumInvalidRecipients { get; set; }
public void LoadFrom(MailMessage message)
{
MailMessageMapping.ToTransmission(message, this);
}
}
} | using System.Collections.Generic;
using System.Net.Mail;
using SparkPost.Utilities;
namespace SparkPost
{
public class Transmission
{
public Transmission()
{
Recipients = new List<Recipient>();
Metadata = new Dictionary<string, object>();
SubstitutionData = new Dictionary<string, object>();
Content = new Content();
Options = new Options();
}
public Transmission(MailMessage message) : this()
{
MailMessageMapping.ToTransmission(message, this);
}
public string Id { get; set; }
public string State { get; set; }
public Options Options { get; set; }
public IList<Recipient> Recipients { get; set; }
public string ListId { get; set; }
public string CampaignId { get; set; }
public string Description { get; set; }
public IDictionary<string, object> Metadata { get; set; }
public IDictionary<string, object> SubstitutionData { get; set; }
public string ReturnPath { get; set; }
public Content Content { get; set; }
public int TotalRecipients { get; set; }
public int NumGenerated { get; set; }
public int NumFailedGeneration { get; set; }
public int NumInvalidRecipients { get; set; }
}
} | apache-2.0 | C# |
4eb03f91bfdac6a9780eb4a2c8ec664820a42f96 | Fix bug argument matcher would cause index out of range | terrajobst/apiporter | src/ApiPorter.Patterns/ArgumentMatcher.cs | src/ApiPorter.Patterns/ArgumentMatcher.cs | using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ApiPorter.Patterns
{
internal sealed class ArgumentMatcher : Matcher
{
private readonly ArgumentVariable _variable;
private readonly int _following;
public ArgumentMatcher(ArgumentVariable variable, int following)
{
_variable = variable;
_following = following;
}
public override Match Run(SyntaxNodeOrToken nodeOrToken)
{
if (nodeOrToken.Kind() != SyntaxKind.Argument)
return Match.NoMatch;
var argument = (ArgumentSyntax) nodeOrToken.AsNode();
if (_variable.MinOccurrences == 1 && _variable.MaxOccurrences == 1)
return Match.Success.WithSyntaxNodeOrToken(argument);
var argumentList = argument.Parent as ArgumentListSyntax;
if (argumentList == null)
return Match.NoMatch;
var currentIndex = argumentList.Arguments.IndexOf(argument);
var availableCount = argumentList.Arguments.Count - currentIndex - _following;
if (availableCount == 0)
return Match.NoMatch;
var captureCount = _variable.MaxOccurrences == null
? availableCount
: Math.Min(availableCount, _variable.MaxOccurrences.Value);
if (captureCount < _variable.MinOccurrences)
return Match.NoMatch;
var endIndex = currentIndex + captureCount - 1;
var endArgument = argumentList.Arguments[endIndex];
return Match.Success.AddCapture(_variable, argument, endArgument);
}
}
} | using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ApiPorter.Patterns
{
internal sealed class ArgumentMatcher : Matcher
{
private readonly ArgumentVariable _variable;
private readonly int _following;
public ArgumentMatcher(ArgumentVariable variable, int following)
{
_variable = variable;
_following = following;
}
public override Match Run(SyntaxNodeOrToken nodeOrToken)
{
if (nodeOrToken.Kind() != SyntaxKind.Argument)
return Match.NoMatch;
var argument = (ArgumentSyntax) nodeOrToken.AsNode();
if (_variable.MinOccurrences == 1 && _variable.MaxOccurrences == 1)
return Match.Success.WithSyntaxNodeOrToken(argument);
var argumentList = argument.Parent as ArgumentListSyntax;
if (argumentList == null)
return Match.NoMatch;
var currentIndex = argumentList.Arguments.IndexOf(argument);
var availableCount = argumentList.Arguments.Count - currentIndex - _following;
var captureCount = _variable.MaxOccurrences == null
? availableCount
: Math.Min(availableCount, _variable.MaxOccurrences.Value);
if (captureCount < _variable.MinOccurrences)
return Match.NoMatch;
var endIndex = currentIndex + captureCount - 1;
var endArgument = argumentList.Arguments[endIndex];
return Match.Success.AddCapture(_variable, argument, endArgument);
}
}
} | mit | C# |
8d6b2d768c9e98955709e9beceb65d20558f478a | Delete unused IntPtrHelper.Subtract | YoupHulsebos/corefx,krytarowski/corefx,BrennanConroy/corefx,nbarbettini/corefx,richlander/corefx,tijoytom/corefx,nchikanov/corefx,Ermiar/corefx,stone-li/corefx,wtgodbe/corefx,ericstj/corefx,axelheer/corefx,alexperovich/corefx,twsouthwick/corefx,Jiayili1/corefx,ptoonen/corefx,yizhang82/corefx,gkhanna79/corefx,stone-li/corefx,rjxby/corefx,nchikanov/corefx,nchikanov/corefx,the-dwyer/corefx,parjong/corefx,alexperovich/corefx,mmitche/corefx,billwert/corefx,elijah6/corefx,yizhang82/corefx,dhoehna/corefx,twsouthwick/corefx,krytarowski/corefx,Ermiar/corefx,seanshpark/corefx,jlin177/corefx,Petermarcu/corefx,ptoonen/corefx,krytarowski/corefx,nchikanov/corefx,elijah6/corefx,dotnet-bot/corefx,richlander/corefx,twsouthwick/corefx,mazong1123/corefx,MaggieTsang/corefx,billwert/corefx,parjong/corefx,ptoonen/corefx,zhenlan/corefx,mazong1123/corefx,dhoehna/corefx,elijah6/corefx,rahku/corefx,ericstj/corefx,mmitche/corefx,gkhanna79/corefx,JosephTremoulet/corefx,ravimeda/corefx,shimingsg/corefx,gkhanna79/corefx,Petermarcu/corefx,cydhaselton/corefx,nchikanov/corefx,stephenmichaelf/corefx,alexperovich/corefx,JosephTremoulet/corefx,rjxby/corefx,dhoehna/corefx,ViktorHofer/corefx,billwert/corefx,mazong1123/corefx,ViktorHofer/corefx,JosephTremoulet/corefx,the-dwyer/corefx,ptoonen/corefx,dotnet-bot/corefx,zhenlan/corefx,krk/corefx,axelheer/corefx,jlin177/corefx,nchikanov/corefx,weltkante/corefx,axelheer/corefx,Petermarcu/corefx,krk/corefx,marksmeltzer/corefx,JosephTremoulet/corefx,fgreinacher/corefx,zhenlan/corefx,jlin177/corefx,ptoonen/corefx,jlin177/corefx,ericstj/corefx,seanshpark/corefx,richlander/corefx,ravimeda/corefx,seanshpark/corefx,stephenmichaelf/corefx,axelheer/corefx,mmitche/corefx,Ermiar/corefx,Petermarcu/corefx,marksmeltzer/corefx,axelheer/corefx,rahku/corefx,twsouthwick/corefx,Ermiar/corefx,DnlHarvey/corefx,alexperovich/corefx,JosephTremoulet/corefx,weltkante/corefx,tijoytom/corefx,elijah6/corefx,YoupHulsebos/corefx,gkhanna79/corefx,rubo/corefx,DnlHarvey/corefx,cydhaselton/corefx,Ermiar/corefx,MaggieTsang/corefx,ViktorHofer/corefx,ravimeda/corefx,DnlHarvey/corefx,dhoehna/corefx,weltkante/corefx,cydhaselton/corefx,rubo/corefx,jlin177/corefx,Jiayili1/corefx,ViktorHofer/corefx,Ermiar/corefx,Jiayili1/corefx,DnlHarvey/corefx,elijah6/corefx,shimingsg/corefx,krk/corefx,wtgodbe/corefx,axelheer/corefx,nbarbettini/corefx,rahku/corefx,nbarbettini/corefx,the-dwyer/corefx,weltkante/corefx,yizhang82/corefx,mazong1123/corefx,YoupHulsebos/corefx,Petermarcu/corefx,MaggieTsang/corefx,billwert/corefx,mmitche/corefx,stone-li/corefx,the-dwyer/corefx,parjong/corefx,gkhanna79/corefx,yizhang82/corefx,richlander/corefx,wtgodbe/corefx,parjong/corefx,BrennanConroy/corefx,mazong1123/corefx,mazong1123/corefx,the-dwyer/corefx,tijoytom/corefx,the-dwyer/corefx,rahku/corefx,stephenmichaelf/corefx,dhoehna/corefx,rjxby/corefx,alexperovich/corefx,rjxby/corefx,krytarowski/corefx,richlander/corefx,Petermarcu/corefx,dotnet-bot/corefx,krytarowski/corefx,fgreinacher/corefx,JosephTremoulet/corefx,krytarowski/corefx,seanshpark/corefx,Petermarcu/corefx,YoupHulsebos/corefx,shimingsg/corefx,ravimeda/corefx,richlander/corefx,marksmeltzer/corefx,nbarbettini/corefx,krk/corefx,mmitche/corefx,stone-li/corefx,stone-li/corefx,nbarbettini/corefx,twsouthwick/corefx,cydhaselton/corefx,ViktorHofer/corefx,ravimeda/corefx,elijah6/corefx,cydhaselton/corefx,ptoonen/corefx,shimingsg/corefx,jlin177/corefx,krk/corefx,YoupHulsebos/corefx,parjong/corefx,wtgodbe/corefx,JosephTremoulet/corefx,krk/corefx,yizhang82/corefx,rahku/corefx,mmitche/corefx,krytarowski/corefx,stone-li/corefx,ViktorHofer/corefx,MaggieTsang/corefx,wtgodbe/corefx,ptoonen/corefx,Jiayili1/corefx,seanshpark/corefx,zhenlan/corefx,yizhang82/corefx,parjong/corefx,ericstj/corefx,cydhaselton/corefx,weltkante/corefx,rjxby/corefx,YoupHulsebos/corefx,zhenlan/corefx,wtgodbe/corefx,dotnet-bot/corefx,marksmeltzer/corefx,stephenmichaelf/corefx,dhoehna/corefx,rubo/corefx,billwert/corefx,weltkante/corefx,dotnet-bot/corefx,the-dwyer/corefx,gkhanna79/corefx,billwert/corefx,Jiayili1/corefx,rjxby/corefx,mazong1123/corefx,nchikanov/corefx,richlander/corefx,rjxby/corefx,shimingsg/corefx,marksmeltzer/corefx,jlin177/corefx,DnlHarvey/corefx,billwert/corefx,shimingsg/corefx,tijoytom/corefx,seanshpark/corefx,MaggieTsang/corefx,dhoehna/corefx,rubo/corefx,BrennanConroy/corefx,stephenmichaelf/corefx,rahku/corefx,ericstj/corefx,alexperovich/corefx,zhenlan/corefx,nbarbettini/corefx,marksmeltzer/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,wtgodbe/corefx,zhenlan/corefx,krk/corefx,seanshpark/corefx,fgreinacher/corefx,dotnet-bot/corefx,MaggieTsang/corefx,parjong/corefx,twsouthwick/corefx,nbarbettini/corefx,weltkante/corefx,dotnet-bot/corefx,gkhanna79/corefx,stone-li/corefx,twsouthwick/corefx,yizhang82/corefx,Jiayili1/corefx,tijoytom/corefx,Ermiar/corefx,tijoytom/corefx,elijah6/corefx,cydhaselton/corefx,ravimeda/corefx,mmitche/corefx,fgreinacher/corefx,rubo/corefx,alexperovich/corefx,ericstj/corefx,shimingsg/corefx,Jiayili1/corefx,stephenmichaelf/corefx,YoupHulsebos/corefx,marksmeltzer/corefx,ViktorHofer/corefx,MaggieTsang/corefx,ericstj/corefx,DnlHarvey/corefx,ravimeda/corefx,rahku/corefx,tijoytom/corefx | src/Common/src/System/Net/IntPtrHelper.cs | src/Common/src/System/Net/IntPtrHelper.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.
namespace System.Net
{
internal static class IntPtrHelper
{
internal static IntPtr Add(IntPtr a, int b) => (IntPtr)((long)a + (long)b);
}
}
| // 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.
namespace System.Net
{
internal static class IntPtrHelper
{
internal static IntPtr Add(IntPtr a, int b)
{
return (IntPtr)((long)a + (long)b);
}
internal static long Subtract(IntPtr a, IntPtr b)
{
return ((long)a - (long)b);
}
}
}
| mit | C# |
5276ace3799c95d9a8575f1f8cba307248340aab | update user agent version | watson-developer-cloud/dotnet-standard-sdk,watson-developer-cloud/dotnet-standard-sdk | src/IBM.WatsonDeveloperCloud/Constants.cs | src/IBM.WatsonDeveloperCloud/Constants.cs | /**
* Copyright 2017 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace IBM.WatsonDeveloperCloud
{
/// <summary>
/// This class holds constant values for the SDK.
/// </summary>
public class Constants
{
/// <summary>
/// The version number for this SDK build. Added to the header in
/// each request as `User-Agent`.
/// </summary>
public const string SDK_VERSION = "watson-apis-dotnet-sdk/2.3.0";
/// <summary>
/// A constant used to access custom request headers in the dynamic
/// customData object.
/// </summary>
public const string CUSTOM_REQUEST_HEADERS = "custom_request_headers";
/// <summary>
/// A constant used to access response headers in the dynamic
/// customData object.
/// </summary>
public const string RESPONSE_HEADERS = "response_headers";
/// <summary>
/// A constnat used to access response json in the dynamic customData
/// object.
/// </summary>
public const string JSON = "json";
}
}
| /**
* Copyright 2017 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace IBM.WatsonDeveloperCloud
{
/// <summary>
/// This class holds constant values for the SDK.
/// </summary>
public class Constants
{
/// <summary>
/// The version number for this SDK build. Added to the header in
/// each request as `User-Agent`.
/// </summary>
public const string SDK_VERSION = "watson-apis-dotnet-sdk/2.2.2";
/// <summary>
/// A constant used to access custom request headers in the dynamic
/// customData object.
/// </summary>
public const string CUSTOM_REQUEST_HEADERS = "custom_request_headers";
/// <summary>
/// A constant used to access response headers in the dynamic
/// customData object.
/// </summary>
public const string RESPONSE_HEADERS = "response_headers";
/// <summary>
/// A constnat used to access response json in the dynamic customData
/// object.
/// </summary>
public const string JSON = "json";
}
}
| apache-2.0 | C# |
51bfb38f8435cdc6145010f06adf934773137499 | remove logging, which happened too early | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | unity/EditorPlugin/AfterUnity56/EntryPoint.cs | unity/EditorPlugin/AfterUnity56/EntryPoint.cs | using System;
using JetBrains.Diagnostics;
using UnityEditor;
namespace JetBrains.Rider.Unity.Editor.AfterUnity56
{
[InitializeOnLoad]
public static class EntryPoint
{
static EntryPoint()
{
PluginEntryPoint.OnModelInitialization += UnitTesting.Initialization.OnModelInitializationHandler;
PluginEntryPoint.OnModelInitialization += Navigation.Initialization.OnModelInitializationHandler;
AppDomain.CurrentDomain.DomainUnload += (EventHandler) ((_, __) =>
{
PluginEntryPoint.OnModelInitialization -= UnitTesting.Initialization.OnModelInitializationHandler;
PluginEntryPoint.OnModelInitialization -= Navigation.Initialization.OnModelInitializationHandler;
});
}
}
} | using System;
using JetBrains.Diagnostics;
using UnityEditor;
namespace JetBrains.Rider.Unity.Editor.AfterUnity56
{
[InitializeOnLoad]
public static class EntryPoint
{
private static readonly ILog ourLogger = Log.GetLog("AfterUnity56.EntryPoint");
static EntryPoint()
{
ourLogger.Verbose("AfterUnity56.EntryPoint");
PluginEntryPoint.OnModelInitialization += UnitTesting.Initialization.OnModelInitializationHandler;
PluginEntryPoint.OnModelInitialization += Navigation.Initialization.OnModelInitializationHandler;
AppDomain.CurrentDomain.DomainUnload += (EventHandler) ((_, __) =>
{
PluginEntryPoint.OnModelInitialization -= UnitTesting.Initialization.OnModelInitializationHandler;
PluginEntryPoint.OnModelInitialization -= Navigation.Initialization.OnModelInitializationHandler;
});
}
}
} | apache-2.0 | C# |
0199b81fd159e52a5da43a7c71c55a50a299d495 | use only date for the FirstRegistration field | mdavid626/artemis | src/Artemis.Web/App_Start/AutoMapperConfig.cs | src/Artemis.Web/App_Start/AutoMapperConfig.cs | using Artemis.Common;
using Artemis.Web.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Artemis.Web
{
public static class AutoMapperConfig
{
public static IMapper Create()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<CarAdvert, CarAdvertViewModel>()
.ForMember(d => d.New, opt => opt.MapFrom(src => src.IsNew))
.ForMember(d => d.Fuel, opt => opt.MapFrom(src => src.Fuel.ToString().ToLower()))
.ForMember(d => d.FirstRegistration, opt => opt.MapFrom(src => src.FirstRegistration.Value.Date));
cfg.CreateMap<CarAdvertViewModel, CarAdvert>()
.ForMember(d => d.IsNew, opt => opt.MapFrom(src => src.New))
.ForMember(d => d.Fuel, opt => opt.MapFrom(src => Enum.Parse(typeof(FuelType), src.Fuel, true)))
.ForMember(d => d.FirstRegistration, opt => opt.MapFrom(src => src.FirstRegistration.Value.Date));
});
return config.CreateMapper();
}
}
} | using Artemis.Common;
using Artemis.Web.Models;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Artemis.Web
{
public static class AutoMapperConfig
{
public static IMapper Create()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<CarAdvert, CarAdvertViewModel>()
.ForMember(d => d.New, opt => opt.MapFrom(src => src.IsNew))
.ForMember(d => d.Fuel, opt => opt.MapFrom(src => src.Fuel.ToString().ToLower()));
cfg.CreateMap<CarAdvertViewModel, CarAdvert>()
.ForMember(d => d.IsNew, opt => opt.MapFrom(src => src.New))
.ForMember(d => d.Fuel, opt => opt.MapFrom(src => Enum.Parse(typeof(FuelType), src.Fuel, true)));
});
return config.CreateMapper();
}
}
} | mit | C# |
41597efdf71b7c65827de5fe7ec4bae5a110f809 | Hide health bar in no fail | 2yangk23/osu,ZLima12/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,ZLima12/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,2yangk23/osu,peppy/osu-new,EVAST9919/osu,peppy/osu,johnneijzen/osu | osu.Game/Rulesets/Mods/ModNoFail.cs | osu.Game/Rulesets/Mods/ModNoFail.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModNoFail : Mod, IApplicableFailOverride, IApplicableToHUD
{
public override string Name => "No Fail";
public override string Acronym => "NF";
public override IconUsage Icon => OsuIcon.ModNofail;
public override ModType Type => ModType.DifficultyReduction;
public override string Description => "You can't fail, no matter what.";
public override double ScoreMultiplier => 0.5;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModAutoplay) };
/// <summary>
/// We never fail, 'yo.
/// </summary>
public bool AllowFail => false;
public void ApplyToHUD(HUDOverlay overlay) => overlay.HealthDisplay.Hide();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModNoFail : Mod, IApplicableFailOverride
{
public override string Name => "No Fail";
public override string Acronym => "NF";
public override IconUsage Icon => OsuIcon.ModNofail;
public override ModType Type => ModType.DifficultyReduction;
public override string Description => "You can't fail, no matter what.";
public override double ScoreMultiplier => 0.5;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModRelax), typeof(ModSuddenDeath), typeof(ModAutoplay) };
/// <summary>
/// We never fail, 'yo.
/// </summary>
public bool AllowFail => false;
}
}
| mit | C# |
58dc849118c26d440b07a4c761a45daabb9e1f43 | Add standard header | jdno/AIChallengeFramework-Tests | Map/RegionTests.cs | Map/RegionTests.cs | //
// Copyright 2014 jdno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NUnit.Framework;
using System;
using AIChallengeFramework;
namespace AIChallengeFrameworkTests
{
[TestFixture ()]
public class RegionTests
{
[SetUp ()]
public void SetUp ()
{
// Deactive logger for tests
Logger.LogLevel = Logger.Severity.OFF;
}
[Test ()]
public void TestAddNeighbor ()
{
Continent c1 = new Continent (0, 2);
Continent c2 = new Continent (1, 5);
Region r1 = new Region (0, c1);
Region r2 = new Region (1, c1);
Region r3 = new Region (2, c2);
r1.AddNeighbor (r1);
Assert.AreEqual (0, r1.Neighbors.Count);
r1.AddNeighbor (r2);
Assert.AreEqual (1, r1.Neighbors.Count);
Assert.IsFalse (r1.IsBorderRegion ());
r1.AddNeighbor (r3);
Assert.AreEqual (2, r1.Neighbors.Count);
Assert.IsTrue (r1.IsBorderRegion ());
Assert.AreEqual (1, c1.BorderRegions.Count);
}
}
}
| using NUnit.Framework;
using System;
using AIChallengeFramework;
namespace AIChallengeFrameworkTests
{
[TestFixture ()]
public class RegionTests
{
[SetUp ()]
public void SetUp ()
{
// Deactive logger for tests
Logger.LogLevel = Logger.Severity.OFF;
}
[Test ()]
public void TestAddNeighbor ()
{
Continent c1 = new Continent (0, 2);
Continent c2 = new Continent (1, 5);
Region r1 = new Region (0, c1);
Region r2 = new Region (1, c1);
Region r3 = new Region (2, c2);
r1.AddNeighbor (r1);
Assert.AreEqual (0, r1.Neighbors.Count);
r1.AddNeighbor (r2);
Assert.AreEqual (1, r1.Neighbors.Count);
Assert.IsFalse (r1.IsBorderRegion ());
r1.AddNeighbor (r3);
Assert.AreEqual (2, r1.Neighbors.Count);
Assert.IsTrue (r1.IsBorderRegion ());
Assert.AreEqual (1, c1.BorderRegions.Count);
}
}
}
| apache-2.0 | C# |
dd5338502635e95afc7adadc4bc00e13d935f32f | Fix crash when switching maps | ethanmoffat/EndlessClient | EndlessClient/Rendering/NPC/NPCAnimationActions.cs | EndlessClient/Rendering/NPC/NPCAnimationActions.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using EndlessClient.ControlSets;
using EndlessClient.HUD.Controls;
using EOLib.Domain.Notifiers;
namespace EndlessClient.Rendering.NPC
{
public class NPCAnimationActions : INPCAnimationNotifier
{
private readonly IHudControlProvider _hudControlProvider;
private readonly INPCStateCache _npcStateCache;
private readonly INPCRendererRepository _npcRendererRepository;
public NPCAnimationActions(IHudControlProvider hudControlProvider,
INPCStateCache npcStateCache,
INPCRendererRepository npcRendererRepository)
{
_hudControlProvider = hudControlProvider;
_npcStateCache = npcStateCache;
_npcRendererRepository = npcRendererRepository;
}
public void StartNPCWalkAnimation(int npcIndex)
{
if (!_hudControlProvider.IsInGame)
return;
var npcAnimator = _hudControlProvider.GetComponent<INPCAnimator>(HudControlIdentifier.NPCAnimator);
npcAnimator.StartWalkAnimation(npcIndex);
}
public void RemoveNPCFromView(int npcIndex, bool showDeathAnimation)
{
//possible that the server might send a packet for the npc to be removed by the map switch is completed
if (!_hudControlProvider.IsInGame || !_npcRendererRepository.NPCRenderers.ContainsKey(npcIndex))
return;
_npcStateCache.RemoveStateByIndex(npcIndex);
if (!showDeathAnimation)
{
_npcRendererRepository.NPCRenderers[npcIndex].Dispose();
_npcRendererRepository.NPCRenderers.Remove(npcIndex);
}
else
{
_npcRendererRepository.NPCRenderers[npcIndex].StartDying();
}
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using EndlessClient.ControlSets;
using EndlessClient.HUD.Controls;
using EOLib.Domain.Notifiers;
namespace EndlessClient.Rendering.NPC
{
public class NPCAnimationActions : INPCAnimationNotifier
{
private readonly IHudControlProvider _hudControlProvider;
private readonly INPCStateCache _npcStateCache;
private readonly INPCRendererRepository _npcRendererRepository;
public NPCAnimationActions(IHudControlProvider hudControlProvider,
INPCStateCache npcStateCache,
INPCRendererRepository npcRendererRepository)
{
_hudControlProvider = hudControlProvider;
_npcStateCache = npcStateCache;
_npcRendererRepository = npcRendererRepository;
}
public void StartNPCWalkAnimation(int npcIndex)
{
if (!_hudControlProvider.IsInGame)
return;
var npcAnimator = _hudControlProvider.GetComponent<INPCAnimator>(HudControlIdentifier.NPCAnimator);
npcAnimator.StartWalkAnimation(npcIndex);
}
public void RemoveNPCFromView(int npcIndex, bool showDeathAnimation)
{
if (!_hudControlProvider.IsInGame)
return;
_npcStateCache.RemoveStateByIndex(npcIndex);
if (!showDeathAnimation)
{
_npcRendererRepository.NPCRenderers[npcIndex].Dispose();
_npcRendererRepository.NPCRenderers.Remove(npcIndex);
}
else
{
_npcRendererRepository.NPCRenderers[npcIndex].StartDying();
}
}
}
}
| mit | C# |
f8752580480a62671fa32489464e6c2ec7d95d2c | fix #1152: ошибка отладчика на точках останова после Выполнить()/Вычислить() | EvilBeaver/OneScript,EvilBeaver/OneScript,EvilBeaver/OneScript,EvilBeaver/OneScript,EvilBeaver/OneScript | src/VSCode.DebugAdapter/ProtocolExtensions.cs | src/VSCode.DebugAdapter/ProtocolExtensions.cs | /*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using VSCodeDebug;
using StackFrame = OneScript.DebugProtocol.StackFrame;
namespace VSCode.DebugAdapter
{
public static class ProtocolExtensions
{
private static readonly char[] specialChars = new char[] { '<', '>' };
public static bool IsStringModule(this StackFrame frame)
{
return frame.Source.IndexOfAny(specialChars) != -1;
}
public static Source GetSource(this StackFrame frame)
{
if (frame.IsStringModule())
{
return new Source(frame.Source, null)
{
origin = frame.Source,
presentationHint = "deemphasize"
};
}
return new Source(frame.Source);
}
}
} | /*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using VSCodeDebug;
using StackFrame = OneScript.DebugProtocol.StackFrame;
namespace VSCode.DebugAdapter
{
public static class ProtocolExtensions
{
public static bool IsStringModule(this StackFrame frame)
{
return frame.Source == "<string>";
}
public static Source GetSource(this StackFrame frame)
{
if (frame.IsStringModule())
{
return new Source(frame.Source, null)
{
origin = frame.Source,
presentationHint = "deemphasize"
};
}
return new Source(frame.Source);
}
}
} | mpl-2.0 | C# |
2e80e2be5146f0f7d54c476d6c9530b2f7abf96d | Reword epilepsy warning description text | peppy/osu,peppy/osu-new,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Screens/Edit/Setup/DesignSection.cs | osu.Game/Screens/Edit/Setup/DesignSection.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Setup
{
internal class DesignSection : SetupSection
{
private LabelledSwitchButton widescreenSupport;
private LabelledSwitchButton epilepsyWarning;
private LabelledSwitchButton letterboxDuringBreaks;
public override LocalisableString Title => "Design";
[BackgroundDependencyLoader]
private void load()
{
Children = new[]
{
widescreenSupport = new LabelledSwitchButton
{
Label = "Widescreen support",
Current = { Value = Beatmap.BeatmapInfo.WidescreenStoryboard }
},
epilepsyWarning = new LabelledSwitchButton
{
Label = "Epilepsy warning",
Description = "Recommended if the storyboard contains scenes with rapidly flashing colours.",
Current = { Value = Beatmap.BeatmapInfo.EpilepsyWarning }
},
letterboxDuringBreaks = new LabelledSwitchButton
{
Label = "Letterbox during breaks",
Current = { Value = Beatmap.BeatmapInfo.LetterboxInBreaks }
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
widescreenSupport.Current.BindValueChanged(_ => updateBeatmap());
epilepsyWarning.Current.BindValueChanged(_ => updateBeatmap());
letterboxDuringBreaks.Current.BindValueChanged(_ => updateBeatmap());
}
private void updateBeatmap()
{
Beatmap.BeatmapInfo.WidescreenStoryboard = widescreenSupport.Current.Value;
Beatmap.BeatmapInfo.EpilepsyWarning = epilepsyWarning.Current.Value;
Beatmap.BeatmapInfo.LetterboxInBreaks = letterboxDuringBreaks.Current.Value;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Setup
{
internal class DesignSection : SetupSection
{
private LabelledSwitchButton widescreenSupport;
private LabelledSwitchButton epilepsyWarning;
private LabelledSwitchButton letterboxDuringBreaks;
public override LocalisableString Title => "Design";
[BackgroundDependencyLoader]
private void load()
{
Children = new[]
{
widescreenSupport = new LabelledSwitchButton
{
Label = "Widescreen support",
Current = { Value = Beatmap.BeatmapInfo.WidescreenStoryboard }
},
epilepsyWarning = new LabelledSwitchButton
{
Label = "Epilepsy warning",
Description = "Setting this is recommended if the storyboard contains scenes with rapidly flashing colours.",
Current = { Value = Beatmap.BeatmapInfo.EpilepsyWarning }
},
letterboxDuringBreaks = new LabelledSwitchButton
{
Label = "Letterbox during breaks",
Current = { Value = Beatmap.BeatmapInfo.LetterboxInBreaks }
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
widescreenSupport.Current.BindValueChanged(_ => updateBeatmap());
epilepsyWarning.Current.BindValueChanged(_ => updateBeatmap());
letterboxDuringBreaks.Current.BindValueChanged(_ => updateBeatmap());
}
private void updateBeatmap()
{
Beatmap.BeatmapInfo.WidescreenStoryboard = widescreenSupport.Current.Value;
Beatmap.BeatmapInfo.EpilepsyWarning = epilepsyWarning.Current.Value;
Beatmap.BeatmapInfo.LetterboxInBreaks = letterboxDuringBreaks.Current.Value;
}
}
}
| mit | C# |
d1272271951c90811f2e07655f4e32189f5a039d | Put in TODO item. | modulexcite/DebuggerStepThroughRemover,tiesmaster/DebuggerStepThroughRemover | DebuggerStepThroughRemover/DebuggerStepThroughRemover.Test/TestData.cs | DebuggerStepThroughRemover/DebuggerStepThroughRemover.Test/TestData.cs | namespace DebuggerStepThroughRemover.Test
{
public class TestData
{
public string Description { private get; set; }
public string BrokenSource { get; set; }
public string ExpectedFixedSource { get; set; }
// TODO: maybe replace these two props with some higher level construct
// from Rosly itself (maybe Microsoft.CodeAnalysis.Text.LinePosition?)
public int Line { get; set; }
public int Column { get; set; }
public override string ToString()
{
return Description;
}
}
} | namespace DebuggerStepThroughRemover.Test
{
public class TestData
{
public string Description { private get; set; }
public string BrokenSource { get; set; }
public string ExpectedFixedSource { get; set; }
public int Line { get; set; }
public int Column { get; set; }
public override string ToString()
{
return Description;
}
}
} | mit | C# |
2391c1d95dc06d283d0ece53b5c3d996dc52ffc9 | adjust minimum versions to align with SMAPI 1.1 | Pathoschild/StardewMods | ChestsAnywhere/Framework/Constants.cs | ChestsAnywhere/Framework/Constants.cs | using StardewValley;
namespace Pathoschild.Stardew.ChestsAnywhere.Framework
{
/// <summary>Constant mod values.</summary>
internal static class Constant
{
/*********
** Accessors
*********/
/// <summary>The minimum supported version of Stardew Valley.</summary>
public const string MinimumGameVersion = "1.1";
/// <summary>The minimum supported version of SMAPI.</summary>
public const string MinimumApiVersion = "1.1";
/// <summary>The number of rows in an inventory grid.</summary>
public const int SlotRows = 3;
/// <summary>The number of columns in an inventory grid.</summary>
public const int SlotColumns = 12;
/// <summary>The maximum number of elements in an inventory.</summary>
public const int SlotCount = Constant.SlotRows * Constant.SlotColumns;
/// <summary>The inventory slot size for the current zoom level.</summary>
public static int SlotSize => Game1.tileSize;
}
}
| using StardewValley;
namespace Pathoschild.Stardew.ChestsAnywhere.Framework
{
/// <summary>Constant mod values.</summary>
internal static class Constant
{
/*********
** Accessors
*********/
/// <summary>The minimum supported version of Stardew Valley.</summary>
public const string MinimumGameVersion = "1.11";
/// <summary>The minimum supported version of SMAPI.</summary>
public const string MinimumApiVersion = "0.40 1.1";
/// <summary>The number of rows in an inventory grid.</summary>
public const int SlotRows = 3;
/// <summary>The number of columns in an inventory grid.</summary>
public const int SlotColumns = 12;
/// <summary>The maximum number of elements in an inventory.</summary>
public const int SlotCount = Constant.SlotRows * Constant.SlotColumns;
/// <summary>The inventory slot size for the current zoom level.</summary>
public static int SlotSize => Game1.tileSize;
}
}
| mit | C# |
59a432ff40841a4880438d876d498adebd9c762d | Remove unused variable | geosharath/xenadmin,stephen-turner/xenadmin,cheng-z/xenadmin,MihaelaStoica/xenadmin,Frezzle/xenadmin,kc284/xenadmin,MihaelaStoica/xenadmin,minli1/xenadmin,MihaelaStoica/xenadmin,cheng-z/xenadmin,agimofcarmen/xenadmin,xenserver/xenadmin,GaborApatiNagy/xenadmin,cheng--zhang/xenadmin,cheng--zhang/xenadmin,kc284/xenadmin,robhoes/xenadmin,MihaelaStoica/xenadmin,GaborApatiNagy/xenadmin,cheng-z/xenadmin,huizh/xenadmin,agimofcarmen/xenadmin,cheng--zhang/xenadmin,minli1/xenadmin,ushamandya/xenadmin,cheng--zhang/xenadmin,jijiang/xenadmin,cheng-z/xenadmin,huizh/xenadmin,Frezzle/xenadmin,agimofcarmen/xenadmin,geosharath/xenadmin,qlw/xenadmin,ushamandya/xenadmin,jijiang/xenadmin,ushamandya/xenadmin,ushamandya/xenadmin,geosharath/xenadmin,jijiang/xenadmin,Frezzle/xenadmin,cheng--zhang/xenadmin,jijiang/xenadmin,robhoes/xenadmin,ushamandya/xenadmin,kc284/xenadmin,MihaelaStoica/xenadmin,robhoes/xenadmin,qlw/xenadmin,GaborApatiNagy/xenadmin,GaborApatiNagy/xenadmin,letsboogey/xenadmin,qlw/xenadmin,huizh/xenadmin,cheng-z/xenadmin,letsboogey/xenadmin,ushamandya/xenadmin,stephen-turner/xenadmin,Frezzle/xenadmin,letsboogey/xenadmin,huizh/xenadmin,letsboogey/xenadmin,minli1/xenadmin,xenserver/xenadmin,minli1/xenadmin,robhoes/xenadmin,jijiang/xenadmin,stephen-turner/xenadmin,kc284/xenadmin,cheng--zhang/xenadmin,xenserver/xenadmin,jijiang/xenadmin,qlw/xenadmin,Frezzle/xenadmin,geosharath/xenadmin,minli1/xenadmin,robhoes/xenadmin,stephen-turner/xenadmin,kc284/xenadmin,letsboogey/xenadmin,minli1/xenadmin,geosharath/xenadmin,geosharath/xenadmin,cheng-z/xenadmin,agimofcarmen/xenadmin,qlw/xenadmin,agimofcarmen/xenadmin,robhoes/xenadmin,stephen-turner/xenadmin,GaborApatiNagy/xenadmin,huizh/xenadmin,stephen-turner/xenadmin,huizh/xenadmin,GaborApatiNagy/xenadmin,Frezzle/xenadmin,letsboogey/xenadmin,MihaelaStoica/xenadmin | XenModel/Actions/Pool/SetSslLegacyAction.cs | XenModel/Actions/Pool/SetSslLegacyAction.cs | /* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Core;
using XenAPI;
namespace XenAdmin.Actions
{
public class SetSslLegacyAction: PureAsyncAction
{
bool legacyMode;
public SetSslLegacyAction(Pool pool, bool legacyMode)
: base(pool.Connection, Messages.SETTING_SECURITY_SETTINGS)
{
this.Pool = pool;
this.legacyMode = legacyMode;
}
protected override void Run()
{
Pool.Connection.ExpectDisruption = true;
if (legacyMode)
RelatedTask = Pool.async_enable_ssl_legacy(this.Session, Pool.opaque_ref);
else
RelatedTask = Pool.async_disable_ssl_legacy(this.Session, Pool.opaque_ref);
PollToCompletion();
}
protected override void Clean()
{
Pool.Connection.ExpectDisruption = false;
}
}
}
| /* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Core;
using XenAPI;
namespace XenAdmin.Actions
{
public class SetSslLegacyAction: PureAsyncAction
{
bool legacyMode;
private bool p;
public SetSslLegacyAction(Pool pool, bool legacyMode)
: base(pool.Connection, Messages.SETTING_SECURITY_SETTINGS)
{
this.Pool = pool;
this.legacyMode = legacyMode;
}
protected override void Run()
{
Pool.Connection.ExpectDisruption = true;
if (legacyMode)
RelatedTask = Pool.async_enable_ssl_legacy(this.Session, Pool.opaque_ref);
else
RelatedTask = Pool.async_disable_ssl_legacy(this.Session, Pool.opaque_ref);
PollToCompletion();
}
protected override void Clean()
{
Pool.Connection.ExpectDisruption = false;
}
}
}
| bsd-2-clause | C# |
105b58c471ec4b48e391f4034293a35da62e914f | Update copyright notice | markembling/MarkEmbling.PostcodesIO | MarkEmbling.PostcodesIO/Properties/AssemblyInfo.cs | MarkEmbling.PostcodesIO/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("MarkEmbling.PostcodesIO")]
[assembly: AssemblyDescription("Library for interacting with the excellent Postcodes.io service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.PostcodesIO")]
[assembly: AssemblyCopyright("Copyright © Mark Embling & contributors 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a31ab2d0-733e-4d9e-9e5f-fab2b40dc02e")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.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("MarkEmbling.PostcodesIO")]
[assembly: AssemblyDescription("Library for interacting with the excellent Postcodes.io service.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.PostcodesIO")]
[assembly: AssemblyCopyright("Copyright © Mark Embling 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("a31ab2d0-733e-4d9e-9e5f-fab2b40dc02e")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
| mit | C# |
f1dd3e4b9de439141e44ab62ad93e4c67640770a | check paths with OrdinalIgnoreCase in PackageIconConverter | campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer | PackageExplorer/Converters/PackageIconConverter.cs | PackageExplorer/Converters/PackageIconConverter.cs | using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;
namespace PackageExplorer
{
public class PackageIconConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
{
var metadata = package.PackageMetadata;
if (!string.IsNullOrEmpty(metadata.Icon))
{
foreach (var file in package.RootFolder.GetFiles())
{
if (string.Equals(file.Path, metadata.Icon, StringComparison.OrdinalIgnoreCase))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = file.GetStream();
image.EndInit();
return image;
}
}
}
if (metadata.IconUrl != null)
{
var image = new BitmapImage();
image.BeginInit();
image.UriSource = metadata.IconUrl;
image.EndInit();
return image;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
| using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;
namespace PackageExplorer
{
public class PackageIconConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
{
var metadata = package.PackageMetadata;
if (!string.IsNullOrEmpty(metadata.Icon))
{
foreach (var file in package.RootFolder.GetFiles())
{
if (file.Path == metadata.Icon)
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = file.GetStream();
image.EndInit();
return image;
}
}
}
if (metadata.IconUrl != null)
{
var image = new BitmapImage();
image.BeginInit();
image.UriSource = metadata.IconUrl;
image.EndInit();
return image;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
| mit | C# |
6e60aa17dc6be66b1c8b93c4dcc67db67cef5a7d | Fix for issue U4-5364 without trying to fix the localization of the error text. | KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,rajendra1809/Umbraco-CMS,leekelleher/Umbraco-CMS,qizhiyu/Umbraco-CMS,abjerner/Umbraco-CMS,jchurchley/Umbraco-CMS,abryukhov/Umbraco-CMS,rajendra1809/Umbraco-CMS,timothyleerussell/Umbraco-CMS,hfloyd/Umbraco-CMS,gregoriusxu/Umbraco-CMS,neilgaietto/Umbraco-CMS,lars-erik/Umbraco-CMS,Spijkerboer/Umbraco-CMS,kasperhhk/Umbraco-CMS,rustyswayne/Umbraco-CMS,m0wo/Umbraco-CMS,sargin48/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,VDBBjorn/Umbraco-CMS,VDBBjorn/Umbraco-CMS,VDBBjorn/Umbraco-CMS,mstodd/Umbraco-CMS,gkonings/Umbraco-CMS,neilgaietto/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,rajendra1809/Umbraco-CMS,markoliver288/Umbraco-CMS,markoliver288/Umbraco-CMS,corsjune/Umbraco-CMS,bjarnef/Umbraco-CMS,Spijkerboer/Umbraco-CMS,lars-erik/Umbraco-CMS,engern/Umbraco-CMS,DaveGreasley/Umbraco-CMS,markoliver288/Umbraco-CMS,rasmuseeg/Umbraco-CMS,christopherbauer/Umbraco-CMS,rasmuseeg/Umbraco-CMS,AzarinSergey/Umbraco-CMS,corsjune/Umbraco-CMS,ehornbostel/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,madsoulswe/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,abjerner/Umbraco-CMS,Tronhus/Umbraco-CMS,VDBBjorn/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,gregoriusxu/Umbraco-CMS,markoliver288/Umbraco-CMS,TimoPerplex/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,corsjune/Umbraco-CMS,jchurchley/Umbraco-CMS,ehornbostel/Umbraco-CMS,aadfPT/Umbraco-CMS,hfloyd/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,mittonp/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,WebCentrum/Umbraco-CMS,gkonings/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,AzarinSergey/Umbraco-CMS,arknu/Umbraco-CMS,TimoPerplex/Umbraco-CMS,mattbrailsford/Umbraco-CMS,Phosworks/Umbraco-CMS,aaronpowell/Umbraco-CMS,kgiszewski/Umbraco-CMS,tcmorris/Umbraco-CMS,timothyleerussell/Umbraco-CMS,ehornbostel/Umbraco-CMS,abjerner/Umbraco-CMS,base33/Umbraco-CMS,gavinfaux/Umbraco-CMS,arknu/Umbraco-CMS,mittonp/Umbraco-CMS,Khamull/Umbraco-CMS,ordepdev/Umbraco-CMS,timothyleerussell/Umbraco-CMS,sargin48/Umbraco-CMS,gkonings/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,Tronhus/Umbraco-CMS,nvisage-gf/Umbraco-CMS,qizhiyu/Umbraco-CMS,lars-erik/Umbraco-CMS,DaveGreasley/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,m0wo/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmusfjord/Umbraco-CMS,rustyswayne/Umbraco-CMS,lingxyd/Umbraco-CMS,mstodd/Umbraco-CMS,gavinfaux/Umbraco-CMS,DaveGreasley/Umbraco-CMS,gavinfaux/Umbraco-CMS,leekelleher/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,bjarnef/Umbraco-CMS,qizhiyu/Umbraco-CMS,bjarnef/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,rasmusfjord/Umbraco-CMS,gregoriusxu/Umbraco-CMS,gkonings/Umbraco-CMS,rustyswayne/Umbraco-CMS,corsjune/Umbraco-CMS,lingxyd/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,iahdevelop/Umbraco-CMS,sargin48/Umbraco-CMS,rustyswayne/Umbraco-CMS,kgiszewski/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,markoliver288/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,engern/Umbraco-CMS,iahdevelop/Umbraco-CMS,marcemarc/Umbraco-CMS,christopherbauer/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,iahdevelop/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,arknu/Umbraco-CMS,AzarinSergey/Umbraco-CMS,tompipe/Umbraco-CMS,gregoriusxu/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,nvisage-gf/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,romanlytvyn/Umbraco-CMS,nvisage-gf/Umbraco-CMS,Khamull/Umbraco-CMS,WebCentrum/Umbraco-CMS,umbraco/Umbraco-CMS,lingxyd/Umbraco-CMS,ordepdev/Umbraco-CMS,christopherbauer/Umbraco-CMS,qizhiyu/Umbraco-CMS,engern/Umbraco-CMS,aaronpowell/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,kasperhhk/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,robertjf/Umbraco-CMS,engern/Umbraco-CMS,romanlytvyn/Umbraco-CMS,tompipe/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,iahdevelop/Umbraco-CMS,aaronpowell/Umbraco-CMS,romanlytvyn/Umbraco-CMS,romanlytvyn/Umbraco-CMS,robertjf/Umbraco-CMS,Phosworks/Umbraco-CMS,tcmorris/Umbraco-CMS,DaveGreasley/Umbraco-CMS,m0wo/Umbraco-CMS,ehornbostel/Umbraco-CMS,sargin48/Umbraco-CMS,timothyleerussell/Umbraco-CMS,Pyuuma/Umbraco-CMS,KevinJump/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,jchurchley/Umbraco-CMS,tcmorris/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,mstodd/Umbraco-CMS,nvisage-gf/Umbraco-CMS,Khamull/Umbraco-CMS,Tronhus/Umbraco-CMS,base33/Umbraco-CMS,mittonp/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,timothyleerussell/Umbraco-CMS,neilgaietto/Umbraco-CMS,abryukhov/Umbraco-CMS,mstodd/Umbraco-CMS,christopherbauer/Umbraco-CMS,bjarnef/Umbraco-CMS,Khamull/Umbraco-CMS,Khamull/Umbraco-CMS,christopherbauer/Umbraco-CMS,marcemarc/Umbraco-CMS,lingxyd/Umbraco-CMS,hfloyd/Umbraco-CMS,Phosworks/Umbraco-CMS,AzarinSergey/Umbraco-CMS,Phosworks/Umbraco-CMS,mittonp/Umbraco-CMS,leekelleher/Umbraco-CMS,m0wo/Umbraco-CMS,rasmusfjord/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,m0wo/Umbraco-CMS,neilgaietto/Umbraco-CMS,abryukhov/Umbraco-CMS,kasperhhk/Umbraco-CMS,lingxyd/Umbraco-CMS,Spijkerboer/Umbraco-CMS,mstodd/Umbraco-CMS,neilgaietto/Umbraco-CMS,kgiszewski/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,romanlytvyn/Umbraco-CMS,tompipe/Umbraco-CMS,madsoulswe/Umbraco-CMS,gavinfaux/Umbraco-CMS,TimoPerplex/Umbraco-CMS,TimoPerplex/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,abryukhov/Umbraco-CMS,ehornbostel/Umbraco-CMS,kasperhhk/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,Pyuuma/Umbraco-CMS,VDBBjorn/Umbraco-CMS,Pyuuma/Umbraco-CMS,Pyuuma/Umbraco-CMS,robertjf/Umbraco-CMS,rasmusfjord/Umbraco-CMS,Pyuuma/Umbraco-CMS,NikRimington/Umbraco-CMS,rajendra1809/Umbraco-CMS,markoliver288/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,gregoriusxu/Umbraco-CMS,rustyswayne/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,Spijkerboer/Umbraco-CMS,TimoPerplex/Umbraco-CMS,gavinfaux/Umbraco-CMS,madsoulswe/Umbraco-CMS,aadfPT/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,Tronhus/Umbraco-CMS,aadfPT/Umbraco-CMS,tcmorris/Umbraco-CMS,DaveGreasley/Umbraco-CMS,nvisage-gf/Umbraco-CMS,kasperhhk/Umbraco-CMS,base33/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,ordepdev/Umbraco-CMS,engern/Umbraco-CMS,mittonp/Umbraco-CMS,rajendra1809/Umbraco-CMS,iahdevelop/Umbraco-CMS,ordepdev/Umbraco-CMS,lars-erik/Umbraco-CMS,corsjune/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,ordepdev/Umbraco-CMS,sargin48/Umbraco-CMS,Tronhus/Umbraco-CMS,qizhiyu/Umbraco-CMS,gkonings/Umbraco-CMS,Phosworks/Umbraco-CMS,rasmusfjord/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,AzarinSergey/Umbraco-CMS | src/Umbraco.Core/PropertyEditors/EmailValidator.cs | src/Umbraco.Core/PropertyEditors/EmailValidator.cs | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Umbraco.Core.Models;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// A validator that validates an email address
/// </summary>
[ValueValidator("Email")]
internal sealed class EmailValidator : ManifestValueValidator, IPropertyValidator
{
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
{
var asString = value.ToString();
var emailVal = new EmailAddressAttribute();
if (asString != string.Empty && emailVal.IsValid(asString) == false)
{
// TODO: localize these!
yield return new ValidationResult("Email is invalid", new[] { "value" });
}
}
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
{
return this.Validate(value, null, preValues, editor);
}
}
} | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Umbraco.Core.Models;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// A validator that validates an email address
/// </summary>
[ValueValidator("Email")]
internal sealed class EmailValidator : ManifestValueValidator, IPropertyValidator
{
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
{
var asString = value.ToString();
var emailVal = new EmailAddressAttribute();
if (emailVal.IsValid(asString) == false)
{
//TODO: localize these!
yield return new ValidationResult("Email is invalid", new[] { "value" });
}
}
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
{
return Validate(value, null, preValues, editor);
}
}
} | mit | C# |
d3f487c6d73f86cc2f55cf20284d808d1e2d47ce | Clean up SimpleServer class. | mattleibow/RestSharp,benfo/RestSharp,uQr/RestSharp,fmmendo/RestSharp,restsharp/RestSharp,dyh333/RestSharp,who/RestSharp,wparad/RestSharp,rucila/RestSharp,kouweizhong/RestSharp,huoxudong125/RestSharp,mwereda/RestSharp,KraigM/RestSharp,amccarter/RestSharp,periface/RestSharp,lydonchandra/RestSharp,mattwalden/RestSharp,dmgandini/RestSharp,haithemaraissia/RestSharp,RestSharp-resurrected/RestSharp,eamonwoortman/RestSharp.Unity,SaltyDH/RestSharp,dgreenbean/RestSharp,felipegtx/RestSharp,PKRoma/RestSharp,wparad/RestSharp,cnascimento/RestSharp,chengxiaole/RestSharp,rivy/RestSharp,jiangzm/RestSharp | RestSharp.IntegrationTests/Helpers/SimpleServer.cs | RestSharp.IntegrationTests/Helpers/SimpleServer.cs | namespace RestSharp.IntegrationTests.Helpers
{
using System;
using System.Net;
using System.Threading;
public class SimpleServer : IDisposable
{
private readonly HttpListener listener;
private readonly Action<HttpListenerContext> handler;
private Thread processor;
public static SimpleServer Create(
string url,
Action<HttpListenerContext> handler,
AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous)
{
var listener = new HttpListener { Prefixes = { url }, AuthenticationSchemes = authenticationSchemes };
var server = new SimpleServer(listener, handler);
server.Start();
return server;
}
private SimpleServer(HttpListener listener, Action<HttpListenerContext> handler)
{
this.listener = listener;
this.handler = handler;
}
public void Start()
{
if (this.listener.IsListening)
{
return;
}
this.listener.Start();
this.processor = new Thread(() =>
{
var context = this.listener.GetContext();
this.handler(context);
context.Response.Close();
}) { Name = "WebServer" };
this.processor.Start();
}
public void Dispose()
{
this.processor.Abort();
this.listener.Stop();
this.listener.Close();
}
}
}
| using System;
using System.Net;
using System.Threading;
namespace RestSharp.IntegrationTests.Helpers
{
public class SimpleServer : IDisposable
{
private readonly HttpListener _listener;
private readonly Action<HttpListenerContext> _handler;
private Thread _processor;
public static SimpleServer Create(string url, Action<HttpListenerContext> handler,
AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous)
{
var listener = new HttpListener
{
Prefixes = {url},
AuthenticationSchemes = authenticationSchemes
};
var server = new SimpleServer(listener, handler);
server.Start();
return server;
}
private SimpleServer(HttpListener listener, Action<HttpListenerContext> handler)
{
_listener = listener;
_handler = handler;
}
public void Start()
{
if (!_listener.IsListening)
{
_listener.Start();
_processor = new Thread(() =>
{
var context = _listener.GetContext();
_handler(context);
context.Response.Close();
}) {Name = "WebServer"};
_processor.Start();
}
}
public void Dispose()
{
_processor.Abort();
_listener.Stop();
_listener.Close();
}
}
}
| apache-2.0 | C# |
537cc53eca44647fa8e916f0b000e19b404e8518 | Add Commands repo to unit of work | MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings | DynThings.Data.Repositories/Core/UnitOfWork.cs | DynThings.Data.Repositories/Core/UnitOfWork.cs | /////////////////////////////////////////////////////////////////
// Created by : Caesar Moussalli //
// TimeStamp : 31-1-2016 //
// Content : Associate Repositories to the Unit of Work //
// Notes : Send DB context to repositories to reduce DB //
// connectivity sessions count //
/////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DynThings.Data.Models;
namespace DynThings.Data.Repositories
{
public static class UnitOfWork
{
#region Repositories
public static LocationViewsRepository repoLocationViews = new LocationViewsRepository();
public static LocationViewTypesRepository repoLocationViewTypes = new LocationViewTypesRepository();
public static LocationsRepository repoLocations = new LocationsRepository();
public static EndpointsRepository repoEndpoints = new EndpointsRepository();
public static EndpointIOsRepository repoEndpointIOs = new EndpointIOsRepository();
public static EndPointTypesRepository repoEndpointTypes = new EndPointTypesRepository();
public static DevicesRepositories repoDevices = new DevicesRepositories();
public static CommandsRepository repoEndPointCommands = new CommandsRepository();
#endregion
#region Enums
public enum RepositoryMethodResultType
{
Ok = 1,
Failed = 2
}
#endregion
}
}
| /////////////////////////////////////////////////////////////////
// Created by : Caesar Moussalli //
// TimeStamp : 31-1-2016 //
// Content : Associate Repositories to the Unit of Work //
// Notes : Send DB context to repositories to reduce DB //
// connectivity sessions count //
/////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DynThings.Data.Models;
namespace DynThings.Data.Repositories
{
public static class UnitOfWork
{
#region Repositories
public static LocationViewsRepository repoLocationViews = new LocationViewsRepository();
public static LocationViewTypesRepository repoLocationViewTypes = new LocationViewTypesRepository();
public static LocationsRepository repoLocations = new LocationsRepository();
public static EndpointsRepository repoEndpoints = new EndpointsRepository();
public static EndpointIOsRepository repoEndpointIOs = new EndpointIOsRepository();
public static EndPointTypesRepository repoEndpointTypes = new EndPointTypesRepository();
public static DevicesRepositories repoDevices = new DevicesRepositories();
public static EndPointCommandsRepository repoEndPointCommands = new EndPointCommandsRepository();
#endregion
#region Enums
public enum RepositoryMethodResultType
{
Ok = 1,
Failed = 2
}
#endregion
}
}
| mit | C# |
4978c41eaf65cc5fe2cb560413eae9301f24a870 | Remove unecessary entity | alfredosegundo/BudgetMVC,alfredosegundo/BudgetMVC | BudgetMVC.ConsoleTest/Program.cs | BudgetMVC.ConsoleTest/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BudgetMVC.Model.EntityFramework;
using BudgetMVC.Model.Entity;
using BudgetMVC.Model.Entity.Enum;
namespace BudgetMVC.ConsoleTest
{
class Program
{
static void Main(string[] args)
{
using (var db = new BudgetContext())
{
db.Expenses.Add(new Expense { Description = DateTime.Now.ToLongDateString(), Value = DateTime.Now.Second * 0.38 });
db.SaveChanges();
var query = from expense in db.Expenses
orderby expense.CreationDate
select expense;
Console.WriteLine("Database: " + db.Database.Connection.ConnectionString);
Console.WriteLine("All expenses in the database:");
foreach (var item in query)
{
Console.WriteLine("Date: " + item.CreationDate);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BudgetMVC.Model.EntityFramework;
using BudgetMVC.Model.Entity;
using BudgetMVC.Model.Entity.Enum;
namespace BudgetMVC.ConsoleTest
{
class Program
{
static void Main(string[] args)
{
using (var db = new BudgetContext())
{
db.PeriodicExpenses.Add(new PeriodicExpense
{
FirstEvent = DateTime.Today,
FinalEvent = DateTime.Today.AddDays(120),
Description = "Periodic Expense " + Guid.NewGuid().ToString(),
Periodicity = Periodicity.Monthly,
Value = DateTime.Now.Second * 1.97
});
db.Expenses.Add(new Expense { Description = DateTime.Now.ToLongDateString(), Value = DateTime.Now.Second * 0.38 });
db.SaveChanges();
var query = from expense in db.Expenses
orderby expense.CreationDate
select expense;
Console.WriteLine("Database: " + db.Database.Connection.ConnectionString);
Console.WriteLine("All expenses in the database:");
foreach (var item in query)
{
Console.WriteLine("Date: " + item.CreationDate);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
}
| mit | C# |
2d5ad5043b37e2d4610d02b73cb43ffe208ea17a | update version | gaochundong/Cowboy | SolutionVersion.cs | SolutionVersion.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("Cowboy is a library for building Sockets/HTTP based services.")]
[assembly: AssemblyCompany("Dennis Gao")]
[assembly: AssemblyProduct("Cowboy")]
[assembly: AssemblyCopyright("Copyright © 2015-2016 Dennis Gao.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.10.0")]
[assembly: AssemblyFileVersion("1.1.10.0")]
[assembly: ComVisible(false)]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("Cowboy is a library for building Sockets/HTTP based services.")]
[assembly: AssemblyCompany("Dennis Gao")]
[assembly: AssemblyProduct("Cowboy")]
[assembly: AssemblyCopyright("Copyright © 2015-2016 Dennis Gao.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.9.0")]
[assembly: AssemblyFileVersion("1.1.9.0")]
[assembly: ComVisible(false)]
| mit | C# |
9f98311adaed46346b11aa2d396b8e0087bf1997 | Add trace with some quotes | davidebbo-test/Mvc52Application,davidebbo-test/Mvc52Application,davidebbo-test/Mvc52Application | Mvc52Application/Controllers/HomeController.cs | Mvc52Application/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyCoolLib;
namespace Mvc52Application.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now);
Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now);
Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now);
Trace.TraceInformation("123"456\"789");
return View();
}
public ActionResult About()
{
ViewBag.Message = $"SayHello: {Hello.SayHello("David")}, Foo Appsetting: {ConfigurationManager.AppSettings["foo"]}";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyCoolLib;
namespace Mvc52Application.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now);
Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now);
Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now);
return View();
}
public ActionResult About()
{
ViewBag.Message = $"SayHello: {Hello.SayHello("David")}, Foo Appsetting: {ConfigurationManager.AppSettings["foo"]}";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | apache-2.0 | C# |
342c973021d5f7cfba29a730e3beee7875bc10a9 | Fix Change new value & original values dictionaries to object values instead of string | Charcoals/PivotalTracker.NET,Charcoals/PivotalTracker.NET | PivotalTrackerDotNet/Domain/Change.cs | PivotalTrackerDotNet/Domain/Change.cs | using System.Collections.Generic;
namespace PivotalTrackerDotNet.Domain
{
public class Change
{
public ResourceKind Kind { get; set; }
public ChangeType ChangeType { get; set; }
public int Id { get; set; }
public Dictionary<string, object> NewValues { get; set; }
public Dictionary<string, object> OriginalValues { get; set; }
public string Name { get; set; }
public StoryType StoryType { get; set; }
}
} | using System.Collections.Generic;
namespace PivotalTrackerDotNet.Domain
{
public class Change
{
public ResourceKind Kind { get; set; }
public ChangeType ChangeType { get; set; }
public int Id { get; set; }
public Dictionary<string, string> NewValues { get; set; }
public Dictionary<string, string> OriginalValues { get; set; }
public string Name { get; set; }
public StoryType StoryType { get; set; }
}
} | mit | C# |
dd7fc078ce6148007394351e2b31d4d23da546cc | Fix translation formatting. | PintaProject/Pinta,PintaProject/Pinta,PintaProject/Pinta | Pinta.Core/PaletteFormats/PaletteDescriptor.cs | Pinta.Core/PaletteFormats/PaletteDescriptor.cs | //
// PaletteDescriptor.cs
//
// Author:
// Matthias Mailänder
//
// Copyright (c) 2017 Matthias Mailänder
//
// 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 Gtk;
using System.Text;
namespace Pinta.Core
{
public sealed class PaletteDescriptor
{
public string[] Extensions { get; private set; }
public IPaletteLoader Loader { get; private set; }
public IPaletteSaver Saver { get; private set; }
public FileFilter Filter { get; private set; }
public PaletteDescriptor (string displayPrefix, string[] extensions, IPaletteLoader loader, IPaletteSaver saver)
{
if (extensions == null || (loader == null && saver == null)) {
throw new ArgumentNullException ("Palette descriptor is initialized incorrectly");
}
this.Extensions = extensions;
this.Loader = loader;
this.Saver = saver;
FileFilter ff = new FileFilter ();
StringBuilder formatNames = new StringBuilder ();
foreach (string ext in extensions) {
if (formatNames.Length > 0)
formatNames.Append (", ");
string wildcard = string.Format ("*.{0}", ext);
ff.AddPattern (wildcard);
formatNames.Append (wildcard);
}
ff.Name = Translations.GetString ("{0} palette ({1})", displayPrefix, formatNames);
this.Filter = ff;
}
public bool IsReadOnly ()
{
return Saver == null;
}
public bool IsWriteOnly ()
{
return Loader == null;
}
}
} | //
// PaletteDescriptor.cs
//
// Author:
// Matthias Mailänder
//
// Copyright (c) 2017 Matthias Mailänder
//
// 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 Gtk;
using System.Text;
namespace Pinta.Core
{
public sealed class PaletteDescriptor
{
public string[] Extensions { get; private set; }
public IPaletteLoader Loader { get; private set; }
public IPaletteSaver Saver { get; private set; }
public FileFilter Filter { get; private set; }
public PaletteDescriptor (string displayPrefix, string[] extensions, IPaletteLoader loader, IPaletteSaver saver)
{
if (extensions == null || (loader == null && saver == null)) {
throw new ArgumentNullException ("Palette descriptor is initialized incorrectly");
}
this.Extensions = extensions;
this.Loader = loader;
this.Saver = saver;
FileFilter ff = new FileFilter ();
StringBuilder formatNames = new StringBuilder ();
foreach (string ext in extensions) {
if (formatNames.Length > 0)
formatNames.Append (", ");
string wildcard = string.Format ("*.{0}", ext);
ff.AddPattern (wildcard);
formatNames.Append (wildcard);
}
ff.Name = string.Format (Translations.GetString ("{0} palette ({1})"), displayPrefix, formatNames);
this.Filter = ff;
}
public bool IsReadOnly ()
{
return Saver == null;
}
public bool IsWriteOnly ()
{
return Loader == null;
}
}
} | mit | C# |
bc0be409e69fe8c7d26780bd9fbb5898b3dfbb69 | Remove usage of FX_DEPS_FILE as a fallback for locating `dotnet`, since that can find the wrong result when a newer patch is installed to the global dotnet location than the one installed into the folder containing Process.MainModule. | fixie/fixie | src/Fixie.Cli/Dotnet.cs | src/Fixie.Cli/Dotnet.cs | #if !NET452
namespace Fixie.Cli
{
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
class Dotnet
{
public static readonly string Path = FindDotnet();
static string FindDotnet()
{
var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet";
//If `dotnet` is the currently running process, return the full path to that executable.
using (var currentProcess = Process.GetCurrentProcess())
{
var mainModule = currentProcess.MainModule;
var currentProcessIsDotNet =
!string.IsNullOrEmpty(mainModule?.FileName) &&
System.IO.Path.GetFileName(mainModule.FileName)
.Equals(fileName, StringComparison.OrdinalIgnoreCase);
if (currentProcessIsDotNet)
return mainModule.FileName;
throw new CommandLineException($"Failed to locate `dotnet`.");
}
}
}
}
#endif | #if !NET452
namespace Fixie.Cli
{
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
class Dotnet
{
public static readonly string Path = FindDotnet();
static string FindDotnet()
{
var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet";
//If `dotnet` is the currently running process, return the full path to that executable.
var mainModule = GetCurrentProcessMainModule();
var currentProcessIsDotNet =
!string.IsNullOrEmpty(mainModule?.FileName) &&
System.IO.Path.GetFileName(mainModule.FileName)
.Equals(fileName, StringComparison.OrdinalIgnoreCase);
if (currentProcessIsDotNet)
return mainModule.FileName;
// Find "dotnet" by using the location of the shared framework.
var fxDepsFile = AppContext.GetData("FX_DEPS_FILE") as string;
if (string.IsNullOrEmpty(fxDepsFile))
throw new CommandLineException("While attempting to locate `dotnet`, FX_DEPS_FILE could not be found in the AppContext.");
var dotnetDirectory =
new FileInfo(fxDepsFile) // Microsoft.NETCore.App.deps.json
.Directory? // (version)
.Parent? // Microsoft.NETCore.App
.Parent? // shared
.Parent; // DOTNET_HOME
if (dotnetDirectory == null)
throw new CommandLineException("While attempting to locate `dotnet`. Could not traverse directories from FX_DEPS_FILE to DOTNET_HOME.");
var dotnetPath = System.IO.Path.Combine(dotnetDirectory.FullName, fileName);
if (!File.Exists(dotnetPath))
throw new CommandLineException($"Failed to locate `dotnet`. The path does not exist: {dotnetPath}");
return dotnetPath;
}
static ProcessModule GetCurrentProcessMainModule()
{
using (var currentProcess = Process.GetCurrentProcess())
return currentProcess.MainModule;
}
}
}
#endif | mit | C# |
ec0d9fbbd0429c0ba49df3981cc3fab36615536e | Rewrite Play animation to only play animation once. | DerTraveler/into-the-thick-of-it | Assets/Script/Player.cs | Assets/Script/Player.cs | /* Copyright (c) 2016 Kevin Fischer
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 1.0f;
private Animator animator;
private SpriteRenderer spriteRenderer;
public enum State {
Idle,
Walking,
Attacking
}
[SerializeField]
private State state = State.Idle;
[SerializeField]
private string currentAnimation = "IdleDown";
[SerializeField]
private Vector2 moveDirection = new Vector2(0, 0);
[SerializeField]
private Vector2 faceDirection = new Vector2(0, -1);
[SerializeField]
private bool directionPressed = false;
void Start () {
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
ReadInput();
UpdateState();
PlayAnimation();
UpdateTransform();
}
private void ReadInput() {
moveDirection.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
directionPressed = moveDirection.sqrMagnitude > float.Epsilon;
if (Mathf.Approximately(moveDirection.sqrMagnitude, 1.0f)) {
faceDirection.Set(moveDirection.x, moveDirection.y);
}
}
private void UpdateState() {
switch(state) {
case State.Idle:
if (directionPressed) {
state = State.Walking;
}
break;
case State.Walking:
if (!directionPressed) {
state = State.Idle;
}
break;
}
}
private void PlayAnimation() {
// Flipping on X axis
spriteRenderer.flipX = Mathf.Approximately(faceDirection.x, -1.0f);
string nextAnimation = currentAnimation;
switch (state) {
case State.Idle:
nextAnimation = "Idle" + getDirectionName();
break;
case State.Walking:
nextAnimation = "Walk" + getDirectionName();
break;
}
if (nextAnimation != currentAnimation) {
currentAnimation = nextAnimation;
animator.Play(currentAnimation);
}
}
private string getDirectionName() {
if (faceDirection.y > 0) {
return "Up";
} else if (faceDirection.y < 0) {
return "Down";
} else {
return "Side";
}
}
private void UpdateTransform() {
if (state == State.Walking) {
Vector3 newPos = transform.position + (Vector3)(moveDirection * speed * Time.deltaTime);
transform.position = newPos;
}
}
}
| /* Copyright (c) 2016 Kevin Fischer
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 1.0f;
private Animator animator;
private SpriteRenderer spriteRenderer;
public enum State {
Idle,
Walking,
Attacking
}
[SerializeField]
private State state = State.Idle;
[SerializeField]
private Vector2 moveDirection = new Vector2(0, 0);
[SerializeField]
private Vector2 faceDirection = new Vector2(0, -1);
[SerializeField]
private bool directionPressed = false;
void Start () {
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
ReadInput();
UpdateState();
PlayAnimation();
UpdateTransform();
}
private void ReadInput() {
moveDirection.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
directionPressed = moveDirection.sqrMagnitude > float.Epsilon;
if (Mathf.Approximately(moveDirection.sqrMagnitude, 1.0f)) {
faceDirection.Set(moveDirection.x, moveDirection.y);
}
}
private void UpdateState() {
switch(state) {
case State.Idle:
if (directionPressed) {
state = State.Walking;
}
break;
case State.Walking:
if (!directionPressed) {
state = State.Idle;
}
break;
}
}
private void PlayAnimation() {
// Flipping on X axis
spriteRenderer.flipX = Mathf.Approximately(faceDirection.x, -1.0f);
switch (state) {
case State.Idle:
animator.Play("Idle" + getDirectionName());
break;
case State.Walking:
animator.Play("Walk" + getDirectionName());
break;
}
}
private string getDirectionName() {
if (faceDirection.y > 0) {
return "Up";
} else if (faceDirection.y < 0) {
return "Down";
} else {
return "Side";
}
}
private void UpdateTransform() {
if (state == State.Walking) {
Vector3 newPos = transform.position + (Vector3)(moveDirection * speed * Time.deltaTime);
transform.position = newPos;
}
}
}
| mpl-2.0 | C# |
5872975e102052d503ff85604d9c4435bbb70bc1 | Refactor Tower behavior | emazzotta/unity-tower-defense | Assets/Scripts/Tower.cs | Assets/Scripts/Tower.cs | using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
Transform towerTransform;
public float range = 10f;
public GameObject bulletPrefab;
public int cost = 5;
public int damage = 10;
public float radius = 0;
private MetallKefer nearestMetallKefer;
void Start () {
InvokeRepeating("AimAtTarget", 0, 0.5f);
this.nearestMetallKefer = null;
towerTransform = transform.Find("Tower");
}
void AimAtTarget() {
MetallKefer[] enemies = GameObject.FindObjectsOfType<MetallKefer>();
this.nearestMetallKefer = GetClosestEnemy(enemies);
if(nearestMetallKefer != null) {
if (nearestMetallKefer != null && nearestMetallKefer.GetHealth () > 0) {
ShootAt (nearestMetallKefer);
}
Vector3 lookRotation = nearestMetallKefer.transform.position - this.transform.position;
if (lookRotation != Vector3.zero) {
var targetRotation = Quaternion.LookRotation(lookRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
}
}
}
void ShootAt(MetallKefer metallKefer) {
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation);
bulletGO.transform.SetParent (this.transform);
Bullet b = bulletGO.GetComponent<Bullet>();
b.target = metallKefer;
b.damage = damage;
}
MetallKefer GetClosestEnemy(MetallKefer[] enemies) {
MetallKefer tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (MetallKefer enemy in enemies) {
float dist = Vector3.Distance(enemy.transform.position, currentPos);
if (dist < minDist) {
tMin = enemy;
minDist = dist;
}
}
return tMin;
}
}
| using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
Transform towerTransform;
public float range = 10f;
public GameObject bulletPrefab;
public int cost = 5;
public int damage = 10;
public float radius = 0;
private MetallKefer nearestMetallKefer;
void Start () {
InvokeRepeating("AimAtTarget", 0, 0.5f);
this.nearestMetallKefer = null;
towerTransform = transform.Find("Tower");
}
void AimAtTarget() {
MetallKefer[] enemies = GameObject.FindObjectsOfType<MetallKefer>();
this.nearestMetallKefer = GetClosestEnemy(enemies);
if(nearestMetallKefer == null) {
Debug.Log("No enemies?");
return;
}
if (nearestMetallKefer != null && nearestMetallKefer.GetHealth () > 0) {
ShootAt (nearestMetallKefer);
}
Vector3 lookRotation = nearestMetallKefer.transform.position - this.transform.position;
if (lookRotation != Vector3.zero) {
var targetRotation = Quaternion.LookRotation(lookRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
}
}
void ShootAt(MetallKefer metallKefer) {
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation);
bulletGO.transform.SetParent (this.transform);
Bullet b = bulletGO.GetComponent<Bullet>();
b.target = metallKefer;
b.damage = damage;
}
MetallKefer GetClosestEnemy(MetallKefer[] enemies) {
MetallKefer tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (MetallKefer enemy in enemies) {
float dist = Vector3.Distance(enemy.transform.position, currentPos);
if (dist < minDist) {
tMin = enemy;
minDist = dist;
}
}
return tMin;
}
}
| mit | C# |
6e89f37438d3d5220b709a8237fe1d83b1c7113f | Return to old container | Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog | SpaceBlog/SpaceBlog/Views/Article/Index.cshtml | SpaceBlog/SpaceBlog/Views/Article/Index.cshtml | @model IEnumerable<SpaceBlog.Models.Article>
@using SpaceBlog.Utilities;
@{
ViewBag.Title = "Articles";
}
<div class="container">
<h2>@ViewBag.Title</h2>
@Html.ActionLink("Create New Article", "Create", new { area = "" }, new { @class = "btn btn-primary" })
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Content)
</th>
<th>
@Html.DisplayNameFor(model => model.Date)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
Actions
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Utils.CutText(item.Content)
</td>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author.FullName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "btn-sm btn-primary" })
@Html.ActionLink("Details", "Details", new { id = item.Id }, new { @class = "btn-sm btn-primary" })
@Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "btn-sm btn-danger" })
</td>
</tr>
}
</table>
</div> | @model IEnumerable<SpaceBlog.Models.Article>
@using SpaceBlog.Utilities;
@{
ViewBag.Title = "Articles";
}
<div class="container-fluid">
<h2>@ViewBag.Title</h2>
@Html.ActionLink("Create New Article", "Create", new { area = "" }, new { @class = "btn btn-primary" })
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Content)
</th>
<th>
@Html.DisplayNameFor(model => model.Date)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
Actions
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Utils.CutText(item.Content)
</td>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author.FullName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "btn-sm btn-primary" })
@Html.ActionLink("Details", "Details", new { id = item.Id }, new { @class = "btn-sm btn-primary" })
@Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "btn-sm btn-danger" })
</td>
</tr>
}
</table>
</div> | mit | C# |
6bf22ca80d19bc4b79146aea7566d1cbac5e6bea | bump to 1.12.7 | Terradue/DotNetOpenSearch | Terradue.OpenSearch/Properties/AssemblyInfo.cs | Terradue.OpenSearch/Properties/AssemblyInfo.cs | /*
* Copyright (C) 2010-2014 Terradue S.r.l.
*
* This file is part of Terradue.OpenSearch.
*
* Foobar is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Terradue.OpenSearch.
* If not, see http://www.gnu.org/licenses/.
*/
/*!
\namespace Terradue.OpenSearch
@{
Terradue.OpenSearch is a .Net library that provides an engine perform OpenSearch query from a class or an URL to multiple and custom types of results
\xrefitem sw_version "Versions" "Software Package Version" 1.12.7
\xrefitem sw_link "Link" "Software Package Link" [DotNetOpenSearch](https://github.com/Terradue/DotNetOpenSearch)
\xrefitem sw_license "License" "Software License" [AGPL](https://github.com/DotNetOpenSearch/Terradue.OpenSearch/blob/master/LICENSE)
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Syndication
\ingroup OpenSearch
@}
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using NuGet4Mono.Extensions;
[assembly: AssemblyTitle("Terradue.OpenSearch")]
[assembly: AssemblyDescription("Terradue.OpenSearch is a library targeting .NET 4.0 and above that provides an easy way to perform OpenSearch query from a class or an URL to multiple and custom types of results (Atom, Rdf...)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Terradue")]
[assembly: AssemblyProduct("Terradue.OpenSearch")]
[assembly: AssemblyCopyright("Terradue")]
[assembly: AssemblyAuthors("Emmanuel Mathot")]
[assembly: AssemblyProjectUrl("https://github.com/Terradue/DotNetOpenSearch")]
[assembly: AssemblyLicenseUrl("https://github.com/Terradue/DotNetOpenSearch/blob/master/LICENSE")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.12.7.*")]
[assembly: AssemblyInformationalVersion("1.12.7")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
| /*
* Copyright (C) 2010-2014 Terradue S.r.l.
*
* This file is part of Terradue.OpenSearch.
*
* Foobar is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Terradue.OpenSearch.
* If not, see http://www.gnu.org/licenses/.
*/
/*!
\namespace Terradue.OpenSearch
@{
Terradue.OpenSearch is a .Net library that provides an engine perform OpenSearch query from a class or an URL to multiple and custom types of results
\xrefitem sw_version "Versions" "Software Package Version" 1.12.6
\xrefitem sw_link "Link" "Software Package Link" [DotNetOpenSearch](https://github.com/Terradue/DotNetOpenSearch)
\xrefitem sw_license "License" "Software License" [AGPL](https://github.com/DotNetOpenSearch/Terradue.OpenSearch/blob/master/LICENSE)
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Syndication
\ingroup OpenSearch
@}
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using NuGet4Mono.Extensions;
[assembly: AssemblyTitle("Terradue.OpenSearch")]
[assembly: AssemblyDescription("Terradue.OpenSearch is a library targeting .NET 4.0 and above that provides an easy way to perform OpenSearch query from a class or an URL to multiple and custom types of results (Atom, Rdf...)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Terradue")]
[assembly: AssemblyProduct("Terradue.OpenSearch")]
[assembly: AssemblyCopyright("Terradue")]
[assembly: AssemblyAuthors("Emmanuel Mathot")]
[assembly: AssemblyProjectUrl("https://github.com/Terradue/DotNetOpenSearch")]
[assembly: AssemblyLicenseUrl("https://github.com/Terradue/DotNetOpenSearch/blob/master/LICENSE")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.12.6.*")]
[assembly: AssemblyInformationalVersion("1.12.6")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
| agpl-3.0 | C# |
2f635f1d51221f5ac56fd18edd6b0b142c5b240e | Update Pettable.cs | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,krille90/unitystation,Necromunger/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Player/Pettable.cs | UnityProject/Assets/Scripts/Player/Pettable.cs | using UnityEngine;
/// <summary>
/// Allows an object to be pet by a player. Shameless copy of Huggable.cs
/// </summary>
public class Pettable : MonoBehaviour, IClientInteractable<PositionalHandApply>
{
public bool Interact(PositionalHandApply interaction)
{
var targetNPCHealth = interaction.TargetObject.GetComponent<LivingHealthBehaviour>();
var performerPlayerHealth = interaction.Performer.GetComponent<PlayerHealth>();
var performerRegisterPlayer = interaction.Performer.GetComponent<RegisterPlayer>();
// Is the target in range for a pet? Is the target conscious for the pet? Is the performer's intent set to help?
// Is the performer's hand empty? Is the performer not stunned/downed? Is the performer conscious to perform the interaction?
// Is the performer interacting with itself?
if (!PlayerManager.LocalPlayerScript.IsInReach(interaction.WorldPositionTarget, false) ||
targetNPCHealth.ConsciousState != ConsciousState.CONSCIOUS ||
UIManager.CurrentIntent != Intent.Help ||
interaction.HandObject != null ||
performerPlayerHealth.ConsciousState != ConsciousState.CONSCIOUS ||
performerRegisterPlayer.IsLayingDown ||
interaction.Performer == interaction.TargetObject)
{
return false;
}
Chat.AddActionMsgToChat(interaction.Performer,
$"You pet {interaction.TargetObject.name}.", $"{interaction.Performer.ExpensiveName()} pets {interaction.TargetObject.name}.");
return true;
}
} | using UnityEngine;
/// <summary>
/// Allows an object to be pet by a player.
/// </summary>
public class Pettable : MonoBehaviour, IClientInteractable<PositionalHandApply>
{
public bool Interact(PositionalHandApply interaction)
{
var targetNPCHealth = interaction.TargetObject.GetComponent<LivingHealthBehaviour>();
var performerPlayerHealth = interaction.Performer.GetComponent<PlayerHealth>();
var performerRegisterPlayer = interaction.Performer.GetComponent<RegisterPlayer>();
// Is the target in range for a pet? Is the target conscious for the pet? Is the performer's intent set to help?
// Is the performer's hand empty? Is the performer not stunned/downed? Is the performer conscious to perform the interaction?
// Is the performer interacting with itself?
if (!PlayerManager.LocalPlayerScript.IsInReach(interaction.WorldPositionTarget, false) ||
targetNPCHealth.ConsciousState != ConsciousState.CONSCIOUS ||
UIManager.CurrentIntent != Intent.Help ||
interaction.HandObject != null ||
performerPlayerHealth.ConsciousState != ConsciousState.CONSCIOUS ||
performerRegisterPlayer.IsLayingDown ||
interaction.Performer == interaction.TargetObject)
{
return false;
}
Chat.AddActionMsgToChat(interaction.Performer,
$"You pet {interaction.TargetObject.name}.", $"{interaction.Performer.ExpensiveName()} pets {interaction.TargetObject.name}.");
return true;
}
} | agpl-3.0 | C# |
6d578e9d0acc6a028ef081bab00b0868b8110cfd | Put markers in a dictionary for reuse. | jb-aero/CMSC491-VR | VRUnityProject/Assets/OurStuff/ObjectPlacer.cs | VRUnityProject/Assets/OurStuff/ObjectPlacer.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPlacer : MonoBehaviour {
public CountryLocation reader;
public GameObject prefab;
private Dictionary<string, GameObject> markers;
// Use this for initialization
void Start () {
Debug.Log ("LOOK WE ARE DOING THINGS");
reader.NotANormalWord ();
Debug.Log ("Size of our data: " + reader.countries.Count);
foreach (KeyValuePair<string, List<float>> entry in reader.countries)
{
int numItems = entry.Value.Count;
if(numItems == 1)
{
Debug.Log(entry.Key + ", num items: " + entry.Value.Count);
}
Debug.Log (entry.Key + ", lat: " + entry.Value[1] + ", long: " + entry.Value[2]);
GameObject marker = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.Euler(new Vector3(0, -entry.Value[2], entry.Value[1])));
marker.name = entry.Key;
markers.Add(entry.Key, marker);
}
Debug.Log ("THINGS HAVE BEEN DONE");
}
// Update is called once per frame
void Update () {
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPlacer : MonoBehaviour {
public CountryLocation reader;
public GameObject prefab;
// Use this for initialization
void Start () {
Debug.Log ("LOOK WE ARE DOING THINGS");
reader.NotANormalWord ();
Debug.Log ("Size of our data: " + reader.countries.Count);
foreach (KeyValuePair<string, List<float>> entry in reader.countries)
{
int numItems = entry.Value.Count;
if(numItems == 1)
{
Debug.Log(entry.Key + ", num items: " + entry.Value.Count);
}
Debug.Log (entry.Key + ", lat: " + entry.Value[1] + ", long: " + entry.Value[2]);
GameObject marker = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.Euler(new Vector3(0, -entry.Value[2], entry.Value[1])));
marker.name = entry.Key;
}
Debug.Log ("THINGS HAVE BEEN DONE");
}
// Update is called once per frame
void Update () {
}
}
| mit | C# |
e7d3d7ad90b1152a10ac83c8f5e3c38c7dc43fd0 | Update AssemblyInfo.cs | sbennett1990/WordOfTheDay | WordOfTheDay.Window/Properties/AssemblyInfo.cs | WordOfTheDay.Window/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Window")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Window")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Window")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Lowe's Companies, Inc.")]
[assembly: AssemblyProduct("Window")]
[assembly: AssemblyCopyright("Copyright © Lowe's Companies, Inc. 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bsd-2-clause | C# |
9cffa4fa0299feeb0bcb4ea8ff498db4677db16b | Switch to try/catch for assemblyload hook | antmicro/xwt,mono/xwt | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.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;
using AppKit;
using Foundation;
using ObjCRuntime;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
static readonly object lockObject = new object();
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.IgnoreMissingAssembliesDuringRegistration = true;
// Setup a registration handler that does not let Xamarin.Mac register assemblies by default.
Runtime.AssemblyRegistration += Runtime_AssemblyRegistration;
NSApplication.Init ();
// Register a callback when an assembly is loaded so it's registered in the xammac registrar.
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
// Manually register all the currently loaded assemblies.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Runtime.RegisterAssembly(assembly);
}
}
}
private static void Runtime_AssemblyRegistration(object sender, AssemblyRegistrationEventArgs args)
{
// If we don't do this, Xamarin.Mac will forcefully load all the assemblies referenced from the app startup assembly.
args.Register = false;
}
private static void CurrentDomain_AssemblyLoad (object sender, AssemblyLoadEventArgs args)
{
try
{
Runtime.RegisterAssembly(args.LoadedAssembly);
} catch (Exception e)
{
Console.Error.WriteLine("Error during static registrar initialization load", e);
}
}
}
}
| //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.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;
using AppKit;
using Foundation;
using ObjCRuntime;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
static readonly object lockObject = new object();
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.IgnoreMissingAssembliesDuringRegistration = true;
// Setup a registration handler that does not let Xamarin.Mac register assemblies by default.
Runtime.AssemblyRegistration += Runtime_AssemblyRegistration;
NSApplication.Init ();
// Register a callback when an assembly is loaded so it's registered in the xammac registrar.
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
// Manually register all the currently loaded assemblies.
lock (lockObject)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Runtime.RegisterAssembly(assembly);
}
}
}
}
private static void Runtime_AssemblyRegistration(object sender, AssemblyRegistrationEventArgs args)
{
// If we don't do this, Xamarin.Mac will forcefully load all the assemblies referenced from the app startup assembly.
args.Register = false;
}
private static void CurrentDomain_AssemblyLoad (object sender, AssemblyLoadEventArgs args)
{
lock (lockObject)
{
Runtime.RegisterAssembly(args.LoadedAssembly);
}
}
}
}
| mit | C# |
e67c611188be9338753c6f8e08088ec4da9b836c | 修复C/S计算MD5不一致问题(大小写不一致) | mc-gulu/ulog,mc-gulu/ulog,mc-gulu/ulog,mc-gulu/ulog | ulog/ulog_test/Assets/Util.cs | ulog/ulog_test/Assets/Util.cs | using UnityEngine;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public delegate void onFileProcessed(string filepath);
public class Util
{
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory, onFileProcessed handleFile)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
handleFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory, handleFile);
}
public static long GetFileSize(string filepath)
{
try
{
return new FileInfo(filepath).Length;
}
catch (System.Exception)
{
return 0;
}
}
public static string GetFileMD5(string filepath)
{
try
{
StringBuilder b = new StringBuilder();
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filepath))
{
byte[] digest = md5.ComputeHash(stream);
for (int i = 0; i < digest.Length; i++)
{
b.AppendFormat("{0:x}", digest[i]);
}
}
}
return b.ToString();
}
catch (System.Exception)
{
return "";
}
}
}
| using UnityEngine;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public delegate void onFileProcessed(string filepath);
public class Util
{
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory, onFileProcessed handleFile)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
handleFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory, handleFile);
}
public static long GetFileSize(string filepath)
{
try
{
return new FileInfo(filepath).Length;
}
catch (System.Exception)
{
return 0;
}
}
public static string GetFileMD5(string filepath)
{
try
{
StringBuilder b = new StringBuilder();
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filepath))
{
byte[] digest = md5.ComputeHash(stream);
for (int i = 0; i < digest.Length; i++)
{
b.AppendFormat("{0:X}", digest[i]);
}
}
}
return b.ToString();
}
catch (System.Exception)
{
return "";
}
}
}
| mit | C# |
05b9cba521b64105c9d68a620b639b39df43de70 | Add `LocalisableString.Format` method | ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework | osu.Framework/Localisation/LocalisableString.cs | osu.Framework/Localisation/LocalisableString.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
#nullable enable
namespace osu.Framework.Localisation
{
/// <summary>
/// A descriptor representing text that can be localised and formatted.
/// </summary>
public readonly struct LocalisableString : IEquatable<LocalisableString>
{
/// <summary>
/// The underlying data.
/// </summary>
internal readonly object? Data;
/// <summary>
/// Creates a new <see cref="LocalisableString"/> with underlying string data.
/// </summary>
public LocalisableString(string data)
{
Data = data;
}
/// <summary>
/// Creates a new <see cref="LocalisableString"/> with underlying localisable string data.
/// </summary>
public LocalisableString(ILocalisableStringData data)
{
Data = data;
}
/// <summary>
/// Replaces one or more format items in a specified string with a localised string representation of a corresponding object in <paramref name="args"/>.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The objects to format.</param>
public static LocalisableString Format(string format, params object?[] args) => new LocalisableFormattableString(format, args);
// it's somehow common to call default(LocalisableString), and we should return empty string then.
public override string ToString() => Data?.ToString() ?? string.Empty;
public bool Equals(LocalisableString other) => LocalisableStringEqualityComparer.Default.Equals(this, other);
public override bool Equals(object? obj) => obj is LocalisableString other && Equals(other);
public override int GetHashCode() => LocalisableStringEqualityComparer.Default.GetHashCode(this);
public static bool operator ==(LocalisableString left, LocalisableString right) => left.Equals(right);
public static bool operator !=(LocalisableString left, LocalisableString right) => !left.Equals(right);
public static implicit operator LocalisableString(string text) => new LocalisableString(text);
public static implicit operator LocalisableString(TranslatableString translatable) => new LocalisableString(translatable);
public static implicit operator LocalisableString(RomanisableString romanisable) => new LocalisableString(romanisable);
public static implicit operator LocalisableString(LocalisableFormattableString formattable) => new LocalisableString(formattable);
public static implicit operator LocalisableString(CaseTransformableString transformable) => new LocalisableString(transformable);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
#nullable enable
namespace osu.Framework.Localisation
{
/// <summary>
/// A descriptor representing text that can be localised and formatted.
/// </summary>
public readonly struct LocalisableString : IEquatable<LocalisableString>
{
/// <summary>
/// The underlying data.
/// </summary>
internal readonly object? Data;
/// <summary>
/// Creates a new <see cref="LocalisableString"/> with underlying string data.
/// </summary>
public LocalisableString(string data)
{
Data = data;
}
/// <summary>
/// Creates a new <see cref="LocalisableString"/> with underlying localisable string data.
/// </summary>
public LocalisableString(ILocalisableStringData data)
{
Data = data;
}
// it's somehow common to call default(LocalisableString), and we should return empty string then.
public override string ToString() => Data?.ToString() ?? string.Empty;
public bool Equals(LocalisableString other) => LocalisableStringEqualityComparer.Default.Equals(this, other);
public override bool Equals(object? obj) => obj is LocalisableString other && Equals(other);
public override int GetHashCode() => LocalisableStringEqualityComparer.Default.GetHashCode(this);
public static implicit operator LocalisableString(string text) => new LocalisableString(text);
public static implicit operator LocalisableString(TranslatableString translatable) => new LocalisableString(translatable);
public static implicit operator LocalisableString(RomanisableString romanisable) => new LocalisableString(romanisable);
public static implicit operator LocalisableString(LocalisableFormattableString formattable) => new LocalisableString(formattable);
public static implicit operator LocalisableString(CaseTransformableString transformable) => new LocalisableString(transformable);
public static bool operator ==(LocalisableString left, LocalisableString right) => left.Equals(right);
public static bool operator !=(LocalisableString left, LocalisableString right) => !left.Equals(right);
}
}
| mit | C# |
261ec7b9ebd1c88a8583d73efd4cc0eda91ec03a | Fix CORS configuration | senioroman4uk/PathFinder | PathFinder.EntryPoint/Startup.cs | PathFinder.EntryPoint/Startup.cs | using System;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using PathFinder.EntryPoint;
using PathFinder.Infrastructure.Extensions;
using PathFinder.Infrastructure.Providers;
using PathFinder.Security.DAL.Context;
using PathFinder.Security.DAL.Managers;
using SimpleInjector;
using SimpleInjector.Integration.WebApi;
[assembly: OwinStartup(typeof(Startup))]
namespace PathFinder.EntryPoint
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// CORS needs to be first in the pipeline
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
var container = SimpleInjectorConfiguration.ConfigurationSimpleInjector();
app.UseSimpleInjectorContext(container);
app.CreatePerOwinContext(container.GetInstance<SecurityContext>);
app.CreatePerOwinContext(container.GetInstance<AppUserManager>);
ConfigureOAuth(app);
HttpConfiguration configuration = ConfigureWebApi(container);
app.UseWebApi(configuration);
}
private void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
private HttpConfiguration ConfigureWebApi(Container container)
{
HttpConfiguration configuration = new HttpConfiguration
{
DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container),
};
configuration.MapHttpAttributeRoutes();
configuration.EnsureInitialized();
return configuration;
}
}
}
| using System;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using PathFinder.EntryPoint;
using PathFinder.Infrastructure.Extensions;
using PathFinder.Infrastructure.Providers;
using PathFinder.Security.DAL.Context;
using PathFinder.Security.DAL.Managers;
using SimpleInjector.Integration.WebApi;
[assembly: OwinStartup(typeof(Startup))]
namespace PathFinder.EntryPoint
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = SimpleInjectorConfiguration.ConfigurationSimpleInjector();
app.UseSimpleInjectorContext(container);
app.CreatePerOwinContext(container.GetInstance<SecurityContext>);
app.CreatePerOwinContext(container.GetInstance<AppUserManager>);
ConfigureOAuth(app);
HttpConfiguration configuration = new HttpConfiguration
{
DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container)
};
configuration.MapHttpAttributeRoutes();
configuration.EnsureInitialized();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(configuration);
}
private void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
| mit | C# |
1f4ca853129a77dc488bb7c751df3ed5b1c63bc4 | Add license header | ismangil/clearbooks-rest,ismangil/clearbooks-rest | clearbooks-rest/Controllers/CountriesController.cs | clearbooks-rest/Controllers/CountriesController.cs | // Copyright (c) 2016 Perry Ismangil
// This file is part of clearbooks-rest project.
//
// clearbooks-rest project is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// clearbooks-rest project is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with clearbooks-rest project. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace clearbooks_rest.Controllers
{
public class CountriesController : ApiController
{
/// <summary>
/// Retrieves two-letter country code
/// </summary>
/// <param name="countryName">Full country name</param>
/// <returns>Two-letter country code</returns>
[Route("api/GetCountryCode")]
public string GetCountryCode(string countryName)
{
var countries = new Bia.Countries.Iso3166Countries(StringComparer.OrdinalIgnoreCase);
return countries.GetAlpha2CodeByName(countryName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace clearbooks_rest.Controllers
{
public class CountriesController : ApiController
{
/// <summary>
/// Retrieves two-letter country code
/// </summary>
/// <param name="countryName">Full country name</param>
/// <returns>Two-letter country code</returns>
[Route("api/GetCountryCode")]
public string GetCountryCode(string countryName)
{
var countries = new Bia.Countries.Iso3166Countries(StringComparer.OrdinalIgnoreCase);
return countries.GetAlpha2CodeByName(countryName);
}
}
}
| agpl-3.0 | C# |
c0b0fd71a6c6390078207abdfe5a54f180ab258b | Add bot class method stubs | FireCube-/HarvesterBot | TexasHoldEm/Bot.cs | TexasHoldEm/Bot.cs | using System;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Bot {
private const int chromosomeSize = 10;
private Chromosome<double> chromosome;
public Bot() {
chromosome = new Chromosome<double>(chromosomeSize);
}
public Bot(double[] values) {
chromosome = new Chromosome<double>(values);
}
public bool betOrFold(int currentBet) {
// True is bet, False is fold
return true;
}
public int makeBet() {
// returns the ammount to bet
return 0;
}
private double getEnemyWinProb() {
// Returns the probability of the enemy winning
return 0.0;
}
private double getSelfWinProb() {
// Returns the probability of us winning
return 0.0;
}
}
| using System;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Bot {
public Bot() {
//
// TODO: Add constructor logic here
//
}
}
| mit | C# |
59ef8e2bb0637537b531a3d3efdbae370d311b7a | Bring welcome page back to project | peterblazejewicz/vnext-web-starter-kit,peterblazejewicz/vnext-web-starter-kit,peterblazejewicz/vnext-web-starter-kit | Startup.cs | Startup.cs | using Microsoft.AspNet.Builder;
namespace KWebStartup
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseWelcomePage();
}
}
} | using Microsoft.AspNet.Builder;
namespace KWebStartup
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
}
} | mit | C# |
bbed4d59f4a913233fa97340dcecc08ac471c9e8 | Improve debug output | mj1856/RavenDB-TimeZones | Raven.TimeZones/Extensions.cs | Raven.TimeZones/Extensions.cs | using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Raven.Abstractions.Indexing;
using Raven.Client;
namespace Raven.TimeZones
{
public static class Extensions
{
public static void InitializeTimeZones(this IDocumentStore documentStore)
{
documentStore.ExecuteIndex(new ZoneShapesIndex());
}
public static void ImportTimeZoneShapes(this IDocumentStore documentStore, string databaseName, string shapefilePath, bool replaceExistingShapes = false)
{
var importer = new DataImporter(documentStore, databaseName);
importer.ImportShapefile(shapefilePath, replaceExistingShapes);
}
public static void ImportTimeZoneShapes(this IDocumentStore documentStore, string shapefilePath, bool replaceExistingShapes = false)
{
var importer = new DataImporter(documentStore);
importer.ImportShapefile(shapefilePath, replaceExistingShapes);
}
public static string GetZoneForLocation(this IDocumentSession session, double latitude, double longitude)
{
// note: WKT uses lon/lat ordering
var point = string.Format(CultureInfo.InvariantCulture, "POINT ({0} {1})", longitude, latitude);
var results = session.Query<ZoneShape>()
.Customize(x => x.RelatesToShape("location", point, SpatialRelation.Intersects))
.ToList();
foreach (var x in results)
Debug.WriteLine(x.Zone);
var result = results.FirstOrDefault();
return result == null ? null : result.Zone;
}
}
}
| using System.Globalization;
using System.Linq;
using Raven.Abstractions.Indexing;
using Raven.Client;
namespace Raven.TimeZones
{
public static class Extensions
{
public static void InitializeTimeZones(this IDocumentStore documentStore)
{
documentStore.ExecuteIndex(new ZoneShapesIndex());
}
public static void ImportTimeZoneShapes(this IDocumentStore documentStore, string databaseName, string shapefilePath, bool replaceExistingShapes = false)
{
var importer = new DataImporter(documentStore, databaseName);
importer.ImportShapefile(shapefilePath, replaceExistingShapes);
}
public static void ImportTimeZoneShapes(this IDocumentStore documentStore, string shapefilePath, bool replaceExistingShapes = false)
{
var importer = new DataImporter(documentStore);
importer.ImportShapefile(shapefilePath, replaceExistingShapes);
}
public static string GetZoneForLocation(this IDocumentSession session, double latitude, double longitude)
{
// note: WKT uses lon/lat ordering
var point = string.Format(CultureInfo.InvariantCulture, "POINT ({0} {1})", longitude, latitude);
var result = session.Query<ZoneShape>()
.Customize(x => x.RelatesToShape("location", point, SpatialRelation.Intersects))
.FirstOrDefault();
return result == null ? null : result.Zone;
}
}
}
| mit | C# |
3d99454ed3976b8a379bf3200add82187cf85b5c | Refresh grid view when books model reloaded | allquixotic/banshee-gst-sharp-work,Dynalon/banshee-osx,petejohanson/banshee,ixfalia/banshee,ixfalia/banshee,arfbtwn/banshee,babycaseny/banshee,Dynalon/banshee-osx,lamalex/Banshee,stsundermann/banshee,petejohanson/banshee,arfbtwn/banshee,babycaseny/banshee,GNOME/banshee,ixfalia/banshee,mono-soc-2011/banshee,directhex/banshee-hacks,petejohanson/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,lamalex/Banshee,GNOME/banshee,GNOME/banshee,mono-soc-2011/banshee,petejohanson/banshee,Dynalon/banshee-osx,Carbenium/banshee,lamalex/Banshee,dufoli/banshee,petejohanson/banshee,allquixotic/banshee-gst-sharp-work,mono-soc-2011/banshee,allquixotic/banshee-gst-sharp-work,ixfalia/banshee,Dynalon/banshee-osx,dufoli/banshee,stsundermann/banshee,mono-soc-2011/banshee,stsundermann/banshee,arfbtwn/banshee,babycaseny/banshee,GNOME/banshee,arfbtwn/banshee,Carbenium/banshee,GNOME/banshee,directhex/banshee-hacks,stsundermann/banshee,Dynalon/banshee-osx,stsundermann/banshee,Dynalon/banshee-osx,stsundermann/banshee,arfbtwn/banshee,lamalex/Banshee,lamalex/Banshee,dufoli/banshee,GNOME/banshee,ixfalia/banshee,allquixotic/banshee-gst-sharp-work,babycaseny/banshee,dufoli/banshee,dufoli/banshee,Dynalon/banshee-osx,dufoli/banshee,Carbenium/banshee,stsundermann/banshee,Carbenium/banshee,directhex/banshee-hacks,babycaseny/banshee,directhex/banshee-hacks,lamalex/Banshee,GNOME/banshee,babycaseny/banshee,ixfalia/banshee,babycaseny/banshee,arfbtwn/banshee,ixfalia/banshee,Dynalon/banshee-osx,GNOME/banshee,ixfalia/banshee,arfbtwn/banshee,babycaseny/banshee,dufoli/banshee,mono-soc-2011/banshee,petejohanson/banshee,directhex/banshee-hacks,allquixotic/banshee-gst-sharp-work,Carbenium/banshee,mono-soc-2011/banshee,Carbenium/banshee,mono-soc-2011/banshee,arfbtwn/banshee,directhex/banshee-hacks,dufoli/banshee | src/Extensions/Banshee.Audiobook/Banshee.Audiobook/AudiobookContent.cs | src/Extensions/Banshee.Audiobook/Banshee.Audiobook/AudiobookContent.cs | //
// AudiobookContent.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, 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.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Data;
using Hyena.Data.Gui;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
namespace Banshee.Audiobook
{
public class AudiobookContent : ISourceContents
{
private AudiobookLibrarySource library;
private AudiobookGrid grid;
public AudiobookContent ()
{
grid = new AudiobookGrid ();
}
public bool SetSource (ISource src)
{
if (src != null && src == library)
return true;
library = src as AudiobookLibrarySource;
if (library == null) {
return false;
}
grid.SetModel (library.BooksModel);
// Not sure why this is needed
library.BooksModel.Reloaded += delegate {
grid.QueueDraw ();
};
return true;
}
public ISource Source {
get { return library; }
}
public void ResetSource ()
{
library = null;
}
public Widget Widget {
get { return grid; }
}
}
}
| //
// AudiobookContent.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, 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.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Data;
using Hyena.Data.Gui;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
namespace Banshee.Audiobook
{
public class AudiobookContent : ISourceContents
{
private AudiobookLibrarySource library;
private AudiobookGrid grid;
public AudiobookContent ()
{
grid = new AudiobookGrid ();
}
public bool SetSource (ISource src)
{
if (src != null && src == library)
return true;
library = src as AudiobookLibrarySource;
if (library == null) {
return false;
}
grid.SetModel (library.BooksModel);
return true;
}
public ISource Source {
get { return library; }
}
public void ResetSource ()
{
library = null;
}
public Widget Widget {
get { return grid; }
}
}
}
| mit | C# |
38d3d7bb19de53a53db75cacbf43293fff2256be | Remove PremiumRS edition value due to public preview schedule changes | zhencui/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,pankajsn/azure-powershell,pankajsn/azure-powershell,AzureAutomationTeam/azure-powershell,zhencui/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,jtlibing/azure-powershell,hungmai-msft/azure-powershell,jtlibing/azure-powershell,devigned/azure-powershell,yoavrubin/azure-powershell,krkhan/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,rohmano/azure-powershell,AzureRT/azure-powershell,zhencui/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,pankajsn/azure-powershell,zhencui/azure-powershell,yoavrubin/azure-powershell,devigned/azure-powershell,yoavrubin/azure-powershell,ClogenyTechnologies/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,jtlibing/azure-powershell,krkhan/azure-powershell,zhencui/azure-powershell,yantang-msft/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,pankajsn/azure-powershell,AzureRT/azure-powershell,yoavrubin/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,rohmano/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,yantang-msft/azure-powershell,naveedaz/azure-powershell,alfantp/azure-powershell,ClogenyTechnologies/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,seanbamsft/azure-powershell,zhencui/azure-powershell,yantang-msft/azure-powershell,hungmai-msft/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,alfantp/azure-powershell,AzureRT/azure-powershell,alfantp/azure-powershell,jtlibing/azure-powershell,yantang-msft/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,yantang-msft/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,yoavrubin/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,seanbamsft/azure-powershell,ClogenyTechnologies/azure-powershell,AzureRT/azure-powershell,krkhan/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,AzureRT/azure-powershell,atpham256/azure-powershell,seanbamsft/azure-powershell,devigned/azure-powershell | src/ResourceManager/Sql/Commands.Sql/Database/Model/DatabaseEdition.cs | src/ResourceManager/Sql/Commands.Sql/Database/Model/DatabaseEdition.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Sql.Database.Model
{
/// <summary>
/// The database edition
/// </summary>
public enum DatabaseEdition
{
/// <summary>
/// No database edition specified
/// </summary>
None = 0,
/// <summary>
/// A database premium edition
/// </summary>
Premium = 3,
/// <summary>
/// A database basic edition
/// </summary>
Basic = 4,
/// <summary>
/// A database standard edition
/// </summary>
Standard = 5,
/// <summary>
/// Azure SQL Data Warehouse database edition
/// </summary>
DataWarehouse = 6,
/// <summary>
/// Azure SQL Stretch database edition
/// </summary>
Stretch = 7,
/// <summary>
/// Free database edition. Reserved for special use cases/scenarios.
/// </summary>
Free = 8,
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Sql.Database.Model
{
/// <summary>
/// The database edition
/// </summary>
public enum DatabaseEdition
{
/// <summary>
/// No database edition specified
/// </summary>
None = 0,
/// <summary>
/// A database premium edition
/// </summary>
Premium = 3,
/// <summary>
/// A database basic edition
/// </summary>
Basic = 4,
/// <summary>
/// A database standard edition
/// </summary>
Standard = 5,
/// <summary>
/// Azure SQL Data Warehouse database edition
/// </summary>
DataWarehouse = 6,
/// <summary>
/// Azure SQL Stretch database edition
/// </summary>
Stretch = 7,
/// <summary>
/// Free database edition. Reserved for special use cases/scenarios.
/// </summary>
Free = 8,
/// <summary>
/// A database PremiumRS edition
/// </summary>
PremiumRS = 9,
}
}
| apache-2.0 | C# |
750b6671fac0052a3523e31d3f73ecccd09567e6 | Add LateUpdate check to scaler | NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,plrusek/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare | Assets/Scripts/UI/TextMeshLimitSize.cs | Assets/Scripts/UI/TextMeshLimitSize.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class TextMeshLimitSize : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private Vector2 maxExtents;
[SerializeField]
private TextMesh textMesh;
[SerializeField]
private Renderer textRenderer;
[SerializeField]
private Vector3 defaultScale;
#pragma warning restore 0649
private string lastString;
void Awake()
{
if (textMesh == null)
textMesh = GetComponent<TextMesh>();
if (textRenderer == null)
textRenderer = textMesh.GetComponent<Renderer>();
if (maxExtents == Vector2.zero)
maxExtents = textRenderer.bounds.extents;
if (!Application.isPlaying)
defaultScale = transform.localScale;
}
void Start()
{
lastString = "";
updateScale();
}
void Update()
{
if (textMesh.text != lastString)
updateScale();
}
void LateUpdate()
{
if (textMesh.text != lastString)
updateScale();
}
public void updateScale()
{
transform.localScale = defaultScale;
if (textRenderer.bounds.extents.x > maxExtents.x || textRenderer.bounds.extents.y > maxExtents.y)
transform.localScale *= Mathf.Min(maxExtents.x / textRenderer.bounds.extents.x, maxExtents.y / textRenderer.bounds.extents.y);
lastString = textMesh.text;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class TextMeshLimitSize : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private Vector2 maxExtents;
[SerializeField]
private TextMesh textMesh;
[SerializeField]
private Renderer textRenderer;
[SerializeField]
private Vector3 defaultScale;
#pragma warning restore 0649
private string lastString;
void Awake()
{
if (textMesh == null)
textMesh = GetComponent<TextMesh>();
if (textRenderer == null)
textRenderer = textMesh.GetComponent<Renderer>();
if (maxExtents == Vector2.zero)
maxExtents = textRenderer.bounds.extents;
if (!Application.isPlaying)
defaultScale = transform.localScale;
}
void Start()
{
lastString = "";
updateScale();
}
void Update()
{
if (textMesh.text != lastString)
updateScale();
}
public void updateScale()
{
transform.localScale = defaultScale;
if (textRenderer.bounds.extents.x > maxExtents.x || textRenderer.bounds.extents.y > maxExtents.y)
transform.localScale *= Mathf.Min(maxExtents.x / textRenderer.bounds.extents.x, maxExtents.y / textRenderer.bounds.extents.y);
lastString = textMesh.text;
}
}
| mit | C# |
0f0f3aa4046cc489b419b54eff1d5bb1a72cf7c8 | Comment Fixing | BillSkiCO/ChessCodingExercise | ChessBoard.cs | ChessBoard.cs | /*
*
*
*
* */
using System;
namespace Chess.Domain
{
public class ChessBoard
{
public static readonly int MaxBoardWidth = 7;
public static readonly int MaxBoardHeight = 7;
private Pawn[,] pieces;
public ChessBoard ()
{
pieces = new Pawn[MaxBoardWidth, MaxBoardHeight];
}
/* Pre-Condition: Intake of Pawn Object, 2 integers (x,y coordinates) and Enum Piececolor (black or white).
* Post-Condition: Pawn Object with input generated (x,y) coordinates and color. */
public void Add(Pawn pawn, int xCoordinate, int yCoordinate, PieceColor pieceColor)
{
// Set _xCoordinate in Pawn.
pawn.XCoordinate = xCoordinate;
// Set _yCoordinate in Pawn.
pawn.YCoordinate = yCoordinate;
// Set _pieceColor using mutator Pawn() in Pawn.
pawn = new Pawn(pieceColor);
}
/* Pre-Condition: Intake of 2 integers (x,y) coordinates.
* Post-Condition: Returns True or False based on (x ,y) Coordinates in comparison to MaxBoardWidth and MaxBoardHeight.*/
public bool IsLegalBoardPosition(int xCoordinate, int yCoordinate)
{
// Non-Zero Test, y bound and then x bound.
if(xCoordinate >= 0 && yCoordinate >= 0)
{
if ((MaxBoardHeight >= yCoordinate))
{
if ((MaxBoardWidth >= xCoordinate))
{
return true;
}
else
return false;
}
else
return false;
}
else
return false;
}
}
}
| /*
*
*
*
* */
using System;
namespace Chess.Domain
{
public class ChessBoard
{
public static readonly int MaxBoardWidth = 7;
public static readonly int MaxBoardHeight = 7;
private Pawn[,] pieces;
public ChessBoard ()
{
pieces = new Pawn[MaxBoardWidth, MaxBoardHeight];
}
/* Pre-Condition: Intake of Pawn Object, 2 integers (x,y coordinates), Enum Piececolor (black or white)
* Post-Condition: Pawn Object with input generated (x,y) coordinates and color */
public void Add(Pawn pawn, int xCoordinate, int yCoordinate, PieceColor pieceColor)
{
pawn.XCoordinate = xCoordinate; //Set _xCoordinate in Pawn class
pawn.YCoordinate = yCoordinate; //Set _yCoordinate in Pawn class
pawn = new Pawn(pieceColor); //Set _pieceColor using mutator Pawn() in Pawn class
}
/* Pre-Condition: Intake of 2 integers
* Post-Condition: Returns True or False based on (x ,y) Coordinates in comparison to MaxBoardWidth and MaxBoardHeight*/
public bool IsLegalBoardPosition(int xCoordinate, int yCoordinate)
{
if(xCoordinate >= 0 && yCoordinate >= 0){ //Non-zero test
if ((MaxBoardHeight >= yCoordinate)){ //yCoordinate Test
if ((MaxBoardWidth >= xCoordinate)){ //xCoordinate Test
return true;
}
else
return false; //xCoordinate Test Fail
}
else
return false; //yCoordinate Test Fail
}
else
return false; //Non-Zero Test Fail
}
}
}
| mit | C# |
2e60c02e15c11b87d06d84a5ed70b073e28d9dd7 | Fix IosSurfaceRenderer | florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho | Bindings/iOS/IosPlatformInitializer.cs | Bindings/iOS/IosPlatformInitializer.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Urho.Forms;
using System.Runtime.InteropServices;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using UIKit;
[assembly: ExportRendererAttribute(typeof(UrhoSurface), typeof(IosSurfaceRenderer))]
namespace Urho.Forms
{
public class IosSurfaceRenderer : ViewRenderer<UrhoSurface, IosUrhoSurface>
{
protected override void OnElementChanged(ElementChangedEventArgs<UrhoSurface> e)
{
var surface = new IosUrhoSurface();
surface.BackgroundColor = UIColor.Red;
e.NewElement.UrhoApplicationLauncher = surface.Launcher;
SetNativeControl(surface);
}
}
public class IosUrhoSurface : UIView
{
static TaskCompletionSource<Application> applicationTaskSource;
static readonly SemaphoreSlim launcherSemaphore = new SemaphoreSlim(1);
static Urho.iOS.UrhoSurface surface;
static Urho.Application app;
[DllImport(Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
static extern void SDL_SendAppEvent(Urho.iOS.SdlEvent sdlEvent);
internal async Task<Urho.Application> Launcher(Type type, ApplicationOptions options)
{
await launcherSemaphore.WaitAsync();
applicationTaskSource = new TaskCompletionSource<Application>();
Urho.Application.Started += UrhoApplicationStarted;
if (surface != null)
{
//app.Graphics.Release (false, false);
}
else {
this.Add(surface = new Urho.iOS.UrhoSurface(this.Bounds));
}
app = Urho.Application.CreateInstance(type, options);
app.Run();
return await applicationTaskSource.Task;
}
void UrhoApplicationStarted()
{
Urho.Application.Started -= UrhoApplicationStarted;
applicationTaskSource?.TrySetResult(app);
launcherSemaphore.Release();
}
}
}
| using System.Linq;
using System.Runtime.InteropServices;
using Foundation;
namespace Urho.iOS
{
public static class IosUrhoInitializer
{
[DllImport(Consts.NativeImport)]
static extern void InitSdl(string resDir, string docDir);
[DllImport(Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
static extern void SDL_SetMainReady();
internal static void OnInited()
{
string docsDir = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.All, true).FirstOrDefault();
string resourcesDir = NSBundle.MainBundle.ResourcePath;
InitSdl(resourcesDir, docsDir);
SDL_SetMainReady();
NSFileManager.DefaultManager.ChangeCurrentDirectory(resourcesDir);
}
}
}
| mit | C# |
2046637adfeebd8fed58a7878aa9725510b13d34 | Add HasMoreResults to DocumentList | diadoc/diadocsdk-csharp,diadoc/diadocsdk-csharp | src/Proto/Documents/DocumentList.cs | src/Proto/Documents/DocumentList.cs | using System.Runtime.InteropServices;
using Diadoc.Api.Com;
namespace Diadoc.Api.Proto.Documents
{
[ComVisible(true)]
[Guid("C04B249A-7FEA-4C4D-A273-AEEDA147AF4F")]
public interface IDocumentList
{
int TotalCount { get; }
ReadonlyList DocumentsList { get; }
bool HasMoreResults { get; }
}
[ComVisible(true)]
[Guid("4E7F2FF8-ECD0-43B6-A89D-041715BA5AD6")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentList))]
public partial class DocumentList : SafeComObject, IDocumentList
{
public ReadonlyList DocumentsList
{
get { return new ReadonlyList(Documents); }
}
}
}
| using System.Runtime.InteropServices;
using Diadoc.Api.Com;
namespace Diadoc.Api.Proto.Documents
{
[ComVisible(true)]
[Guid("C04B249A-7FEA-4C4D-A273-AEEDA147AF4F")]
public interface IDocumentList
{
int TotalCount { get; }
ReadonlyList DocumentsList { get; }
}
[ComVisible(true)]
[Guid("4E7F2FF8-ECD0-43B6-A89D-041715BA5AD6")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDocumentList))]
public partial class DocumentList : SafeComObject, IDocumentList
{
public ReadonlyList DocumentsList
{
get { return new ReadonlyList(Documents); }
}
}
}
| mit | C# |
ad585267f187a5a5ff52ee474219db21a346d970 | Modify File userAuth.cpl/userAuth.cpl/userAuth.cpl.cs | ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate | userAuth.cpl/userAuth.cpl/userAuth.cpl.cs | userAuth.cpl/userAuth.cpl/userAuth.cpl.cs | using System;
using Xamarin.Forms;
namespace userAuth.cpl
{
public class App : Application
{
public App ()
{
// The root page of your application
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
XAlign = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
}
}
};
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
protected void OnClick ()
{
// Handle click send to your app
}
public class StackOrientationMod : Element.Constraint{}
{
// Modify the stack orient command
}
public class ClickRef : IViewController
{
public ClickRef ()
{
IVisualElementController = Element.ContentPage()
{
Attribute.ReferenceEquals}:(bool){
object OnClick();
object OnRelease();
from Setter (import value.ascending[1])
if () { element.identifier != null
while (
const [prop (X:369, 85, 583), (Y:583, 883, 963), (Z: 356, 963, 912)].deploy
}
}
} Setter. StackOrientation from; - objectvalues.ascending value
}] const StackAltitude::meta (Frame, StackOrientation, Math.count.Frame(stackalloc::meta(const: frame_stack_init){
var framealloc = Type="Hex" ;
for (framealloc = 0) {
InvalidCastException(reset_framealloc: return());
if (framealloc:-int:count = 1) {
ColumnDefinitionCollection().--^X
}; else (Frame = int + count in Exception) {
while Exception != prop:Y(Int32 <= yield);
} case: += Int64 (X:0);
switch(Element.const(Int64 ++ >1;
return ClickRef.prop(X)
}
}
"Move file connect.ts from javascript/ to app/dynamic/app/javascript/(hidden)" | using System;
using Xamarin.Forms;
namespace userAuth.cpl
{
public class App : Application
{
public App ()
{
// The root page of your application
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
XAlign = TextAlignment.Center,
Text = "Welcome to Xamarin Forms!"
}
}
}
};
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
protected void OnClick ()
{
// Handle click send to your app
}
public class StackOrientationMod : Element.Constraint/|\(InputPr)
{
// Modify the stack orient command
}
public class ClickRef : IViewController
{
public ClickRef ()
{
IVisualElementController = Element.ContentPage()
{
Attribute.ReferenceEquals}:(bool){
object OnClick();
object OnRelease();
from Setter (import value.ascending[1])
if () { element.identifier != null
while (
const [prop (X:369, 85, 583), (Y:583, 883, 963), (Z: 356, 963, 912)].deploy
}
}
} Setter. StackOrientation from object(values.ascending, value)
}
| mit | C# |
850cbf01906721bcc6d9bfbd7b382babfb833535 | Fix WaitFor methods missing from IDispatcher | ProductiveRage/Bridge.React,ProductiveRage/Bridge.React | Bridge.React/Dispatcher/IDispatcher.cs | Bridge.React/Dispatcher/IDispatcher.cs | using System;
using System.Collections.Generic;
namespace Bridge.React
{
public interface IDispatcher
{
/// <summary>
/// Dispatches an action that will be sent to all callbacks registered with this dispatcher.
/// </summary>
/// <param name="action">The action to dispatch; may not be null.</param>
void Dispatch(IDispatcherAction action);
/// <summary>
/// Registers a callback to receive actions dispatched through this dispatcher. For historical reasons, this is called Receive instead of Register - this interface originally only had a Register method
/// that accepted a callback for DispatcherMessage instance, which were actions paired with a source of either View or Server and which were dispatched via methods HandleViewAction or HandleServerAction.
/// These methods and the DispatcherMessage class are now considered obsolete, as is the Register method that receives DispatcherMessage instance. However, in order to avoid breaking existing code, the
/// method that registers to receive unwrapped IDispatcherAction instances must be called a name other than Register (otherwise previously-compiling code could be afflicted by call-is-ambiguous errors).
/// </summary>
/// <param name="callback">The callback; may not be null.</param>
/// <remarks>
/// Actions will be sent to each receiver in the same order as which the receivers called Register.
/// </remarks>
DispatchToken Receive(Action<IDispatcherAction> callback);
/// <summary>
/// Unregisters the callback associated with the given token.
/// </summary>
/// <param name="token">The dispatch token to unregister; may not be null.</param>
/// <remarks>
/// This method cannot be called while a dispatch is in progress.
/// </remarks>
void Unregister(DispatchToken token);
[Obsolete("Support for Actions attributed to different sources (i.e. View vs. Server actions) will be removed from the IDispatcher interface. Use the Dispatch method instead of HandleViewAction or HandleServerAction.")]
void HandleServerAction(IDispatcherAction action);
[Obsolete("Support for Actions attributed to different sources (i.e. View vs. Server actions) will be removed from the IDispatcher interface. Use the Dispatch method instead of HandleViewAction or HandleServerAction.")]
void HandleViewAction(IDispatcherAction action);
[Obsolete("Support for Actions attributed to different sources (i.e. View vs. Server actions) will be removed from the IDispatcher interface. Use the Receive(Action<IDispatcherAction>) method instead of Register(Action<DispatcherMessage>).")]
DispatchToken Register(Action<DispatcherMessage> callback);
/// <summary>
/// Waits for the callbacks associated with the given tokens to be called first during a dispatch operation.
/// </summary>
/// <param name="tokens">The tokens to wait on; may not be null.</param>
/// <remarks>
/// This method can only be called while a dispatch is in progress.
/// </remarks>
void WaitFor(IEnumerable<DispatchToken> tokens);
/// <summary>
/// Waits for the callbacks associated with the given tokens to be called first during a dispatch operation.
/// </summary>
/// <param name="tokens">The tokens to wait on; may not be null.</param>
/// <remarks>
/// This method can only be called while a dispatch is in progress.
/// </remarks>
void WaitFor(params DispatchToken[] tokens);
}
} | using System;
namespace Bridge.React
{
public interface IDispatcher
{
/// <summary>
/// Dispatches an action that will be sent to all callbacks registered with this dispatcher.
/// </summary>
/// <param name="action">The action to dispatch; may not be null.</param>
void Dispatch(IDispatcherAction action);
/// <summary>
/// Registers a callback to receive actions dispatched through this dispatcher. For historical reasons, this is called Receive instead of Register - this interface originally only had a Register method
/// that accepted a callback for DispatcherMessage instance, which were actions paired with a source of either View or Server and which were dispatched via methods HandleViewAction or HandleServerAction.
/// These methods and the DispatcherMessage class are now considered obsolete, as is the Register method that receives DispatcherMessage instance. However, in order to avoid breaking existing code, the
/// method that registers to receive unwrapped IDispatcherAction instances must be called a name other than Register (otherwise previously-compiling code could be afflicted by call-is-ambiguous errors).
/// </summary>
/// <param name="callback">The callback; may not be null.</param>
/// <remarks>
/// Actions will be sent to each receiver in the same order as which the receivers called Register.
/// </remarks>
DispatchToken Receive(Action<IDispatcherAction> callback);
/// <summary>
/// Unregisters the callback associated with the given token.
/// </summary>
/// <param name="token">The dispatch token to unregister; may not be null.</param>
/// <remarks>
/// This method cannot be called while a dispatch is in progress.
/// </remarks>
void Unregister(DispatchToken token);
[Obsolete("Support for Actions attributed to different sources (i.e. View vs. Server actions) will be removed from the IDispatcher interface. Use the Dispatch method instead of HandleViewAction or HandleServerAction.")]
void HandleServerAction(IDispatcherAction action);
[Obsolete("Support for Actions attributed to different sources (i.e. View vs. Server actions) will be removed from the IDispatcher interface. Use the Dispatch method instead of HandleViewAction or HandleServerAction.")]
void HandleViewAction(IDispatcherAction action);
[Obsolete("Support for Actions attributed to different sources (i.e. View vs. Server actions) will be removed from the IDispatcher interface. Use the Receive(Action<IDispatcherAction>) method instead of Register(Action<DispatcherMessage>).")]
DispatchToken Register(Action<DispatcherMessage> callback);
}
} | mit | C# |
96ff0f66a2a6a62f4cbea94a449864015dc3699f | update version information | esskar/SignalR.RavenDB | src/SignalR.RavenDB/AssemblyInfo.cs | src/SignalR.RavenDB/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("SignalR.RavenDB")]
[assembly: AssemblyDescription("RavenDB messaging backplane for scaling out of ASP.NET SignalR applications in a web-farm.")]
[assembly: AssemblyProduct("SignalR.RavenDB")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyVersion("1.0.2")]
[assembly: AssemblyFileVersion("1.0.2")]
| using System.Reflection;
[assembly: AssemblyTitle("SignalR.RavenDB")]
[assembly: AssemblyDescription("RavenDB messaging backplane for scaling out of ASP.NET SignalR applications in a web-farm.")]
[assembly: AssemblyProduct("SignalR.RavenDB")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
61e739816d2794a9369a65ace51ce41f0ddbca25 | Make KeyManager look in the right place for connections.dll. | BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop | src/BloomExe/WebLibraryIntegration/KeyManager.cs | src/BloomExe/WebLibraryIntegration/KeyManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Palaso.Extensions;
using Palaso.IO;
namespace Bloom.WebLibraryIntegration
{
/// <summary>
/// This class is responsible for the key bits of information that are needed to access our backend sites.
/// These keys are not very secret and could easily be found, for example, by packet snooping.
/// However, we want to keep them out of source code where someone might be able to do a google search
/// and easily find our keys and use our storage.
/// The keys are currently stored in a file called connections.dll. The installer must place a version of this
/// in the EXE directory. Developers must do so manually.
/// You can see what keys are stored in what order by checking the constructor.
/// Enhance: it may be helpful to use a distinct version of connections.dll for developers, testers,
/// and others who should be working in a sandbox rather than modifying the live data.
/// That will work for Parse.com, where we currently have different API keys for the sandbox.
/// For the S3 data, we currently just use different buckets. If we wanted to, we could put the
/// 'real data' bucket name here also, and put the appropriate one into the testing version of connections.dll.
/// Todo: Some of the real keys are still in our version control history. Before we go live, we may want
/// to change the keys so any keys discovered in our version control are obsolete.
/// </summary>
static class KeyManager
{
public static string S3AccessKey { get; private set; }
public static string S3SecretAccessKey { get; private set; }
public static string ParseApiKey { get; private set; }
public static string ParseApplicationKey { get; private set; }
public static string ParseUnitTestApiKey { get; private set; }
public static string ParseUnitTextApplicationKey { get; private set; }
static KeyManager()
{
var connectionsPath = FileLocator.GetFileDistributedWithApplication("connections.dll");
var lines = File.ReadAllLines(connectionsPath);
S3AccessKey = lines[0];
S3SecretAccessKey = lines[1];
ParseApiKey = lines[2];
ParseApplicationKey = lines[3];
ParseUnitTestApiKey = lines[4];
ParseUnitTextApplicationKey = lines[5];
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Palaso.Extensions;
namespace Bloom.WebLibraryIntegration
{
/// <summary>
/// This class is responsible for the key bits of information that are needed to access our backend sites.
/// These keys are not very secret and could easily be found, for example, by packet snooping.
/// However, we want to keep them out of source code where someone might be able to do a google search
/// and easily find our keys and use our storage.
/// The keys are currently stored in a file called connections.dll. The installer must place a version of this
/// in the EXE directory. Developers must do so manually.
/// You can see what keys are stored in what order by checking the constructor.
/// Enhance: it may be helpful to use a distinct version of connections.dll for developers, testers,
/// and others who should be working in a sandbox rather than modifying the live data.
/// That will work for Parse.com, where we currently have different API keys for the sandbox.
/// For the S3 data, we currently just use different buckets. If we wanted to, we could put the
/// 'real data' bucket name here also, and put the appropriate one into the testing version of connections.dll.
/// Todo: Some of the real keys are still in our version control history. Before we go live, we may want
/// to change the keys so any keys discovered in our version control are obsolete.
/// </summary>
static class KeyManager
{
public static string S3AccessKey { get; private set; }
public static string S3SecretAccessKey { get; private set; }
public static string ParseApiKey { get; private set; }
public static string ParseApplicationKey { get; private set; }
public static string ParseUnitTestApiKey { get; private set; }
public static string ParseUnitTextApplicationKey { get; private set; }
static KeyManager()
{
var connectionsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Replace("file:", string.Empty).TrimStart('/'))
.CombineForPath("connections.dll");
var lines = File.ReadAllLines(connectionsPath);
S3AccessKey = lines[0];
S3SecretAccessKey = lines[1];
ParseApiKey = lines[2];
ParseApplicationKey = lines[3];
ParseUnitTestApiKey = lines[4];
ParseUnitTextApplicationKey = lines[5];
}
}
}
| mit | C# |
1ab641e5ed7b5c5cf937ed128ff18722f2aeb50c | remove link | nimeshvaghasiya/MyHeritage,nimeshvaghasiya/MyHeritage,nimeshvaghasiya/MyHeritage,nimeshvaghasiya/MyHeritage,nimeshvaghasiya/MyHeritage | src/MyHeritage.API/Controllers/TreeController.cs | src/MyHeritage.API/Controllers/TreeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MyHeritage.Data.Abstract;
namespace MyHeritage.API.Controllers
{
[Route("api/[controller]")]
public class TreeController : Controller
{
private ITreeMemberHeritageRepository _treeMemberHeritageRepository;
public TreeController(ITreeMemberHeritageRepository treeMemberHeritageRepository)
{
_treeMemberHeritageRepository = treeMemberHeritageRepository;
}
[HttpGet("GetAll/{id}")]
public IActionResult GetAll(int id = 1)
{
var result = _treeMemberHeritageRepository.FindBy(t => t.LinkToMemberMasterId == id);
return new OkObjectResult(result);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MyHeritage.Data.Abstract;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MyHeritage.API.Controllers
{
[Route("api/[controller]")]
public class TreeController : Controller
{
private ITreeMemberHeritageRepository _treeMemberHeritageRepository;
public TreeController(ITreeMemberHeritageRepository treeMemberHeritageRepository)
{
_treeMemberHeritageRepository = treeMemberHeritageRepository;
}
[HttpGet("GetAll/{id}")]
public IActionResult GetAll(int id = 1)
{
var result = _treeMemberHeritageRepository.FindBy(t => t.LinkToMemberMasterId == id);
return new OkObjectResult(result);
}
}
}
| mit | C# |
d747dec93c1ac2c2b4efa9631c9095fac1cd4761 | Support new FolderErrors event | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/SyncThing/ApiClient/EventType.cs | src/SyncTrayzor/SyncThing/ApiClient/EventType.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.ApiClient
{
[JsonConverter(typeof(StringEnumConverter))]
public enum EventType
{
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.ApiClient
{
[JsonConverter(typeof(StringEnumConverter))]
public enum EventType
{
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
}
}
| mit | C# |
335cd4577a0602db6680186a40800c2718ace43c | Add comment to Auth Login action describing redirect | GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet | aspnet/4-auth/Controllers/SessionController.cs | aspnet/4-auth/Controllers/SessionController.cs | // Copyright(c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
namespace GoogleCloudSamples.Controllers
{
// [START login]
public class SessionController : Controller
{
public ActionResult Login()
{
// Redirect to the Google OAuth 2.0 user consent screen
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
"Google"
);
return new HttpUnauthorizedResult();
}
// ...
// [END login]
// [START logout]
public ActionResult Logout()
{
Request.GetOwinContext().Authentication.SignOut();
return Redirect("/");
}
// [END logout]
}
}
| // Copyright(c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
namespace GoogleCloudSamples.Controllers
{
// [START login]
public class SessionController : Controller
{
// GET: Session/Login
public ActionResult Login()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
"Google"
);
return new HttpUnauthorizedResult();
}
// ...
// [END login]
// [START logout]
// GET: Session/Logout
public ActionResult Logout()
{
Request.GetOwinContext().Authentication.SignOut();
return Redirect("/");
}
// [END logout]
}
}
| apache-2.0 | C# |
7e2ea3b6bc4b8728e34c49f1494798820f65e7cc | Allow products to have 0 price | notdev/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI | RohlikAPI/Helpers/PriceParser.cs | RohlikAPI/Helpers/PriceParser.cs | using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RohlikAPI.Helpers
{
public class PriceParser
{
public double ParsePrice(string priceString)
{
var priceStringWithoutSpaces = priceString.Replace(" ", "").Replace(" ","");
var cleanPriceString = Regex.Match(priceStringWithoutSpaces, @"(\d*?,\d*)|(\d+)").Value;
try
{
var price = double.Parse(cleanPriceString, new CultureInfo("cs-CZ"));
return price;
}
catch (Exception ex)
{
throw new Exception($"Failed to parse product price from string '{priceString}'. Exception: {ex}");
}
}
}
} | using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RohlikAPI.Helpers
{
public class PriceParser
{
public double ParsePrice(string priceString)
{
var priceStringWithoutSpaces = priceString.Replace(" ", "").Replace(" ","");
var cleanPriceString = Regex.Match(priceStringWithoutSpaces, @"(\d*?,\d*)|(\d+)").Value;
try
{
var price = double.Parse(cleanPriceString, new CultureInfo("cs-CZ"));
if (price <= 0)
{
throw new Exception($"Failed to get product price from string '{priceString}'. Resulting price was {price}");
}
return price;
}
catch (Exception ex)
{
throw new Exception($"Failed to parse product price from string '{priceString}'. Exception: {ex}");
}
}
}
} | mit | C# |
cf24ec0f66602481ac0dfd6f4582b1daa15c0573 | Disable SynchronizeNowButton during synchronization. | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer/CalDavSynchronizerRibbon.cs | CalDavSynchronizer/CalDavSynchronizerRibbon.cs | using System;
using System.Reflection;
using CalDavSynchronizer.Ui;
using CalDavSynchronizer.Utilities;
using log4net;
using Microsoft.Office.Tools.Ribbon;
namespace CalDavSynchronizer
{
public partial class CalDavSynchronizerRibbon
{
private void CalDavSynchronizerRibbon_Load (object sender, RibbonUIEventArgs e)
{
}
private async void SynchronizeNowButton_Click (object sender, RibbonControlEventArgs e)
{
SynchronizeNowButton.Enabled = false;
try
{
await ThisAddIn.ComponentContainer.SynchronizeNowNoThrow();
}
finally
{
SynchronizeNowButton.Enabled = true;
}
}
private void OptionsButton_Click (object sender, RibbonControlEventArgs e)
{
ThisAddIn.ComponentContainer.ShowOptionsNoThrow();
}
private void AboutButton_Click (object sender, RibbonControlEventArgs e)
{
using (var aboutForm = new AboutForm())
{
aboutForm.ShowDialog();
}
}
}
} | using System;
using System.Reflection;
using CalDavSynchronizer.Ui;
using CalDavSynchronizer.Utilities;
using log4net;
using Microsoft.Office.Tools.Ribbon;
namespace CalDavSynchronizer
{
public partial class CalDavSynchronizerRibbon
{
private void CalDavSynchronizerRibbon_Load (object sender, RibbonUIEventArgs e)
{
}
private async void SynchronizeNowButton_Click (object sender, RibbonControlEventArgs e)
{
await ThisAddIn.ComponentContainer.SynchronizeNowNoThrow();
}
private void OptionsButton_Click (object sender, RibbonControlEventArgs e)
{
ThisAddIn.ComponentContainer.ShowOptionsNoThrow ();
}
private void AboutButton_Click (object sender, RibbonControlEventArgs e)
{
using (var aboutForm = new AboutForm())
{
aboutForm.ShowDialog();
}
}
}
} | agpl-3.0 | C# |
d5d2922556039808654417c41655c360d96ae3c1 | Add comment as this may be removed in the future | ZLima12/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework | osu.Framework/Platform/Linux/LinuxGameHost.cs | osu.Framework/Platform/Linux/LinuxGameHost.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Platform.Linux.Native;
namespace osu.Framework.Platform.Linux
{
public class LinuxGameHost : DesktopGameHost
{
internal LinuxGameHost(string gameName, bool bindIPC = false)
: base(gameName, bindIPC)
{
Window = new LinuxGameWindow();
Window.WindowStateChanged += (sender, e) =>
{
if (Window.WindowState != OpenTK.WindowState.Minimized)
OnActivated();
else
OnDeactivated();
};
// required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852)
Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL);
}
protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this);
public override Clipboard GetClipboard() => new LinuxClipboard();
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Platform.Linux.Native;
namespace osu.Framework.Platform.Linux
{
public class LinuxGameHost : DesktopGameHost
{
internal LinuxGameHost(string gameName, bool bindIPC = false)
: base(gameName, bindIPC)
{
Window = new LinuxGameWindow();
Window.WindowStateChanged += (sender, e) =>
{
if (Window.WindowState != OpenTK.WindowState.Minimized)
OnActivated();
else
OnDeactivated();
};
Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL);
}
protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this);
public override Clipboard GetClipboard() => new LinuxClipboard();
}
}
| mit | C# |
f5cec0b080b2868799e8dab51843012a79cedca0 | add [m_dic] | yasokada/unity-160820-Inventory-UI | Assets/DataBaseManager.cs | Assets/DataBaseManager.cs | using UnityEngine;
//using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using NS_MyStringUtil;
/*
* - add dictionary [m_dic]
* - add [kIndex_checkDate]
* - add [kIndex_XXX] such as kIndex_row
* v0.1 2016 Aug. 23
* - add LoadCsvResouce()
*/
namespace NS_DataBaseManager
{
public class DataBaseManager {
Dictionary <string, string> m_dic;
// string m_dataString;
public const int kIndex_caseNo = 0;
public const int kIndex_row = 1;
public const int kIndex_column = 2;
public const int kIndex_name = 3;
public const int kIndex_about = 4;
public const int kIndex_url = 5;
public const int kIndex_checkDate = 6;
public void LoadCsvResouce() {
if (m_dic == null) {
m_dic = new Dictionary<string, string>();
}
TextAsset csv = Resources.Load ("inventory") as TextAsset;
StringReader reader = new StringReader (csv.text);
string line = "";
string itmnm;
while (reader.Peek () != -1) {
line = reader.ReadLine ();
itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name);
m_dic->Add (itmnm, line);
}
// m_dataString = line;
}
public string getString() {
// return m_dataString;
}
}
}
| using UnityEngine;
using System.Collections;
using System.IO;
/*
* - add [kIndex_checkDate]
* - add [kIndex_XXX] such as kIndex_row
* v0.1 2016 Aug. 23
* - add LoadCsvResouce()
*/
namespace NS_DataBaseManager
{
public class DataBaseManager {
string m_dataString;
public const int kIndex_caseNo = 0;
public const int kIndex_row = 1;
public const int kIndex_column = 2;
public const int kIndex_name = 3;
public const int kIndex_about = 4;
public const int kIndex_url = 5;
public const int kIndex_checkDate = 6;
public void LoadCsvResouce() {
TextAsset csv = Resources.Load ("inventory") as TextAsset;
StringReader reader = new StringReader (csv.text);
string line = "";
while (reader.Peek () != -1) {
line = line + reader.ReadLine ();
// TODO: add CRLF
}
m_dataString = line;
}
public string getString() {
return m_dataString;
}
}
}
| mit | C# |
99c83b01d3bb99019ffaf69a7ef72b9b48d52e69 | Update PasteController - make fields readonly | mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX | Modix.WebServer/Controllers/PasteController.cs | Modix.WebServer/Controllers/PasteController.cs | using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Modix.Services.CodePaste;
namespace Modix.WebServer.Controllers
{
[Route("~/api")]
public class PasteController : Controller
{
private readonly ICodePasteRepository _codePasteRepository;
public PasteController(ICodePasteRepository codePasteRepository)
{
_codePasteRepository = codePasteRepository;
}
[Route("pastes")]
public IActionResult Index()
{
return Ok(_codePasteRepository.GetPastes().OrderByDescending(d=>d.Created).Take(10));
}
[Route("pastes/{id}")]
public IActionResult Index(int id)
{
return Ok(_codePasteRepository.GetPaste(id));
}
[Route("pastes/{id}/raw")]
public IActionResult Raw(int id)
{
return Content(_codePasteRepository.GetPaste(id).Content, "text/plain");
}
}
}
| using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Modix.Services.CodePaste;
namespace Modix.WebServer.Controllers
{
[Route("~/api")]
public class PasteController : Controller
{
private ICodePasteRepository _codePasteRepository;
public PasteController(ICodePasteRepository codePasteRepository)
{
_codePasteRepository = codePasteRepository;
}
[Route("pastes")]
public IActionResult Index()
{
return Ok(_codePasteRepository.GetPastes().OrderByDescending(d=>d.Created).Take(10));
}
[Route("pastes/{id}")]
public IActionResult Index(int id)
{
return Ok(_codePasteRepository.GetPaste(id));
}
[Route("pastes/{id}/raw")]
public IActionResult Raw(int id)
{
return Content(_codePasteRepository.GetPaste(id).Content, "text/plain");
}
}
}
| mit | C# |
d76b350ca890cb951f50f344e65867af079eee01 | Add missing parameterless ctor for SubscriptionsForType | Abc-Arbitrage/Zebus.Directory,AtwooTM/Zebus,biarne-a/Zebus,rbouallou/Zebus,Abc-Arbitrage/Zebus | src/Abc.Zebus/Directory/SubscriptionsForType.cs | src/Abc.Zebus/Directory/SubscriptionsForType.cs | using Abc.Zebus.Routing;
using ProtoBuf;
namespace Abc.Zebus.Directory
{
[ProtoContract]
public class SubscriptionsForType
{
[ProtoMember(1, IsRequired = true)]
public readonly MessageTypeId MessageTypeId;
[ProtoMember(2, IsRequired = true)]
public readonly BindingKey[] BindingKeys;
public SubscriptionsForType(MessageTypeId messageTypeId, params BindingKey[] bindingKeys)
{
MessageTypeId = messageTypeId;
BindingKeys = bindingKeys;
}
public SubscriptionsForType(){}
}
} | using Abc.Zebus.Routing;
using ProtoBuf;
namespace Abc.Zebus.Directory
{
[ProtoContract]
public class SubscriptionsForType
{
[ProtoMember(1, IsRequired = true)]
public readonly MessageTypeId MessageTypeId;
[ProtoMember(2, IsRequired = true)]
public readonly BindingKey[] BindingKeys;
public SubscriptionsForType(MessageTypeId messageTypeId, params BindingKey[] bindingKeys)
{
MessageTypeId = messageTypeId;
BindingKeys = bindingKeys;
}
}
} | mit | C# |
4ebf9303e0a634652e8b9ece20ad7eaef9026771 | Address feedback | cdmihai/msbuild,AndyGerlicher/msbuild,sean-gilliam/msbuild,chipitsine/msbuild,chipitsine/msbuild,cdmihai/msbuild,cdmihai/msbuild,AndyGerlicher/msbuild,chipitsine/msbuild,cdmihai/msbuild,jeffkl/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,Microsoft/msbuild,mono/msbuild,AndyGerlicher/msbuild,mono/msbuild,Microsoft/msbuild,jeffkl/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,Microsoft/msbuild,mono/msbuild,jeffkl/msbuild,chipitsine/msbuild,AndyGerlicher/msbuild,rainersigwald/msbuild,rainersigwald/msbuild,mono/msbuild,jeffkl/msbuild,Microsoft/msbuild,sean-gilliam/msbuild | src/Build.UnitTests/Graph/ProjectGraph_Tests.cs | src/Build.UnitTests/Graph/ProjectGraph_Tests.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.IO;
using System.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.Build.UnitTests;
using Xunit;
using Shouldly;
namespace Microsoft.Build.Graph.UnitTests
{
public class ProjectgraphTests
{
[Fact]
public void TestGraphWithSingleNode()
{
string projectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<TestProperty>value</TestProperty>
</PropertyGroup>
<Target Name='Build'>
<Message Text='Building test project'/>
</Target>
</Project>
";
using (var env = TestEnvironment.Create())
{
TransientTestProjectWithFiles testProject =
env.CreateTestProjectWithFiles(projectContents, Array.Empty<string>());
var projectGraph = new ProjectGraph(testProject.ProjectFile);
projectGraph.ProjectNodes.Count.ShouldBe(1);
Project projectNode = projectGraph.ProjectNodes.First().Project;
projectNode.FullPath.ShouldBe(testProject.ProjectFile);
}
}
}
}
| // 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.IO;
using System.Linq;
using Microsoft.Build.Evaluation;
using Xunit;
namespace Microsoft.Build.Graph.UnitTests
{
public class ProjectGraphTests
{
[Fact]
public void TestGraphWithSingleNode()
{
string projectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<TestProperty>value</TestProperty>
</PropertyGroup>
<Target Name='Build'>
<Message Text='Building test project'/>
</Target>
</Project>
";
string testDirectory = Path.GetTempPath();
string projectPath = Path.Combine(testDirectory, "ProjectGraphTest.proj");
File.WriteAllText(projectPath, projectContents);
var projectGraph = new ProjectGraph(projectPath);
Assert.Equal(1, projectGraph.ProjectNodes.Count);
Project projectNode = projectGraph.ProjectNodes.First().Project;
Assert.Equal(projectPath, projectNode.FullPath);
}
}
}
| mit | C# |
56fb7bd89cb785cf4b2761c8ee87266c9974ee16 | Fix text on main page. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Views/Home/Index.cshtml | src/CompetitionPlatform/Views/Home/Index.cshtml | @model CompetitionPlatform.Models.ProjectViewModels.ProjectListIndexViewModel
@{
ViewData["Title"] = "Projects";
}
<section class="section section--lead section--padding">
<div class="container container--extend">
<h1 class="text-center page__title">Lykke<span>Streams</span></h1>
<h3 class="page__subtitle mb0">Here the great ideas meet bright minds</h3>
</div>
</section>
<section class="section section--competition_list">
<div class="container container--extend">
<div class="section_header">
<h3 class="section_header__title">Current Projects</h3>
</div>
</div>
</section>
<section id="projectListResults" class="section section--competition_list">
@await Html.PartialAsync("ProjectListPartial", Model)
</section>
| @model CompetitionPlatform.Models.ProjectViewModels.ProjectListIndexViewModel
@{
ViewData["Title"] = "Projects";
}
<section class="section section--lead section--padding">
<div class="container container--extend">
<h1 class="text-center page__title">Lykke<span>Streams</span></h1>
<h3 class="page__subtitle mb0">Here Great Ideas Meet the Brightest Minds</h3>
</div>
</section>
<section class="section section--competition_list">
<div class="container container--extend">
<div class="section_header">
<h3 class="section_header__title">Current Projects</h3>
</div>
</div>
</section>
<section id="projectListResults" class="section section--competition_list">
@await Html.PartialAsync("ProjectListPartial", Model)
</section>
| mit | C# |
abcbe5da55f3c6a4da9cadb252d660871745a856 | Fix compilation error in MembersList.cshtml. | GiveCampUK/GiveCRM,GiveCampUK/GiveCRM | src/GiveCRM.Web/Views/Member/MembersList.cshtml | src/GiveCRM.Web/Views/Member/MembersList.cshtml | @model PagedMemberListViewModel
@using GiveCRM.Web.Models.Members
@using PagedList.Mvc
@{
Layout = null;
}
<script src="@Url.Content("~/Scripts/ViewScripts/MemberList.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
MemberList.Initialise()
});
</script>
@if (Model != null && Model.Count > 0)
{
<table>
<tr>
<th> </th>
<th> </th>
<th> </th>
<th>Reference</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
@foreach (var member in Model)
{
<tr>
<td>@Html.ActionLink("Edit", "Edit", new { id = member.Id })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = member.Id })</td>
<td>@Html.ActionLink("Log Donation", "Donate", new { id = member.Id })</td>
<td>@member.Reference</td>
<td>@member.Salutation @member.FirstName @member.LastName</td>
<td>@member.AddressLine1 @member.AddressLine2 @member.City @member.PostalCode</td>
<td>@member.EmailAddress</td>
</tr>
}
<tr>
<td colspan="7" style="text-align: center">
<style type="text/css">
.PagedList-pager ul li
{
display: inline;
margin: 0 5px;
}
.PagedList-currentPage { font-weight: bold; }
.PagedList-currentPage a { color: Black; }
</style>
@Html.PagedListPager(Model, Model.PagingFunction, PagedListRenderOptions.OnlyShowFivePagesAtATime)
</td>
</tr>
</table>
}
else
{
<p>Your search returned no results.</p>
}
| @model PagedMemberListViewModel
@using GiveCRM.Web.Models.Members
@using PagedList.Mvc
@{
Layout = null;
}
<script src="@Url.Content("~/Scripts/ViewScripts/MemberList.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
MemberList.Initialise()
});
</script>
@if (Model != null && Model.Count > 0)
{
<table>
<tr>
<th> </th>
<th> </th>
<th> </th>
<th>Reference</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
@foreach (var member in Model)
{
<tr>
<td>@Html.ActionLink("Edit", "Edit", new { id = member.Id })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = member.Id } new { title = "ref_" + member.Reference })</td>
<td>@Html.ActionLink("Log Donation", "Donate", new { id = member.Id })</td>
<td>@member.Reference</td>
<td>@member.Salutation @member.FirstName @member.LastName</td>
<td>@member.AddressLine1 @member.AddressLine2 @member.City @member.PostalCode</td>
<td>@member.EmailAddress</td>
</tr>
}
<tr>
<td colspan="7" style="text-align: center">
<style type="text/css">
.PagedList-pager ul li
{
display: inline;
margin: 0 5px;
}
.PagedList-currentPage { font-weight: bold; }
.PagedList-currentPage a { color: Black; }
</style>
@Html.PagedListPager(Model, Model.PagingFunction, PagedListRenderOptions.OnlyShowFivePagesAtATime)
</td>
</tr>
</table>
}
else
{
<p>Your search returned no results.</p>
}
| mit | C# |
36743a02601d14d7b7d6fda52be49ff5f4ac5c27 | use _logger not logger | SkillsFundingAgency/vacancy-register-api,SkillsFundingAgency/vacancy-register-api,SkillsFundingAgency/vacancy-register-api | src/Esfa.Vacancy.Register.Api/Global.asax.cs | src/Esfa.Vacancy.Register.Api/Global.asax.cs | using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Esfa.Vacancy.Register.Api.App_Start;
using SFA.DAS.NLog.Logger;
namespace Esfa.Vacancy.Register.Api
{
public class Global : HttpApplication
{
private ILog _logger;
public Global()
{
_logger = DependencyResolver.Current.GetService<ILog>();
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
MvcHandler.DisableMvcResponseHeader = true;
_logger.Info("Starting Web Role");
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
AutoMapperConfig.Configure();
_logger.Info("Web Role started");
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
application?.Context?.Response.Headers.Remove("Server");
}
protected void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError().GetBaseException();
_logger.Error(ex, "App_Error");
}
}
} | using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Esfa.Vacancy.Register.Api.App_Start;
using SFA.DAS.NLog.Logger;
namespace Esfa.Vacancy.Register.Api
{
public class Global : HttpApplication
{
private ILog _logger;
public Global()
{
_logger = DependencyResolver.Current.GetService<ILog>();
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
MvcHandler.DisableMvcResponseHeader = true;
var logger = DependencyResolver.Current.GetService<ILog>();
logger.Info("Starting Web Role");
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
AutoMapperConfig.Configure();
logger.Info("Web Role started");
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
application?.Context?.Response.Headers.Remove("Server");
}
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
var logger = DependencyResolver.Current.GetService<ILog>();
logger.Error(ex, "App_Error");
}
}
} | mit | C# |
7ac47bab671359d3e6327253d519107a866371a1 | Bump up version 2.4.0 | rickyah/ini-parser,rickyah/ini-parser | src/IniFileParser/Properties/AssemblyInfo.cs | src/IniFileParser/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("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.4.0")]
[assembly: AssemblyFileVersion("2.4.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("INIParser")]
[assembly: AssemblyDescription("A simple INI file processing library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("INIParser")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.3.0")]
[assembly: AssemblyFileVersion("2.3.0")] | mit | C# |
40012a0e13c7bab8d3b2d49f4e52910c9bb52233 | Use the same version as native. | alesliehughes/monoDX,alesliehughes/monoDX | Microsoft.DirectX.Direct3D/AssemblyInfo.cs | Microsoft.DirectX.Direct3D/AssemblyInfo.cs | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyTitle("Microsoft.DirectX.Direct3D")]
[assembly: AssemblyDescription("Replacement for Microsoft managed DirectX layer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.2902.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
| /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyTitle("Microsoft.DirectX.Direct3D")]
[assembly: AssemblyDescription("Replacement for Microsoft managed DirectX layer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("2.0.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
| mit | C# |
9bb5b56c1774b1b78a61b8ce30c87be4cfec4b36 | Update copyright info | frabert/SharpPhysFS | SharpPhysFS/Properties/AssemblyInfo.cs | SharpPhysFS/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("SharpPhysFS")]
[assembly: AssemblyDescription("Managed wrapper around PhysFS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Francesco Bertolaccini")]
[assembly: AssemblyProduct("SharpPhysFS")]
[assembly: AssemblyCopyright("Copyright © 2016 Francesco Bertolaccini")]
[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("1e8d0656-fbd5-4f97-b634-584943b13af2")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.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("SharpPhysFS")]
[assembly: AssemblyDescription("Managed wrapper around PhysFS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Francesco Bertolaccini")]
[assembly: AssemblyProduct("SharpPhysFS")]
[assembly: AssemblyCopyright("Copyright © 2015 Francesco Bertolaccini")]
[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("1e8d0656-fbd5-4f97-b634-584943b13af2")]
// 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.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
| mit | C# |
9280be76ea8507c5c36c8bd2133a4ae70b74f0f2 | Update version 2.8.3 | paralin/D2ModdinClient,paralin/D2ModdinClient | ClientCommon/Version.cs | ClientCommon/Version.cs | namespace ClientCommon
{
public class Version
{
public const string ClientVersion = "2.8.3";
}
} | namespace ClientCommon
{
public class Version
{
public const string ClientVersion = "2.8.2";
}
} | apache-2.0 | C# |
56d258e2915e3c1a97d6397aca90171f590c8f17 | Fix the EF causing issues identity framework | kmlprtsng/MvcGenericProjectTemplate,kmlprtsng/MvcGenericProjectTemplate,kmlprtsng/MvcGenericProjectTemplate | Project.Data/ProjectContext.cs | Project.Data/ProjectContext.cs | using Microsoft.AspNet.Identity.EntityFramework;
using Project.Data.Configuration;
using System.Data.Entity;
using Project.Domain.Entities;
namespace Project.Data
{
public class ProjectContext : IdentityDbContext<ApplicationUser>
{
public ProjectContext() : base("ProjectContext") { }
public DbSet<Gadget> Gadgets { get; set; }
public DbSet<Category> Categories { get; set; }
public virtual void Commit()
{
base.SaveChanges();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new GadgetConfiguration());
modelBuilder.Configurations.Add(new CategoryConfiguration());
}
public static ProjectContext Create()
{
return new ProjectContext();
}
}
}
| using System;
using Microsoft.AspNet.Identity.EntityFramework;
using Project.Data.Configuration;
using System.Data.Entity;
using Project.Domain.Entities;
namespace Project.Data
{
public class ProjectContext : IdentityDbContext<ApplicationUser>
{
public ProjectContext() : base("ProjectContext") { }
public DbSet<Gadget> Gadgets { get; set; }
public DbSet<Category> Categories { get; set; }
public virtual void Commit()
{
base.SaveChanges();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new GadgetConfiguration());
modelBuilder.Configurations.Add(new CategoryConfiguration());
}
public static ProjectContext Create()
{
return new ProjectContext();
}
}
}
| mit | C# |
66f95013ac9b172872a7a32fec733d89219b41fc | Remove unused import | MHeasell/Mappy,MHeasell/Mappy | Mappy/Collections/Grid.cs | Mappy/Collections/Grid.cs | namespace Mappy.Collections
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Grid<T> : IGrid<T>
{
private readonly T[] arr;
public Grid(int width, int height)
{
this.Width = width;
this.Height = height;
this.arr = new T[width * height];
}
public int Width { get; private set; }
public int Height { get; private set; }
public T this[int index]
{
get
{
return this.arr[index];
}
set
{
this.arr[index] = value;
}
}
public T this[int x, int y]
{
get
{
return this.arr[this.ToIndex(x, y)];
}
set
{
this.arr[this.ToIndex(x, y)] = value;
}
}
public IEnumerator<T> GetEnumerator()
{
return this.arr.Cast<T>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.arr.GetEnumerator();
}
}
}
| namespace Mappy.Collections
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Grid<T> : IGrid<T>
{
private readonly T[] arr;
public Grid(int width, int height)
{
this.Width = width;
this.Height = height;
this.arr = new T[width * height];
}
public int Width { get; private set; }
public int Height { get; private set; }
public T this[int index]
{
get
{
return this.arr[index];
}
set
{
this.arr[index] = value;
}
}
public T this[int x, int y]
{
get
{
return this.arr[this.ToIndex(x, y)];
}
set
{
this.arr[this.ToIndex(x, y)] = value;
}
}
public IEnumerator<T> GetEnumerator()
{
return this.arr.Cast<T>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.arr.GetEnumerator();
}
}
}
| mit | C# |
805a2febfe4a4e48a4663487ea775aedf352aa90 | Update ConfigReader.cs | AnkRaiza/cordova-plugin-config-reader,AnkRaiza/cordova-plugin-config-reader,AnkRaiza/cordova-plugin-config-reader | src/wp8/ConfigReader.cs | src/wp8/ConfigReader.cs | using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;
namespace WPCordovaClassLib.Cordova.Commands
{
public class ConfigReader : BaseCommand
{
public async void get(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
string aliasCurrentCommandCallbackId = args[2];
try
{
// Get the file.
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(args[0]);
// Launch the bug query file.
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{result:\"data\"}"));
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), aliasCurrentCommandCallbackId);
}
}
}
}
| using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Windows.Storage;
using System.Diagnostics;
using System.IO;
namespace WPCordovaClassLib.Cordova.Commands
{
public class ConfigReader : BaseCommand
{
public async void open(string options)
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
string aliasCurrentCommandCallbackId = args[2];
try
{
// Get the file.
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(args[0]);
// Launch the bug query file.
await Windows.System.Launcher.LaunchFileAsync(file);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{result:\"data\"}"));
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), aliasCurrentCommandCallbackId);
}
}
}
}
| mit | C# |
10b1738753031921c321464f5f50db0ecfd2e82a | Build and publish nuget package | QuickenLoans/XSerializer | XSerializer/Properties/AssemblyInfo.cs | XSerializer/Properties/AssemblyInfo.cs | using System;
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("XSerializer")]
[assembly: AssemblyDescription("Advanced, high-performance XML and JSON serializers")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-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("5aeaebd0-35de-424c-baa9-ba6d65fa3409")]
[assembly: CLSCompliant(true)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.3.7")]
[assembly: AssemblyInformationalVersion("0.3.7")]
#if !BUILD
[assembly: InternalsVisibleTo("XSerializer.Tests")]
[assembly: InternalsVisibleTo("XSerializer.PerformanceTests")]
#endif | using System;
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("XSerializer")]
[assembly: AssemblyDescription("Advanced, high-performance XML and JSON serializers")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("XSerializer")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-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("5aeaebd0-35de-424c-baa9-ba6d65fa3409")]
[assembly: CLSCompliant(true)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.3.6")]
[assembly: AssemblyInformationalVersion("0.3.6")]
#if !BUILD
[assembly: InternalsVisibleTo("XSerializer.Tests")]
[assembly: InternalsVisibleTo("XSerializer.PerformanceTests")]
#endif | mit | C# |
5cf559e4a28ea629f5b101cd4fcee831d8fb05d4 | Update JoinExtensions.cs | keith-hall/Extensions,keith-hall/Extensions | src/JoinExtensions.cs | src/JoinExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
public static class JoinExtensions
{
public static IEnumerable<Tuple<TLeft, TRight>> LeftJoinEach<TLeft, TRight, TJoin>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TJoin> leftJoinOn, Func<TRight, TJoin> rightJoinOn)
{
var j = from l in left
join r in right on leftJoinOn(l) equals rightJoinOn(r) into gj
from jr in gj.DefaultIfEmpty()
select Tuple.Create(l, jr);
return j;
}
public static IEnumerable<Tuple<TLeft, IEnumerable<TRight>>> LeftJoinAll<TLeft, TRight, TJoin>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TJoin> leftJoinOn, Func<TRight, TJoin> rightJoinOn)
{
var j = from l in left
join r in right on leftJoinOn(l) equals rightJoinOn(r) into gj
select Tuple.Create(l, gj.DefaultIfEmpty());
return j;
}
}
| public static class JoinExtensions {
public static IEnumerable<Tuple<TLeft, TRight>> LeftJoinEach<TLeft, TRight, TJoin> (this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TJoin> leftJoinOn, Func<TRight, TJoin> rightJoinOn) {
var j = from l in left
join r in right on leftJoinOn(l) equals rightJoinOn(r) into gj
from jr in gj.DefaultIfEmpty()
select Tuple.Create(l, jr);
return j;
}
public static IEnumerable<Tuple<TLeft, IEnumerable<TRight>>> LeftJoinAll<TLeft, TRight, TJoin> (this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TJoin> leftJoinOn, Func<TRight, TJoin> rightJoinOn) {
var j = from l in left
join r in right on leftJoinOn(l) equals rightJoinOn(r) into gj
select Tuple.Create(l, gj.DefaultIfEmpty());
return j;
}
}
| apache-2.0 | C# |
db578cc8d5c201e99d8c9813a7ee73aebffa480f | Add option to supply error code in Win32ErrorMessage.SetLast() | kostaslamda/win-installer,xenserver/win-installer,OwenSmith/win-installer,OwenSmith/win-installer,OwenSmith/win-installer,xenserver/win-installer,xenserver/win-installer,benchalmers/win-installer,kostaslamda/win-installer,kostaslamda/win-installer,OwenSmith/win-installer,xenserver/win-installer,kostaslamda/win-installer,OwenSmith/win-installer,benchalmers/win-installer,xenserver/win-installer,kostaslamda/win-installer,benchalmers/win-installer,benchalmers/win-installer,benchalmers/win-installer | src/InstallAgent/PInvoke/Win32ErrorMessage.cs | src/InstallAgent/PInvoke/Win32ErrorMessage.cs | using System.ComponentModel;
using System.Runtime.InteropServices;
namespace PInvoke
{
public static class Win32ErrorMessage
{
private static string message;
public static string GetLast()
{
return message;
}
public static void SetLast(string win32FuncName, int err = -1)
{
if (err == -1)
{
err = Marshal.GetLastWin32Error();
}
message =
win32FuncName + " failed; Error " + err +
": " + new Win32Exception(err).Message;
}
}
}
| using System.ComponentModel;
using System.Runtime.InteropServices;
namespace PInvoke
{
public static class Win32ErrorMessage
{
private static string message;
public static string GetLast()
{
return message;
}
public static void SetLast(string win32FuncName)
{
int err = Marshal.GetLastWin32Error();
message =
win32FuncName + " failed; Error " + err +
": " + new Win32Exception(err).Message;
}
}
}
| bsd-2-clause | C# |
6e7456605d4625dfd4eb9e9a200fdd95b120ec05 | Allow custom handling of chat command response | TorchAPI/Torch | Torch/Commands/CommandContext.cs | Torch/Commands/CommandContext.cs | using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Sandbox.Engine.Networking;
using Sandbox.Game.Multiplayer;
using Torch.API;
using Torch.API.Managers;
using Torch.API.Plugins;
using VRage.Game;
using VRage.Game.ModAPI;
namespace Torch.Commands
{
public class CommandContext
{
/// <summary>
/// The plugin that added this command.
/// </summary>
public ITorchPlugin Plugin { get; }
/// <summary>
/// The current Torch instance.
/// </summary>
public ITorchBase Torch { get; }
/// <summary>
/// The player who ran the command, or null if the server sent it.
/// </summary>
public IMyPlayer Player => Torch.CurrentSession.KeenSession.Players.TryGetPlayerBySteamId(_steamIdSender);
/// <summary>
/// Was this message sent by this program.
/// </summary>
public bool SentBySelf => _steamIdSender == Sync.MyId;
private ulong _steamIdSender;
/// <summary>
/// The command arguments split by spaces and quotes. Ex. "this is" a command -> {this is, a, command}
/// </summary>
public List<string> Args { get; }
/// <summary>
/// The non-split argument string.
/// </summary>
public string RawArgs { get; }
public CommandContext(ITorchBase torch, ITorchPlugin plugin, ulong steamIdSender, string rawArgs = null,
List<string> args = null)
{
Torch = torch;
Plugin = plugin;
_steamIdSender = steamIdSender;
RawArgs = rawArgs;
Args = args ?? new List<string>();
}
public virtual void Respond(string message, string sender = "Server", string font = MyFontEnum.Blue)
{
Torch.CurrentSession.Managers.GetManager<IChatManagerServer>()
?.SendMessageAsOther(sender, message, font, _steamIdSender);
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Sandbox.Engine.Networking;
using Sandbox.Game.Multiplayer;
using Torch.API;
using Torch.API.Managers;
using Torch.API.Plugins;
using VRage.Game;
using VRage.Game.ModAPI;
namespace Torch.Commands
{
public class CommandContext
{
/// <summary>
/// The plugin that added this command.
/// </summary>
public ITorchPlugin Plugin { get; }
/// <summary>
/// The current Torch instance.
/// </summary>
public ITorchBase Torch { get; }
/// <summary>
/// The player who ran the command, or null if the server sent it.
/// </summary>
public IMyPlayer Player => Torch.CurrentSession.KeenSession.Players.TryGetPlayerBySteamId(_steamIdSender);
/// <summary>
/// Was this message sent by this program.
/// </summary>
public bool SentBySelf => _steamIdSender == Sync.MyId;
private ulong _steamIdSender;
/// <summary>
/// The command arguments split by spaces and quotes. Ex. "this is" a command -> {this is, a, command}
/// </summary>
public List<string> Args { get; }
/// <summary>
/// The non-split argument string.
/// </summary>
public string RawArgs { get; }
public CommandContext(ITorchBase torch, ITorchPlugin plugin, ulong steamIdSender, string rawArgs = null,
List<string> args = null)
{
Torch = torch;
Plugin = plugin;
_steamIdSender = steamIdSender;
RawArgs = rawArgs;
Args = args ?? new List<string>();
}
public void Respond(string message, string sender = "Server", string font = MyFontEnum.Blue)
{
Torch.CurrentSession.Managers.GetManager<IChatManagerServer>()
?.SendMessageAsOther(sender, message, font, _steamIdSender);
}
}
} | apache-2.0 | C# |
d96aeeb152ff51b2afe0b7cd541a9ca87a93494e | fix - to_array return input if input.type == array | jdevillard/JmesPath.Net | src/jmespath.net/Functions/ToArrayFunction.cs | src/jmespath.net/Functions/ToArrayFunction.cs | using System;
using DevLab.JmesPath.Expressions;
using Newtonsoft.Json.Linq;
using JmesPathFunction = DevLab.JmesPath.Interop.JmesPathFunction;
namespace DevLab.JmesPath.Functions
{
public class ToArrayFunction : JmesPathFunction
{
public ToArrayFunction()
: base("to_array", 1)
{
}
public override bool Validate(params JmesPathArgument[] args)
{
return true;
}
public override JToken Execute(params JmesPathArgument[] args)
{
var arg = args[0].AsJToken();
if (arg.Type == JTokenType.Array)
return arg;
return new JArray(arg);
}
}
} | using System;
using DevLab.JmesPath.Expressions;
using Newtonsoft.Json.Linq;
using JmesPathFunction = DevLab.JmesPath.Interop.JmesPathFunction;
namespace DevLab.JmesPath.Functions
{
public class ToArrayFunction : JmesPathFunction
{
public ToArrayFunction()
: base("to_array", 1)
{
}
public override bool Validate(params JmesPathArgument[] args)
{
return true;
}
public override JToken Execute(params JmesPathArgument[] args)
{
return new JArray(args[0].AsJToken());
}
}
} | apache-2.0 | C# |
759ebc5991f13cb680c591625c4393489fc0c443 | Remove unnecessary library | andrewjleavitt/SpaceThing | Assets/Scripts/ShieldBehavior.cs | Assets/Scripts/ShieldBehavior.cs | using UnityEngine;
public class ShieldBehavior {
public float amount = 0.0f;
public float rechargeAmount = 0.0f;
public float rechargeRate = 0.0f;
private float capacity = 0.0f;
private float nextRecharge = 0.0f;
private string shieldName;
public ShieldBehavior(string newShieldName, float newCapacity, float newRechargeAmount, float rechargeRate) {
shieldName = newShieldName;
capacity = newCapacity;
rechargeAmount = newRechargeAmount;
rechargeRate = newRechargeAmount;
amount = capacity;
}
public void Recharge() {
if (amount == capacity) {
return;
}
if (Time.time < nextRecharge) {
return;
}
amount += rechargeAmount;
nextRecharge = Time.time + rechargeRate;
}
public string Status() {
return amount.ToString();
}
}
| using System;
using UnityEngine;
public class ShieldBehavior {
public float amount = 0.0f;
public float rechargeAmount = 0.0f;
public float rechargeRate = 0.0f;
private float capacity = 0.0f;
private float nextRecharge = 0.0f;
private string shieldName;
public ShieldBehavior(string newShieldName, float newCapacity, float newRechargeAmount, float rechargeRate) {
shieldName = newShieldName;
capacity = newCapacity;
rechargeAmount = newRechargeAmount;
rechargeRate = newRechargeAmount;
amount = capacity;
}
public void Recharge() {
if (amount == capacity) {
return;
}
if (Time.time < nextRecharge) {
return;
}
amount += rechargeAmount;
nextRecharge = Time.time + rechargeRate;
}
public string Status() {
return amount.ToString();
}
}
| unlicense | C# |
284ba9ed38e24a15a3657954cbcb45a050425302 | Update GetMerchantDetails.cs | devkale/sample-code-csharp,AuthorizeNet/sample-code-csharp | TransactionReporting/GetMerchantDetails.cs | TransactionReporting/GetMerchantDetails.cs | using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Controllers.Bases;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace net.authorize.sample
{
class GetMerchantDetails
{
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey)
{
Console.WriteLine("Get Merchant Details Sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
var request = new getMerchantDetailsRequest
{
merchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, Item = ApiTransactionKey, ItemElementName = ItemChoiceType.transactionKey }
};
// instantiate the controller that will call the service
var controller = new getMerchantDetailsController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
// validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
Console.WriteLine("Merchant Name: " + response.merchantName);
Console.WriteLine("Gateway ID: " + response.gatewayId);
Console.Write("Processors: ");
foreach (processorType processor in response.processors)
{
Console.Write(processor.name + "; ");
}
}
else
{
Console.WriteLine("Failed to get merchant details.");
}
}
else
{
Console.WriteLine("Null Response.");
}
return response;
}
}
}
| using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Controllers.Bases;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace net.authorize.sample.TransactionReporting
{
class GetMerchantDetails
{
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey)
{
Console.WriteLine("Get Merchant Details Sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
var request = new getMerchantDetailsRequest
{
merchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, Item = ApiTransactionKey, ItemElementName = ItemChoiceType.transactionKey }
};
// instantiate the controller that will call the service
var controller = new getMerchantDetailsController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
// validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
Console.WriteLine("Merchant Name: " + response.merchantName);
Console.WriteLine("Gateway ID: " + response.gatewayId);
Console.Write("Processors: ");
foreach (processorType processor in response.processors)
{
Console.Write(processor.name + "; ");
}
}
else
{
Console.WriteLine("Failed to get merchant details.");
}
}
else
{
Console.WriteLine("Null Response.");
}
return response;
}
}
} | mit | C# |
081cf6c59f8b6526029070288d16b609336f13da | Add Response Bad Request on Detail Page | krprasert/tdd-carfuel,krprasert/tdd-carfuel,krprasert/tdd-carfuel | carfuel/Controllers/CarsController.cs | carfuel/Controllers/CarsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
namespace CarFuel.Controllers {
public class CarsController : Controller {
private ICarDb db;
private CarService carService;
public CarsController() {
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index() {
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create() {
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item) {
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex){
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid id)
{
if( id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
namespace CarFuel.Controllers {
public class CarsController : Controller {
private ICarDb db;
private CarService carService;
public CarsController() {
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index() {
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create() {
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item) {
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex){
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid id)
{
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
} | mit | C# |
9d388c96e1ff833d211428d93f70d282bf1ac6bb | Add fields for #4567 | dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk | SnapMD.ConnectedCare.ApiModels/HospitalInfo.cs | SnapMD.ConnectedCare.ApiModels/HospitalInfo.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SnapMD.ConnectedCare.ApiModels
{
public class HospitalInfo
{
public int HospitalId { get; set; }
public string HospitalName { get; set; }
public string ContactPerson { get; set; }
public string Email { get; set; }
public string HospitalImage { get; set; }
public string ContactNumber { get; set; }
public string IsActive { get; set; }
public string HospitalCode { get; set; }
public string BrandName { get; set; }
public string BrandTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public int? StateId { get; set; }
public double? ConsultationCharge { get; set; }
public string HospitalDomainName { get; set; }
public string BrandColor { get; set; }
public string ITDepartmentContactNumber { get; set; }
public string AppointmentsContactNumber { get; set; }
public string Locale { get; set; }
public string PatientLogin { get; set; }
public string PatientConsultEndUrl { get; set; }
public virtual IEnumerable<HospitalHours> OperatingHours { get; set; }
public List<string> EnabledModules { get; set; }
/// <summary>
/// Allowed values: No/Optional/Manditory ... todo: Create enum
/// </summary>
public string CustomerSso { get; set; }
public string CustomerSsoLinkText { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SnapMD.ConnectedCare.ApiModels
{
public class HospitalInfo
{
public int HospitalId { get; set; }
public string HospitalName { get; set; }
public string ContactPerson { get; set; }
public string Email { get; set; }
public string HospitalImage { get; set; }
public string ContactNumber { get; set; }
public string IsActive { get; set; }
public string HospitalCode { get; set; }
public string BrandName { get; set; }
public string BrandTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public int? StateId { get; set; }
public double? ConsultationCharge { get; set; }
public string HospitalDomainName { get; set; }
public string BrandColor { get; set; }
public string ITDepartmentContactNumber { get; set; }
public string AppointmentsContactNumber { get; set; }
public string Locale { get; set; }
public string PatientLogin { get; set; }
public string PatientConsultEndUrl { get; set; }
public virtual IEnumerable<HospitalHours> OperatingHours { get; set; }
public List<string> EnabledModules { get; set; }
}
}
| apache-2.0 | C# |
8ff584a61deeec44044fdd8fbfdbf73edc545576 | Update Version to 1.5.1 | Spryng/SpryngApiHttpDotNet | SpryngApiHttpDotNet/Properties/AssemblyInfo.cs | SpryngApiHttpDotNet/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("SpryngHttpApiDotNet")]
[assembly: AssemblyDescription("Spryng Http Api .NET Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Spryng")]
[assembly: AssemblyProduct("SpryngHttpApiDotNet")]
[assembly: AssemblyCopyright("Spryng © 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("678f2f8b-1255-4b87-b170-b35bbe5b2d4a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.1.0")]
[assembly: AssemblyFileVersion("1.5.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("SpryngHttpApiDotNet")]
[assembly: AssemblyDescription("Spryng Http Api .NET Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Spryng")]
[assembly: AssemblyProduct("SpryngHttpApiDotNet")]
[assembly: AssemblyCopyright("Spryng © 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("678f2f8b-1255-4b87-b170-b35bbe5b2d4a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
| bsd-2-clause | C# |
432ff5efabdd754058b5ca73c5f3244271ea254c | Update AdDuplexAdUnitBundle.cs | tiksn/TIKSN-Framework | TIKSN.Core/Advertising/AdDuplexAdUnitBundle.cs | TIKSN.Core/Advertising/AdDuplexAdUnitBundle.cs | namespace TIKSN.Advertising
{
public class AdDuplexAdUnitBundle : AdUnitBundle
{
public AdDuplexAdUnitBundle(string applicationId, string adUnitId)
: base(
new AdUnit(AdProviders.AdDuplex, applicationId, adUnitId, true),
new AdUnit(AdProviders.AdDuplex, applicationId, adUnitId))
{
}
}
}
| namespace TIKSN.Advertising
{
public class AdDuplexAdUnitBundle : AdUnitBundle
{
public AdDuplexAdUnitBundle(string applicationId, string adUnitId)
: base(
new AdUnit(AdProviders.AdDuplex, applicationId, adUnitId, true),
new AdUnit(AdProviders.AdDuplex, applicationId, adUnitId))
{
}
}
} | mit | C# |
a57e7262784bafb49ac23f9b90c1c7897044e249 | Undo a change which causes compiler error in .NET 4.0 (but not .NET 4.5 | OneGet/nuget,oliver-feng/nuget,OneGet/nuget,ctaggart/nuget,zskullz/nuget,jholovacs/NuGet,xoofx/NuGet,jmezach/NuGet2,oliver-feng/nuget,antiufo/NuGet2,mrward/nuget,akrisiun/NuGet,indsoft/NuGet2,jmezach/NuGet2,jmezach/NuGet2,rikoe/nuget,indsoft/NuGet2,rikoe/nuget,oliver-feng/nuget,atheken/nuget,zskullz/nuget,mrward/NuGet.V2,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,GearedToWar/NuGet2,xoofx/NuGet,dolkensp/node.net,mrward/NuGet.V2,oliver-feng/nuget,mrward/nuget,mrward/NuGet.V2,pratikkagda/nuget,oliver-feng/nuget,mono/nuget,mono/nuget,GearedToWar/NuGet2,rikoe/nuget,antiufo/NuGet2,mrward/nuget,indsoft/NuGet2,themotleyfool/NuGet,mrward/nuget,GearedToWar/NuGet2,zskullz/nuget,xoofx/NuGet,RichiCoder1/nuget-chocolatey,kumavis/NuGet,zskullz/nuget,ctaggart/nuget,jholovacs/NuGet,jmezach/NuGet2,chocolatey/nuget-chocolatey,mono/nuget,pratikkagda/nuget,ctaggart/nuget,OneGet/nuget,jmezach/NuGet2,chocolatey/nuget-chocolatey,alluran/node.net,mrward/NuGet.V2,atheken/nuget,alluran/node.net,dolkensp/node.net,themotleyfool/NuGet,mrward/NuGet.V2,mrward/nuget,chocolatey/nuget-chocolatey,OneGet/nuget,ctaggart/nuget,pratikkagda/nuget,antiufo/NuGet2,GearedToWar/NuGet2,alluran/node.net,themotleyfool/NuGet,chocolatey/nuget-chocolatey,xoofx/NuGet,xoofx/NuGet,jholovacs/NuGet,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,anurse/NuGet,antiufo/NuGet2,anurse/NuGet,pratikkagda/nuget,jholovacs/NuGet,RichiCoder1/nuget-chocolatey,kumavis/NuGet,chester89/nugetApi,akrisiun/NuGet,antiufo/NuGet2,GearedToWar/NuGet2,pratikkagda/nuget,jholovacs/NuGet,GearedToWar/NuGet2,indsoft/NuGet2,rikoe/nuget,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,mrward/nuget,pratikkagda/nuget,jmezach/NuGet2,jholovacs/NuGet,alluran/node.net,chester89/nugetApi,xoofx/NuGet,mono/nuget,oliver-feng/nuget,dolkensp/node.net,indsoft/NuGet2,mrward/NuGet.V2,dolkensp/node.net | src/CommandLine/Common/AggregateRepositoryHelper.cs | src/CommandLine/Common/AggregateRepositoryHelper.cs | using System.Collections.Generic;
using System.Linq;
namespace NuGet.Common
{
public static class AggregateRepositoryHelper
{
public static AggregateRepository CreateAggregateRepositoryFromSources(IPackageRepositoryFactory factory, IPackageSourceProvider sourceProvider, IEnumerable<string> sources)
{
AggregateRepository repository;
if (sources != null && sources.Any())
{
var repositories = sources.Select(s => sourceProvider.ResolveSource(s))
.Select(factory.CreateRepository)
.ToList();
repository = new AggregateRepository(repositories);
}
else
{
repository = sourceProvider.GetAggregate(factory, ignoreFailingRepositories: true);
}
return repository;
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace NuGet.Common
{
public static class AggregateRepositoryHelper
{
public static AggregateRepository CreateAggregateRepositoryFromSources(IPackageRepositoryFactory factory, IPackageSourceProvider sourceProvider, IEnumerable<string> sources)
{
AggregateRepository repository;
if (sources != null && sources.Any())
{
var repositories = sources.Select(sourceProvider.ResolveSource)
.Select(factory.CreateRepository)
.ToList();
repository = new AggregateRepository(repositories);
}
else
{
repository = sourceProvider.GetAggregate(factory, ignoreFailingRepositories: true);
}
return repository;
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.