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 |
|---|---|---|---|---|---|---|---|---|
c34819d885f7e359f8e08e189fa767b1f2500ba2
|
Fix stock firmware support detection
|
blackmamba97/Transformer-Toolkit
|
Toolkit/Classes/Device.cs
|
Toolkit/Classes/Device.cs
|
/*
* Device.cs - Developed by Max Röhrl for Transformer Toolkit
*/
using System;
using System.Linq;
namespace Toolkit
{
public class Device
{
/// <summary>
/// Android version of the latest Asus firmware for TF700T/TF300T/ME301T
/// </summary>
private const string MinAndroidVersion = "4.2.1";
/// <summary>
/// List of supported devices
/// </summary>
private static readonly string[] SupportedDevices = { "tf700t", "tf300t", "me301t", "hammerhead", "hammerheadcaf" };
public string SerialNumber { get; }
public string DeviceName { get; }
public string CodeName { get; }
public string AndroidVersion { get; }
public bool Supported { get; }
public bool OutdatedFirmware { get; }
public bool Rooted { get; }
public Device(string serialNumber, StartDialog startDialog)
{
SerialNumber = serialNumber;
DeviceName = Adb.GetBuildProperty("ro.product.model", this);
if (string.IsNullOrEmpty(DeviceName))
{
startDialog.ShowErrorMessageBox($"The informations about the connected device with the serial number \"{SerialNumber}\" "
+ "could not be fetched. Please follow the instructions to setup USB debugging.");
}
else
{
CodeName = Adb.GetBuildProperty("ro.build.product", this);
AndroidVersion = Adb.GetBuildProperty("ro.build.version.release", this);
Supported = SupportedDevices.Contains(CodeName.ToLower());
OutdatedFirmware = Convert.ToInt32(AndroidVersion.Replace(".", string.Empty))
< Convert.ToInt32(MinAndroidVersion.Replace(".", string.Empty));
string suOutput = Adb.ExecuteAdbShellCommand("su -v", this);
Rooted = !(suOutput.Contains("not found") || suOutput.Contains("permission denied"));
}
}
}
}
|
/*
* Device.cs - Developed by Max Röhrl for Transformer Toolkit
*/
using System;
using System.Linq;
namespace Toolkit
{
public class Device
{
/// <summary>
/// Android version of the latest Asus firmware for TF700T/TF300T/ME301T
/// </summary>
private const string MinAndroidVersion = "4.2.1";
/// <summary>
/// List of supported devices
/// </summary>
private static readonly string[] SupportedDevices = { "tf700t", "tf300t", "me301t", "hammerhead", "hammerheadcaf" };
public string SerialNumber { get; }
public string DeviceName { get; }
public string CodeName { get; }
public string AndroidVersion { get; }
public bool Supported { get; }
public bool OutdatedFirmware { get; }
public bool Rooted { get; }
public Device(string serialNumber, StartDialog startDialog)
{
SerialNumber = serialNumber;
DeviceName = Adb.GetBuildProperty("ro.product.model", this);
if (string.IsNullOrEmpty(DeviceName))
{
startDialog.ShowErrorMessageBox($"The informations about the connected device with the serial number \"{SerialNumber}\" "
+ "could not be fetched. Please follow the instructions to setup USB debugging.");
}
else
{
CodeName = Adb.GetBuildProperty("ro.build.product", this);
AndroidVersion = Adb.GetBuildProperty("ro.build.version.release", this);
Supported = SupportedDevices.Contains(CodeName);
OutdatedFirmware = Convert.ToInt32(AndroidVersion.Replace(".", string.Empty))
< Convert.ToInt32(MinAndroidVersion.Replace(".", string.Empty));
string suOutput = Adb.ExecuteAdbShellCommand("su -v", this);
Rooted = !(suOutput.Contains("not found") || suOutput.Contains("permission denied"));
}
}
}
}
|
mit
|
C#
|
237d722580d347f190b00cbd3dd7f2aaef9a6ff1
|
trim down error page
|
mzrimsek/scheduler,mzrimsek/scheduler,mzrimsek/scheduler
|
Views/Shared/Error.cshtml
|
Views/Shared/Error.cshtml
|
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>
|
mit
|
C#
|
e8623db1f737ba2fbaa6a26738dba2c12f931cfc
|
Add AUID documentation
|
HelloKitty/GladNet2,HelloKitty/GladNet2.0,HelloKitty/GladNet2,HelloKitty/GladNet2.0
|
src/GladNet.Common/Network/Peer/Connection/IConnectionDetails.cs
|
src/GladNet.Common/Network/Peer/Connection/IConnectionDetails.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace GladNet.Common
{
/// <summary>
/// Connection details describing the remote and local peer details.
/// </summary>
public interface IConnectionDetails
{
/// <summary>
/// IPAddress of the remote peer.
/// </summary>
IPAddress RemoteIP { get; }
/// <summary>
/// Remote port of the peer.
/// </summary>
int RemotePort { get; }
/// <summary>
/// Local port the peer is connecting on.
/// </summary>
int LocalPort { get; }
//https://github.com/HelloKitty/GladNet2.Specifications/blob/master/Routing/AUIDSpecification.md
/// <summary>
/// Application Unique ID (AUID) of the peer.
/// </summary>
int ConnectionID { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace GladNet.Common
{
/// <summary>
/// Connection details describing the remote and local peer details.
/// </summary>
public interface IConnectionDetails
{
/// <summary>
/// IPAddress of the remote peer.
/// </summary>
IPAddress RemoteIP { get; }
/// <summary>
/// Remote port of the peer.
/// </summary>
int RemotePort { get; }
/// <summary>
/// Local port the peer is connecting on.
/// </summary>
int LocalPort { get; }
/// <summary>
/// Connection ID of the peer. (unique per port)
/// </summary>
int ConnectionID { get; }
}
}
|
bsd-3-clause
|
C#
|
b4417e3bd6275b84e188cbe438ba6e9c50bbe95a
|
Support loading bitmaps from resources.
|
SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,punker76/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,MrDaedra/Avalonia,MrDaedra/Avalonia,jazzay/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,OronDF343/Avalonia,SuperJMN/Avalonia,OronDF343/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,susloparovdenis/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,susloparovdenis/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,susloparovdenis/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex
|
src/Markup/Perspex.Markup.Xaml/Converters/BitmapTypeConverter.cs
|
src/Markup/Perspex.Markup.Xaml/Converters/BitmapTypeConverter.cs
|
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media.Imaging;
using Perspex.Platform;
namespace Perspex.Markup.Xaml.Converters
{
public class BitmapTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
{
var uri = new Uri((string)value, UriKind.RelativeOrAbsolute);
var scheme = uri.IsAbsoluteUri ? uri.Scheme : "file";
switch (scheme)
{
case "file":
return new Bitmap((string)value);
case "resource":
var assets = PerspexLocator.Current.GetService<IAssetLoader>();
return new Bitmap(assets.Open(uri));
default:
throw new NotSupportedException($"Unsupported bitmap URI scheme: {uri.Scheme}.");
}
}
public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
}
|
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media.Imaging;
namespace Perspex.Markup.Xaml.Converters
{
public class BitmapTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
{
return new Bitmap((string)value);
}
public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
d843aef427655a5b6c00a34b007abf64b185623a
|
Remove legercy code in UIElement.(BackgroundTexture)
|
GoodGoodJM/UnityEditorOOP
|
Assets/Editor/EditorUI/Element/UIElement.cs
|
Assets/Editor/EditorUI/Element/UIElement.cs
|
using UnityEditor;
using UnityEngine;
namespace GGM.Editor.UI.Element
{
public abstract class UIElement : IUIElement
{
protected UIElement()
{
LayoutStyle = GUIStyle.none;
}
public Color BackgroundColor { get; set; }
public GUIStyle LayoutStyle { get; set; }
public void Draw()
{
var previousColor = GUI.backgroundColor;
GUI.backgroundColor = BackgroundColor;
EditorGUILayout.BeginVertical(LayoutStyle);
Content();
EditorGUILayout.EndVertical();
GUI.backgroundColor = previousColor;
}
protected abstract void Content();
}
}
|
using UnityEditor;
using UnityEngine;
namespace GGM.Editor.UI.Element
{
public abstract class UIElement : IUIElement
{
protected UIElement()
{
LayoutStyle = GUIStyle.none;
}
public Texture2D BackgroundTexture
{
get { return LayoutStyle.normal.background; }
set { LayoutStyle.normal.background = value; }
}
public Color BackgroundColor { get; set; }
public GUIStyle LayoutStyle { get; set; }
public void Draw()
{
var previousColor = GUI.backgroundColor;
GUI.backgroundColor = BackgroundColor;
EditorGUILayout.BeginVertical(LayoutStyle);
Content();
EditorGUILayout.EndVertical();
GUI.backgroundColor = previousColor;
}
protected abstract void Content();
}
}
|
mit
|
C#
|
2752e969c05c7eae3522f809622a2e332230e53d
|
Replace links by https
|
AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS
|
src/R/Components/Impl/Documentation/OnlineDocumentationUrls.cs
|
src/R/Components/Impl/Documentation/OnlineDocumentationUrls.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Microsoft.R.Components.Documentation {
public static class OnlineDocumentationUrls {
public const string CranIntro = "https://aka.ms/rtvs-cran-r-intro";
public const string CranData = "https://aka.ms/rtvs-cran-data";
public const string CranExtensions = "https://aka.ms/rtvs-cran-r-exts";
public const string CranViews = "https://aka.ms/rtvs-cran-views";
public const string RtvsDocumentation = "https://aka.ms/rtvs-docs";
public const string RtvsSamples = "https://aka.ms/rtvs-examples";
public const string CheckForRtvsUpdates = "https://aka.ms/rtvs-checkforupdate";
public const string MicrosoftRProducts = "https://aka.ms/rtvs-msft-r";
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Microsoft.R.Components.Documentation {
public static class OnlineDocumentationUrls {
public const string CranIntro = "http://aka.ms/rtvs-cran-r-intro";
public const string CranData = "http://aka.ms/rtvs-cran-data";
public const string CranExtensions = "http://aka.ms/rtvs-cran-r-exts";
public const string CranViews = "http://aka.ms/rtvs-cran-views";
public const string RtvsDocumentation = "http://aka.ms/rtvs-docs";
public const string RtvsSamples = "http://aka.ms/rtvs-examples";
public const string CheckForRtvsUpdates = "http://aka.ms/rtvs-checkforupdate";
public const string MicrosoftRProducts = "http://aka.ms/rtvs-msft-r";
}
}
|
mit
|
C#
|
bd8a3f478dee2fd56f2617a8ce70e8114f26655a
|
Update GlobalAlert.cshtml
|
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
|
src/StockportWebapp/Views/stockportgov/Shared/GlobalAlert.cshtml
|
src/StockportWebapp/Views/stockportgov/Shared/GlobalAlert.cshtml
|
@using StockportWebapp.Models
@using StockportWebapp.Utils
@inject ICookiesHelper CookiesHelper
@model Alert
@{
var alertCookies = CookiesHelper.GetCookies<Alert>("alerts");
var isDismissed = alertCookies != null && alertCookies.Contains(Model.Slug) && !Model.IsStatic;
}
@if (!isDismissed)
{
<div class="global-alert-@Model.Severity.ToLowerInvariant()">
<div class="grid-container grid-100 global-alert-container">
<div class="grid-100 mobile-grid-100 tablet-grid-100 global-alert grid-parent">
<div class="hide-on-mobile hide-on-tablet global-alert-icon global-alert-icon-@Model.Severity.ToLowerInvariant()">
<i></i>
</div>
<div class="grid-80 mobile-grid-95 global-alert-text-container">
<div class="global-alert-text-@Model.Severity.ToLowerInvariant()">
<h3>@Model.Title</h3> @Html.Raw(Model.Body)
</div>
</div>
@if (!Model.IsStatic)
{
<div class="global-alert-close-container">
<a href="javascript:void(0)" title="Close @Model.Title alert" aria-label="Close @Model.Title alert">
<div class="global-alert-close-@Model.Severity.ToLowerInvariant()">
<i class="close-alert" data-slug="@Model.Slug" data-parent="global-alert-@Model.Severity.ToLowerInvariant()"></i>
</div>
</a>
</div>
}
</div>
</div>
</div>
}
|
@using StockportWebapp.Models
@using StockportWebapp.Utils
@inject ICookiesHelper CookiesHelper
@model Alert
@{
var alertCookies = CookiesHelper.GetCookies<Alert>("alerts");
var isDismissed = alertCookies != null && alertCookies.Contains(Model.Slug) && !Model.IsStatic;
}
@if (!isDismissed)
{
<div class="global-alert-@Model.Severity.ToLowerInvariant()">
<div class="grid-container grid-100 global-alert-container">
<div class="grid-100 mobile-grid-100 tablet-grid-100 global-alert grid-parent">
<div class="hide-on-mobile hide-on-tablet global-alert-icon global-alert-icon-@Model.Severity.ToLowerInvariant()">
<i></i>
</div>
<div class="grid-80 mobile-grid-95 global-alert-text-container">
<div class="global-alert-text-@Model.Severity.ToLowerInvariant()">
<h3>@Model.Title</h3> @Html.Raw(Model.Body)
</div>
</div>
@if (!Model.IsStatic)
{
<div class="global-alert-close-container">
<a href="javascript:void(0)" Title="Close @Model.Title alert" aria-label="Close @Model.Title alert">
<div class="global-alert-close-@Model.Severity.ToLowerInvariant()">
<i class="close-alert" data-slug="@Model.Slug" data-parent="global-alert-@Model.Severity.ToLowerInvariant()"></i>
</div>
</a>
</div>
}
</div>
</div>
</div>
}
|
mit
|
C#
|
7d276144b871f219d07321480aea1852e9aa7d44
|
Fix player sizing + masking
|
ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,ppy/osu
|
osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/PlayerInstance.cs
|
osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/PlayerInstance.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Users;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
{
public class PlayerInstance : CompositeDrawable
{
public bool PlayerLoaded => stack?.CurrentScreen is Player;
public User User => Score.ScoreInfo.User;
public ScoreProcessor ScoreProcessor => player?.ScoreProcessor;
public WorkingBeatmap Beatmap { get; private set; }
public Ruleset Ruleset { get; private set; }
public readonly Score Score;
private OsuScreenStack stack;
private MultiplayerSpectatorPlayer player;
public PlayerInstance(Score score)
{
Score = score;
RelativeSizeAxes = Axes.Both;
Masking = true;
}
[BackgroundDependencyLoader]
private void load(BeatmapManager beatmapManager)
{
Beatmap = beatmapManager.GetWorkingBeatmap(Score.ScoreInfo.Beatmap, bypassCache: true);
Ruleset = Score.ScoreInfo.Ruleset.CreateInstance();
InternalChild = new GameplayIsolationContainer(Beatmap, Score.ScoreInfo.Ruleset, Score.ScoreInfo.Mods)
{
RelativeSizeAxes = Axes.Both,
Child = new DrawSizePreservingFillContainer
{
RelativeSizeAxes = Axes.Both,
Child = stack = new OsuScreenStack()
}
};
stack.Push(new MultiplayerSpectatorPlayerLoader(Score, () => player = new MultiplayerSpectatorPlayer(Score)));
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Users;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
{
public class PlayerInstance : CompositeDrawable
{
public bool PlayerLoaded => stack?.CurrentScreen is Player;
public User User => Score.ScoreInfo.User;
public ScoreProcessor ScoreProcessor => player?.ScoreProcessor;
public WorkingBeatmap Beatmap { get; private set; }
public Ruleset Ruleset { get; private set; }
public readonly Score Score;
private OsuScreenStack stack;
private MultiplayerSpectatorPlayer player;
public PlayerInstance(Score score)
{
Score = score;
}
[BackgroundDependencyLoader]
private void load(BeatmapManager beatmapManager)
{
Beatmap = beatmapManager.GetWorkingBeatmap(Score.ScoreInfo.Beatmap, bypassCache: true);
Ruleset = Score.ScoreInfo.Ruleset.CreateInstance();
InternalChild = new GameplayIsolationContainer(Beatmap, Score.ScoreInfo.Ruleset, Score.ScoreInfo.Mods)
{
RelativeSizeAxes = Axes.Both,
Child = new DrawSizePreservingFillContainer
{
RelativeSizeAxes = Axes.Both,
Child = stack = new OsuScreenStack()
}
};
stack.Push(new MultiplayerSpectatorPlayerLoader(Score, () => player = new MultiplayerSpectatorPlayer(Score)));
}
}
}
|
mit
|
C#
|
65edbb39dd737e8529a343f385d2600e482b7ff3
|
Add Culture Cloning Test (#41124)
|
ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx
|
src/System.Globalization/tests/CultureInfo/CultureInfoClone.cs
|
src/System.Globalization/tests/CultureInfo/CultureInfoClone.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoClone
{
public static IEnumerable<object[]> Clone_TestData()
{
yield return new object[] { new CultureInfo(CultureInfo.InvariantCulture.Name) };
yield return new object[] { CultureInfo.InvariantCulture };
yield return new object[] { new CultureInfo("fr-FR") };
yield return new object[] { new CultureInfo("en") };
}
[Theory]
[MemberData(nameof(Clone_TestData))]
public void Clone(CultureInfo culture)
{
CultureInfo clone = (CultureInfo)culture.Clone();
Assert.Equal(culture, clone);
Assert.NotSame(clone, culture);
}
[Fact]
public void TestCalendarAfterCloning()
{
CultureInfo ci = new CultureInfo("en-US");
Assert.Same(ci.Calendar, ci.DateTimeFormat.Calendar);
CultureInfo ci1 = (CultureInfo) ci.Clone();
Assert.Same(ci1.Calendar, ci1.DateTimeFormat.Calendar);
Assert.NotSame(ci.Calendar, ci1.Calendar);
Assert.NotSame(((CultureInfo)(ci.Clone())).Calendar, ((CultureInfo)(ci.Clone())).Calendar);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoClone
{
public static IEnumerable<object[]> Clone_TestData()
{
yield return new object[] { new CultureInfo(CultureInfo.InvariantCulture.Name) };
yield return new object[] { CultureInfo.InvariantCulture };
yield return new object[] { new CultureInfo("fr-FR") };
yield return new object[] { new CultureInfo("en") };
}
[Theory]
[MemberData(nameof(Clone_TestData))]
public void Clone(CultureInfo culture)
{
CultureInfo clone = (CultureInfo)culture.Clone();
Assert.Equal(culture, clone);
Assert.NotSame(clone, culture);
}
}
}
|
mit
|
C#
|
b690ad186b60df0640e30f5af58196ddc24b2339
|
Move media type formatter registration to WebApiConfig
|
OSLC/oslc4net,OSLC/oslc4net,OSLC/oslc4net
|
OSLC4Net_SDK/OSLC4Net.StockQuoteSample/App_Start/WebApiConfig.cs
|
OSLC4Net_SDK/OSLC4Net.StockQuoteSample/App_Start/WebApiConfig.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web;
using OSLC4Net.StockQuoteSample.Controllers;
using OSLC4Net.Core.DotNetRdfProvider;
namespace OSLC4Net.StockQuoteSample
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Custom initialization
config.Formatters.Clear();
config.Formatters.Insert(0, new RdfXmlMediaTypeFormatter());
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + "/api";
ServiceProviderController.init(baseUrl);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web;
using OSLC4Net.StockQuoteSample.Controllers;
namespace OSLC4Net.StockQuoteSample
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + "/api";
ServiceProviderController.init(baseUrl);
}
}
}
|
epl-1.0
|
C#
|
b8230d93e61182c7a35465d2c7ec86da7f2a3dc3
|
create a property that receives a parameter by constructor to set the xml file name
|
Natanielsr/ProjectCustomGame
|
ProjectCustomGame/Assets/scripts/models/manager/ScenesManager.cs
|
ProjectCustomGame/Assets/scripts/models/manager/ScenesManager.cs
|
/*
The MIT License (MIT)
Copyright (c) 2017 Nataniel Soares Rodrigues
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 NatanielSoaresRodrigues.ProjectCustomGame.Xml;
using UnityEngine;
using NatanielSoaresRodrigues.ProjectCustomGame.Objs;
using System;
namespace NatanielSoaresRodrigues.ProjectCustomGame.Models.Manager
{
public class ScenesManager : MyObjectManager
{
public string xmlFileName {
get;
set;
}
public Scene CurrentScene {
get{
return current as Scene;
}
private set{ }
}
public ScenesManager(string xmlFileName) : base()
{
//load the xml file
this.xmlFileName = xmlFileName;
if (string.IsNullOrEmpty (xmlFileName))
throw new Exception ("The xml file name needed to be seted");
SceneContainer container = new XmlManagement (xmlFileName, typeof(SceneContainer)).openFile () as SceneContainer;
mainList = container.scenes.ToArray ();
}
public Texture loadTexture(){
if (CurrentScene == null)
return null;
if (CurrentScene.SceneImage == null)
return null;
Texture textureImage = Resources.Load<Texture> ("images/" + CurrentScene.SceneImage);
return textureImage;
}
protected override void mainListOk ()
{
throw new System.NotImplementedException ();
}
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2017 Nataniel Soares Rodrigues
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 NatanielSoaresRodrigues.ProjectCustomGame.Xml;
using UnityEngine;
using NatanielSoaresRodrigues.ProjectCustomGame.Objs;
namespace NatanielSoaresRodrigues.ProjectCustomGame.Models.Manager
{
public class ScenesManager : MyObjectManager
{
public Scene CurrentScene {
get{
return current as Scene;
}
private set{ }
}
public ScenesManager() : base()
{
SceneContainer container = new XmlManagement ("scenes", typeof(SceneContainer)).openFile () as SceneContainer;
mainList = container.scenes.ToArray ();
}
public Texture loadTexture(){
if (CurrentScene == null)
return null;
if (CurrentScene.SceneImage == null)
return null;
Texture textureImage = Resources.Load<Texture> ("images/" + CurrentScene.SceneImage);
return textureImage;
}
protected override void mainListOk ()
{
throw new System.NotImplementedException ();
}
}
}
|
mit
|
C#
|
0850d07986dcad774546eebca155aa802d88bf57
|
Fix crashing when provided osu! cfg file path is incorrect.
|
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
|
osu!StreamCompanion/Code/Modules/osuFallbackDetector/OsuFallbackDetector.cs
|
osu!StreamCompanion/Code/Modules/osuFallbackDetector/OsuFallbackDetector.cs
|
using System;
using System.IO;
using osu_StreamCompanion.Code.Core;
using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfeaces;
namespace osu_StreamCompanion.Code.Modules.osuFallbackDetector
{
class OsuFallbackDetector : IModule, ISettings
{
//LastVersion = b20151228.3
private const string LAST_FALLBACK_VERSION = "b20151228.3";
private Settings _settings;
public bool Started { get; set; }
public void Start(ILogger logger)
{
string FilePath = GetConfigFilePath();
if (!Uri.IsWellFormedUriString(FilePath, UriKind.Absolute))
{
logger.Log("WARNING: Path to osu! config location isn't valid. Tried: \"{0}\"", LogLevel.Advanced, FilePath);
return;
}
if (!File.Exists(FilePath))
{
logger.Log("WARNING: Could not get correct osu! config location. Tried: \"{0}\"", LogLevel.Advanced, FilePath);
return;
}
bool isFallback = IsFallback(FilePath);
_settings.Add("OsuFallback", isFallback);
if (isFallback)
logger.Log("Detected osu fallback version!", LogLevel.Basic);
}
public void SetSettingsHandle(Settings settings)
{
_settings = settings;
}
private bool IsFallback(string configPath)
{
foreach (var cfgLine in File.ReadLines(configPath))
{
if (cfgLine.StartsWith("LastVersion") && cfgLine.Contains(LAST_FALLBACK_VERSION))
return true;
}
return false;
}
private string GetConfigFilePath()
{
//TODO: Fix configuration filename being incorrect in some cases (eg. windows "email" usernames)
string filename = string.Format("osu!.{0}.cfg", Environment.UserName);
return Path.Combine(LoadOsuDir(), filename);
}
private string LoadOsuDir()
{
return _settings.Get("MainOsuDirectory", "");
}
}
}
|
using System;
using System.IO;
using osu_StreamCompanion.Code.Core;
using osu_StreamCompanion.Code.Core.DataTypes;
using osu_StreamCompanion.Code.Interfeaces;
namespace osu_StreamCompanion.Code.Modules.osuFallbackDetector
{
class OsuFallbackDetector : IModule, ISettings
{
//LastVersion = b20151228.3
private const string LAST_FALLBACK_VERSION = "b20151228.3";
private Settings _settings;
public bool Started { get; set; }
public void Start(ILogger logger)
{
string FilePath = GetConfigFilePath();
if (!File.Exists(FilePath))
{
logger.Log("WARNING: Could not get correct osu! config location. Tried: \"{0}\"",LogLevel.Advanced,FilePath);
return;
}
bool isFallback = IsFallback(FilePath);
_settings.Add("OsuFallback", isFallback);
if(isFallback)
logger.Log("Detected osu fallback version!",LogLevel.Basic);
}
public void SetSettingsHandle(Settings settings)
{
_settings = settings;
}
private bool IsFallback(string configPath)
{
foreach (var cfgLine in File.ReadLines(configPath))
{
if (cfgLine.StartsWith("LastVersion") && cfgLine.Contains(LAST_FALLBACK_VERSION))
return true;
}
return false;
}
private string GetConfigFilePath()
{
string filename = string.Format("osu!.{0}.cfg", Environment.UserName);
return Path.Combine(LoadOsuDir(), filename);
}
private string LoadOsuDir()
{
return _settings.Get("MainOsuDirectory", "");
}
}
}
|
mit
|
C#
|
2734983564a3fa132242fbe55a794dd124d582ed
|
Add unique constraints on RulesetInfo table to ensure things stay sane.
|
ppy/osu,DrabWeb/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,ppy/osu,EVAST9919/osu,naoey/osu,2yangk23/osu,smoogipooo/osu,johnneijzen/osu,Damnae/osu,ZLima12/osu,Nabile-Rahmani/osu,nyaamara/osu,NeoAdonis/osu,naoey/osu,RedNesto/osu,peppy/osu,UselessToucan/osu,osu-RP/osu-RP,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,NeoAdonis/osu,tacchinotacchi/osu,Frontear/osuKyzer,UselessToucan/osu,johnneijzen/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,ppy/osu,naoey/osu,smoogipoo/osu,Drezi126/osu
|
osu.Game/Database/RulesetInfo.cs
|
osu.Game/Database/RulesetInfo.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Modes;
using SQLite.Net.Attributes;
namespace osu.Game.Database
{
public class RulesetInfo
{
[PrimaryKey, AutoIncrement]
public int? ID { get; set; }
[Indexed(Unique = true)]
public string Name { get; set; }
[Indexed(Unique = true)]
public string InstantiationInfo { get; set; }
[Indexed]
public bool Available { get; set; }
public Ruleset CreateInstance() => (Ruleset)Activator.CreateInstance(Type.GetType(InstantiationInfo));
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Modes;
using SQLite.Net.Attributes;
namespace osu.Game.Database
{
public class RulesetInfo
{
[PrimaryKey, AutoIncrement]
public int? ID { get; set; }
public string Name { get; set; }
public string InstantiationInfo { get; set; }
[Indexed]
public bool Available { get; set; }
public Ruleset CreateInstance() => (Ruleset)Activator.CreateInstance(Type.GetType(InstantiationInfo));
}
}
|
mit
|
C#
|
73fbfda1b5680e6c8bd2de30da103a020e717737
|
Bump to v0.3.0
|
danielwertheim/structurizer
|
buildconfig.cake
|
buildconfig.cake
|
public class BuildConfig
{
private const string Version = "0.3.0";
private const bool IsPreRelease = false;
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string SemVer { get; private set; }
public string BuildVersion { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty),
BuildVersion = Version + "." + buildRevision,
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
}
|
public class BuildConfig
{
private const string Version = "0.2.0";
private const bool IsPreRelease = false;
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string SemVer { get; private set; }
public string BuildVersion { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty),
BuildVersion = Version + "." + buildRevision,
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
}
|
mit
|
C#
|
7969db849fe933251c8be3a3facfeaee070c992f
|
Install AppHarborInstaller on WindsorContainer
|
appharbor/appharbor-cli
|
src/AppHarbor/Program.cs
|
src/AppHarbor/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer()
.Install(new AppHarborInstaller());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
namespace AppHarbor
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
}
}
}
|
mit
|
C#
|
27744639ac4a1ef756f5cf598549045b7b7917f2
|
change method name.
|
mdsol/Medidata.ZipkinTracerModule
|
src/Medidata.ZipkinTracer.Core/Middlewares/ZipkinMiddleware.cs
|
src/Medidata.ZipkinTracer.Core/Middlewares/ZipkinMiddleware.cs
|
using System.Threading.Tasks;
using log4net;
using Microsoft.Owin;
using Owin;
namespace Medidata.ZipkinTracer.Core.Middlewares
{
public class ZipkinMiddleware : OwinMiddleware
{
private readonly ZipkinMiddlewareOptions _options;
public ZipkinMiddleware(OwinMiddleware next, ZipkinMiddlewareOptions options) : base(next)
{
_options = options;
}
public override async Task Invoke(IOwinContext context)
{
if (_options.Enable)
{
var traceProvider = new TraceProvider(context);
var logger = LogManager.GetLogger("ZipkinMiddleware");
var zipkin = new ZipkinClient(traceProvider, logger);
var span = zipkin.StartServerTrace(context.Request.Uri, context.Request.Method);
await Next.Invoke(context);
zipkin.EndServerTrace(span);
}
}
}
public static class AppBuilderExtensions
{
public static void UseZipkin(this IAppBuilder app, ZipkinMiddlewareOptions options = null)
{
options = options ?? new ZipkinMiddlewareOptions();
app.Use<ZipkinMiddleware>(options);
}
}
}
|
using System.Threading.Tasks;
using log4net;
using Microsoft.Owin;
using Owin;
namespace Medidata.ZipkinTracer.Core.Middlewares
{
public class ZipkinMiddleware : OwinMiddleware
{
private readonly ZipkinMiddlewareOptions _options;
public ZipkinMiddleware(OwinMiddleware next, ZipkinMiddlewareOptions options) : base(next)
{
_options = options;
}
public override async Task Invoke(IOwinContext context)
{
if (_options.Enable)
{
var traceProvider = new TraceProvider(context);
var logger = LogManager.GetLogger("ZipkinMiddleware");
var zipkin = new ZipkinClient(traceProvider, logger);
var span = zipkin.StartServerTrace(context.Request.Uri, context.Request.Method);
await Next.Invoke(context);
zipkin.EndServerTrace(span);
}
}
}
public static class AppBuilderExtensions
{
public static void UseZipkinAuthentication(this IAppBuilder app, ZipkinMiddlewareOptions options = null)
{
options = options ?? new ZipkinMiddlewareOptions();
app.Use<ZipkinMiddleware>(options);
}
}
}
|
mit
|
C#
|
5bba8c6053361348ece9abe262aeb677ff1e7854
|
Update NetCore2 ConsoleExample with LogManager.Shutdown()
|
NLog/NLog.Framework.Logging,NLog/NLog.Framework.Logging,NLog/NLog.Extensions.Logging
|
examples/NetCore2/ConsoleExample/Program.cs
|
examples/NetCore2/ConsoleExample/Program.cs
|
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ConsoleExample
{
class Program
{
static void Main(string[] args)
{
var servicesProvider = BuildDi();
var runner = servicesProvider.GetRequiredService<Runner>();
runner.DoAction("Action1");
Console.WriteLine("Press ANY key to exit");
Console.ReadLine();
NLog.LogManager.Shutdown(); // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
}
private static IServiceProvider BuildDi()
{
var services = new ServiceCollection();
//Runner is the custom class
services.AddTransient<Runner>();
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
//configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("nlog.config");
return serviceProvider;
}
}
public class Runner
{
private readonly ILogger<Runner> _logger;
public Runner(ILogger<Runner> logger)
{
_logger = logger;
}
public void DoAction(string name)
{
_logger.LogDebug(20, "Doing hard work! {Action}", name);
}
}
}
|
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ConsoleExample
{
class Program
{
static void Main(string[] args)
{
var servicesProvider = BuildDi();
var runner = servicesProvider.GetRequiredService<Runner>();
runner.DoAction("Action1");
Console.WriteLine("Press ANY key to exit");
Console.ReadLine();
}
private static IServiceProvider BuildDi()
{
var services = new ServiceCollection();
//Runner is the custom class
services.AddTransient<Runner>();
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
//configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("nlog.config");
return serviceProvider;
}
}
public class Runner
{
private readonly ILogger<Runner> _logger;
public Runner(ILogger<Runner> logger)
{
_logger = logger;
}
public void DoAction(string name)
{
_logger.LogDebug(20, "Doing hard work! {Action}", name);
}
}
}
|
bsd-2-clause
|
C#
|
8712c70271baed3bb3e6be77de8ff205db541939
|
fix model planning and checking
|
volak/Aggregates.NET,volak/Aggregates.NET
|
src/Aggregates.NET.Testing/Internal/TestableApplication.cs
|
src/Aggregates.NET.Testing/Internal/TestableApplication.cs
|
using Aggregates.Internal;
using Aggregates.UnitOfWork;
using Aggregates.UnitOfWork.Query;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading.Tasks;
namespace Aggregates
{
[ExcludeFromCodeCoverage]
class TestableApplication : ITestableApplication
{
private IdRegistry _ids;
public dynamic Bag { get; set; }
internal Dictionary<Id, object> Planned;
internal Dictionary<Id, object> Added;
internal Dictionary<Id, object> Updated;
internal List<Id> Deleted;
internal List<Id> Read;
public TestableApplication(IdRegistry ids)
{
_ids = ids;
Planned = new Dictionary<Id, object>();
Added = new Dictionary<Id, object>();
Updated = new Dictionary<Id, object>();
Deleted = new List<Id>();
Read = new List<Id>();
}
public Task Add<T>(Id id, T document) where T : class
{
Added[id] = document;
return Task.CompletedTask;
}
public Task Delete<T>(Id id) where T : class
{
Deleted.Add(id);
return Task.CompletedTask;
}
public Task<T> Get<T>(Id id) where T : class
{
Read.Add(id);
return Task.FromResult(Planned[id] as T);
}
public Task<IQueryResult<T>> Query<T>(IDefinition query) where T : class
{
throw new NotImplementedException();
}
public Task<T> TryGet<T>(Id id) where T : class
{
Read.Add(id);
if (Planned.ContainsKey(id))
return Task.FromResult(Planned[id] as T);
return Task.FromResult((T)null);
}
public Task Update<T>(Id id, T document) where T : class
{
Updated[id] = document;
return Task.CompletedTask;
}
public IModelChecker<TModel> Check<TModel>(Id id) where TModel : class, new()
{
return new ModelChecker<TModel>(this, id);
}
public IModelPlanner<TModel> Plan<TModel>(Id id) where TModel : class, new()
{
return new ModelPlanner<TModel>(this, id);
}
}
}
|
using Aggregates.Internal;
using Aggregates.UnitOfWork;
using Aggregates.UnitOfWork.Query;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading.Tasks;
namespace Aggregates
{
[ExcludeFromCodeCoverage]
class TestableApplication : ITestableApplication
{
private IdRegistry _ids;
public dynamic Bag { get; set; }
internal Dictionary<Id, object> Planned;
internal Dictionary<Id, object> Added;
internal Dictionary<Id, object> Updated;
internal List<Id> Deleted;
internal List<Id> Read;
public TestableApplication(IdRegistry ids)
{
_ids = ids;
}
public Task Add<T>(Id id, T document) where T : class
{
Added[id] = document;
return Task.CompletedTask;
}
public Task Delete<T>(Id id) where T : class
{
Deleted.Add(id);
return Task.CompletedTask;
}
public Task<T> Get<T>(Id id) where T : class
{
Read.Add(id);
return Task.FromResult(Planned[id] as T);
}
public Task<IQueryResult<T>> Query<T>(IDefinition query) where T : class
{
throw new NotImplementedException();
}
public Task<T> TryGet<T>(Id id) where T : class
{
Read.Add(id);
if (Planned.ContainsKey(id))
return Task.FromResult(Planned[id] as T);
return Task.FromResult((T)null);
}
public Task Update<T>(Id id, T document) where T : class
{
Updated[id] = document;
return Task.CompletedTask;
}
public IModelChecker<TModel> Check<TModel>(Id id) where TModel : class, new()
{
return new ModelChecker<TModel>(this, id);
}
public IModelPlanner<TModel> Plan<TModel>(Id id) where TModel : class, new()
{
return new ModelPlanner<TModel>(this, id);
}
}
}
|
mit
|
C#
|
b12c8d6ee25c524f4d98ba0a57e5659ed5152f9b
|
Add at CompositeAnnouncer Error(Exception exception) implementation
|
barser/fluentmigrator,vgrigoriu/fluentmigrator,wolfascu/fluentmigrator,bluefalcon/fluentmigrator,itn3000/fluentmigrator,IRlyDontKnow/fluentmigrator,drmohundro/fluentmigrator,mstancombe/fluentmig,akema-fr/fluentmigrator,KaraokeStu/fluentmigrator,dealproc/fluentmigrator,mstancombe/fluentmig,amroel/fluentmigrator,daniellee/fluentmigrator,fluentmigrator/fluentmigrator,lcharlebois/fluentmigrator,IRlyDontKnow/fluentmigrator,stsrki/fluentmigrator,istaheev/fluentmigrator,istaheev/fluentmigrator,barser/fluentmigrator,drmohundro/fluentmigrator,fluentmigrator/fluentmigrator,modulexcite/fluentmigrator,spaccabit/fluentmigrator,akema-fr/fluentmigrator,lcharlebois/fluentmigrator,alphamc/fluentmigrator,MetSystem/fluentmigrator,daniellee/fluentmigrator,jogibear9988/fluentmigrator,mstancombe/fluentmig,igitur/fluentmigrator,FabioNascimento/fluentmigrator,alphamc/fluentmigrator,istaheev/fluentmigrator,tommarien/fluentmigrator,modulexcite/fluentmigrator,tommarien/fluentmigrator,bluefalcon/fluentmigrator,wolfascu/fluentmigrator,FabioNascimento/fluentmigrator,MetSystem/fluentmigrator,stsrki/fluentmigrator,amroel/fluentmigrator,igitur/fluentmigrator,schambers/fluentmigrator,mstancombe/fluentmigrator,KaraokeStu/fluentmigrator,vgrigoriu/fluentmigrator,itn3000/fluentmigrator,eloekset/fluentmigrator,dealproc/fluentmigrator,daniellee/fluentmigrator,mstancombe/fluentmigrator,spaccabit/fluentmigrator,eloekset/fluentmigrator,jogibear9988/fluentmigrator,schambers/fluentmigrator
|
src/FluentMigrator.Runner/Announcers/CompositeAnnouncer.cs
|
src/FluentMigrator.Runner/Announcers/CompositeAnnouncer.cs
|
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace FluentMigrator.Runner.Announcers
{
public class CompositeAnnouncer : IAnnouncer
{
private readonly IEnumerable<IAnnouncer> announcers;
public CompositeAnnouncer(params IAnnouncer[] announcers)
{
this.announcers = announcers ?? new IAnnouncer[] {};
}
public void Heading(string message)
{
Each(a => a.Heading(message));
}
public void Say(string message)
{
Each(a => a.Say(message));
}
public void Emphasize(string message)
{
Each(a => a.Emphasize(message));
}
public void Sql(string sql)
{
Each(a => a.Sql(sql));
}
public void ElapsedTime(TimeSpan timeSpan)
{
Each(a => a.ElapsedTime(timeSpan));
}
public void Error(string message)
{
Each(a => a.Error(message));
}
public void Error(Exception exception)
{
while (exception != null)
{
Error(exception.Message);
exception = exception.InnerException;
}
}
public void Write(string message, bool escaped)
{
Each(a => a.Write(message, escaped));
}
private void Each(Action<IAnnouncer> action)
{
foreach (var announcer in announcers)
action(announcer);
}
}
}
|
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace FluentMigrator.Runner.Announcers
{
public class CompositeAnnouncer : IAnnouncer
{
private readonly IEnumerable<IAnnouncer> announcers;
public CompositeAnnouncer(params IAnnouncer[] announcers)
{
this.announcers = announcers ?? new IAnnouncer[] {};
}
public void Heading(string message)
{
Each(a => a.Heading(message));
}
public void Say(string message)
{
Each(a => a.Say(message));
}
public void Emphasize(string message)
{
Each(a => a.Emphasize(message));
}
public void Sql(string sql)
{
Each(a => a.Sql(sql));
}
public void ElapsedTime(TimeSpan timeSpan)
{
Each(a => a.ElapsedTime(timeSpan));
}
public void Error(string message)
{
Each(a => a.Error(message));
}
public void Write(string message, bool escaped)
{
Each(a => a.Write(message, escaped));
}
private void Each(Action<IAnnouncer> action)
{
foreach (var announcer in announcers)
action(announcer);
}
}
}
|
apache-2.0
|
C#
|
05b6ab91c9873885e639e6ba4153b6828dde4edf
|
Disable unused event warning
|
wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,MrDaedra/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia
|
src/Markup/Avalonia.Markup/AlwaysEnabledDelegateCommand.cs
|
src/Markup/Avalonia.Markup/AlwaysEnabledDelegateCommand.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace Avalonia.Markup
{
class AlwaysEnabledDelegateCommand : ICommand
{
private readonly Delegate action;
public AlwaysEnabledDelegateCommand(Delegate action)
{
this.action = action;
}
#pragma warning disable 0067
public event EventHandler CanExecuteChanged;
#pragma warning restore 0067
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
if (action.Method.GetParameters().Length == 0)
{
action.DynamicInvoke();
}
else
{
action.DynamicInvoke(parameter);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace Avalonia.Markup
{
class AlwaysEnabledDelegateCommand : ICommand
{
private readonly Delegate action;
public AlwaysEnabledDelegateCommand(Delegate action)
{
this.action = action;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
if (action.Method.GetParameters().Length == 0)
{
action.DynamicInvoke();
}
else
{
action.DynamicInvoke(parameter);
}
}
}
}
|
mit
|
C#
|
d34d2c95e4258d294402006b49510b689aac54f6
|
Update IComplier.Engine.cs
|
NMSLanX/Natasha
|
src/Natasha/Core/Engine/ComplierModule/IComplier.Engine.cs
|
src/Natasha/Core/Engine/ComplierModule/IComplier.Engine.cs
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Natasha.Complier.Model;
using System.Collections.Immutable;
using System.IO;
using System.Reflection;
namespace Natasha.Complier
{
public abstract partial class IComplier
{
/// <summary>
/// 使用内存流进行脚本编译
/// </summary>
/// <param name="sourceContent">脚本内容</param>
/// <param name="errorAction">发生错误执行委托</param>
/// <returns></returns>
public static (Assembly Assembly, ImmutableArray<Diagnostic> Errors, CSharpCompilation Compilation) StreamComplier(ComplierModel model)
{
var domain = model.Domain;
lock (domain)
{
//创建语言编译
CSharpCompilation compilation = CSharpCompilation.Create(
model.AssemblyName,
options: new CSharpCompilationOptions(
outputKind: OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release,
allowUnsafe: true),
syntaxTrees: model.Trees ,
references: model.References);
//编译并生成程序集
MemoryStream stream = new MemoryStream();
var complieResult = compilation.Emit(stream);
if (complieResult.Success)
{
return (domain.Handler(stream), default, compilation);
}
else
{
stream.Dispose();
return (null, complieResult.Diagnostics, compilation);
}
}
}
}
}
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Natasha.Complier.Model;
using System.Collections.Immutable;
using System.IO;
using System.Reflection;
namespace Natasha.Complier
{
public abstract partial class IComplier
{
/// <summary>
/// 使用内存流进行脚本编译
/// </summary>
/// <param name="sourceContent">脚本内容</param>
/// <param name="errorAction">发生错误执行委托</param>
/// <returns></returns>
public static (Assembly Assembly, ImmutableArray<Diagnostic> Errors, CSharpCompilation Compilation) StreamComplier(ComplierModel model)
{
var domain = model.Domain;
lock (domain)
{
//创建语言编译
CSharpCompilation compilation = CSharpCompilation.Create(
model.AssemblyName,
options: new CSharpCompilationOptions(
outputKind: OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release,
allowUnsafe: true),
syntaxTrees: model.Trees ,
references: model.References);
//编译并生成程序集
MemoryStream stream = new MemoryStream();
var fileResult = compilation.Emit(stream);
if (fileResult.Success)
{
return (domain.Handler(stream), default, compilation);
}
else
{
stream.Dispose();
return (null, fileResult.Diagnostics, compilation);
}
}
}
}
}
|
mpl-2.0
|
C#
|
6f56a5dfb67e43f3cee7c486adfb3de2ce2e0337
|
Fix static problem for multiple RedisConfiguration (#154)
|
imperugo/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions
|
src/StackExchange.Redis.Extensions.Core/Configuration/RedisConfiguration.cs
|
src/StackExchange.Redis.Extensions.Core/Configuration/RedisConfiguration.cs
|
using System.Net.Security;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
public class RedisConfiguration
{
private ConnectionMultiplexer connection;
private ConfigurationOptions options;
/// <summary>
/// The key separation prefix used for all cache entries
/// </summary>
public string KeyPrefix { get; set; }
/// <summary>
/// The password or access key
/// </summary>
public string Password { get; set; }
/// <summary>
/// Specify if the connection can use Admin commands like flush database
/// </summary>
/// <value>
/// <c>true</c> if can use admin commands; otherwise, <c>false</c>.
/// </value>
public bool AllowAdmin { get; set; } = false;
/// <summary>
/// Specify if the connection is a secure connection or not.
/// </summary>
/// <value>
/// <c>true</c> if is secure; otherwise, <c>false</c>.
/// </value>
public bool Ssl { get; set; } = false;
/// <summary>
/// The connection timeout
/// </summary>
public int ConnectTimeout { get; set; } = 5000;
/// <summary>
/// Time (ms) to allow for synchronous operations
/// </summary>
public int SyncTimeout { get; set; } = 1000;
/// <summary>
/// If true, Connect will not create a connection while no servers are available
/// </summary>
public bool AbortOnConnectFail { get; set; }
/// <summary>
/// Database Id
/// </summary>
/// <value>
/// The database id, the default value is 0
/// </value>
public int Database { get; set; } = 0;
/// <summary>
/// The host of Redis Servers
/// </summary>
/// <value>
/// The ips or names
/// </value>
public RedisHost[] Hosts { get; set; }
/// <summary>
/// The strategy to use when executing server wide commands
/// </summary>
public ServerEnumerationStrategy ServerEnumerationStrategy { get; set; }
/// <summary>
/// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party; note
/// that this cannot be specified in the configuration-string.
/// </summary>
public event RemoteCertificateValidationCallback CertificateValidation;
public ConfigurationOptions ConfigurationOptions
{
get
{
if (options == null)
{
options = new ConfigurationOptions
{
Ssl = Ssl,
AllowAdmin = AllowAdmin,
Password = Password,
ConnectTimeout = ConnectTimeout,
SyncTimeout = SyncTimeout,
AbortOnConnectFail = AbortOnConnectFail
};
foreach (var redisHost in Hosts)
options.EndPoints.Add(redisHost.Host, redisHost.Port);
options.CertificateValidation += CertificateValidation;
}
return options;
}
}
public ConnectionMultiplexer Connection
{
get
{
if (connection == null)
connection = ConnectionMultiplexer.Connect(options);
return connection;
}
}
}
}
|
using System.Net.Security;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
public class RedisConfiguration
{
private static ConnectionMultiplexer connection;
private static ConfigurationOptions options;
/// <summary>
/// The key separation prefix used for all cache entries
/// </summary>
public string KeyPrefix { get; set; }
/// <summary>
/// The password or access key
/// </summary>
public string Password { get; set; }
/// <summary>
/// Specify if the connection can use Admin commands like flush database
/// </summary>
/// <value>
/// <c>true</c> if can use admin commands; otherwise, <c>false</c>.
/// </value>
public bool AllowAdmin { get; set; } = false;
/// <summary>
/// Specify if the connection is a secure connection or not.
/// </summary>
/// <value>
/// <c>true</c> if is secure; otherwise, <c>false</c>.
/// </value>
public bool Ssl { get; set; } = false;
/// <summary>
/// The connection timeout
/// </summary>
public int ConnectTimeout { get; set; } = 5000;
/// <summary>
/// Time (ms) to allow for synchronous operations
/// </summary>
public int SyncTimeout { get; set; } = 1000;
/// <summary>
/// If true, Connect will not create a connection while no servers are available
/// </summary>
public bool AbortOnConnectFail { get; set; }
/// <summary>
/// Database Id
/// </summary>
/// <value>
/// The database id, the default value is 0
/// </value>
public int Database { get; set; } = 0;
/// <summary>
/// The host of Redis Servers
/// </summary>
/// <value>
/// The ips or names
/// </value>
public RedisHost[] Hosts { get; set; }
/// <summary>
/// The strategy to use when executing server wide commands
/// </summary>
public ServerEnumerationStrategy ServerEnumerationStrategy { get; set; }
/// <summary>
/// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party; note
/// that this cannot be specified in the configuration-string.
/// </summary>
public event RemoteCertificateValidationCallback CertificateValidation;
public ConfigurationOptions ConfigurationOptions
{
get
{
if (options == null)
{
options = new ConfigurationOptions
{
Ssl = Ssl,
AllowAdmin = AllowAdmin,
Password = Password,
ConnectTimeout = ConnectTimeout,
SyncTimeout = SyncTimeout,
AbortOnConnectFail = AbortOnConnectFail
};
foreach (var redisHost in Hosts)
options.EndPoints.Add(redisHost.Host, redisHost.Port);
options.CertificateValidation += CertificateValidation;
}
return options;
}
}
public ConnectionMultiplexer Connection
{
get
{
if (connection == null)
connection = ConnectionMultiplexer.Connect(options);
return connection;
}
}
}
}
|
mit
|
C#
|
ede3e2e7ec1bb456b66dbb6e1f4e94adc01dffa6
|
Fix an error in JournalEndCrewSession
|
EDDiscovery/EDDiscovery,klightspeed/EDDiscovery,andreaspada/EDDiscovery,andreaspada/EDDiscovery,klightspeed/EDDiscovery,klightspeed/EDDiscovery,EDDiscovery/EDDiscovery,EDDiscovery/EDDiscovery
|
EDDiscovery/EliteDangerous/JournalEvents/JournalEndCrewSession.cs
|
EDDiscovery/EliteDangerous/JournalEvents/JournalEndCrewSession.cs
|
/*
* Copyright © 2017 EDDiscovery development team
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
// When written: when the captain in multicrew disbands the crew
//Parameters:
// OnCrime: (bool) true if crew disbanded as a result of a crime in a lawful session
// { "timestamp":"2017-04-12T11:32:30Z", "event":"EndCrewSession", "OnCrime":false }
[JournalEntryType(JournalTypeEnum.EndCrewSession)]
public class JournalEndCrewSession : JournalEntry
{
public JournalEndCrewSession(JObject evt) : base(evt, JournalTypeEnum.EndCrewSession)
{
OnCrime = evt["OnCrime"].Bool();
}
public bool OnCrime { get; set; }
public override System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.crewmemberquits; } }
public override void FillInformation(out string summary, out string info, out string detailed) //V
{
summary = EventTypeStr.SplitCapsWord();
info = Tools.FieldBuilder("; Crime", OnCrime);
detailed = "";
}
}
}
|
/*
* Copyright © 2017 EDDiscovery development team
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
// When written: when the captain in multicrew disbands the crew
//Parameters:
// OnCrime: (bool) true if crew disbanded as a result of a crime in a lawful session
// { "timestamp":"2017-04-12T11:32:30Z", "event":"EndCrewSession", "OnCrime":false }
[JournalEntryType(JournalTypeEnum.EndCrewSession)]
public class JournalEndCrewSession : JournalEntry
{
public JournalEndCrewSession(JObject evt) : base(evt, JournalTypeEnum.EndCrewSession)
{
OnCrime = evt["Name"].Bool();
}
public bool OnCrime { get; set; }
public override System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.crewmemberquits; } }
public override void FillInformation(out string summary, out string info, out string detailed) //V
{
summary = EventTypeStr.SplitCapsWord();
info = Tools.FieldBuilder("; Crime", OnCrime);
detailed = "";
}
}
}
|
apache-2.0
|
C#
|
658f55b303c56bd75ba53708088bc7768a60154d
|
Edit QueueDataGraphic.cs
|
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
|
QueueDataGraphic/QueueDataGraphic/CSharpFiles/QueueDataGraphic.cs
|
QueueDataGraphic/QueueDataGraphic/CSharpFiles/QueueDataGraphic.cs
|
/********************************************************************
* Develop by Jimmy Hu *
* This program is licensed under the Apache License 2.0. *
* QueueDataGraphic.cs *
* 本檔案用於佇列資料繪圖功能 *
********************************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueDataGraphic.CSharpFiles
{ // namespace start, 進入命名空間
class QueueDataGraphic // QueueDataGraphic class, QueueDataGraphic類別
{ // QueueDataGraphic class start, 進入QueueDataGraphic類別
List<DataQueue> DataQueueList;
} // QueueDataGraphic class end, 結束QueueDataGraphic類別
} // namespace end, 結束命名空間
|
/********************************************************************
* Develop by Jimmy Hu *
* This program is licensed under the Apache License 2.0. *
* QueueDataGraphic.cs *
* 本檔案用於佇列資料繪圖功能 *
********************************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueDataGraphic.CSharpFiles
{ // namespace start, 進入命名空間
class QueueDataGraphic // QueueDataGraphic class, QueueDataGraphic類別
{ // QueueDataGraphic class start, 進入QueueDataGraphic類別
} // QueueDataGraphic class end, 結束QueueDataGraphic類別
} // namespace end, 結束命名空間
|
apache-2.0
|
C#
|
74ba9f65d88e21dc229fe01597991138813e50e5
|
Update SettingSubScriptEffect.cs
|
maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/CSharp/Formatting/DealingWithFontSettings/SettingSubScriptEffect.cs
|
Examples/CSharp/Formatting/DealingWithFontSettings/SettingSubScriptEffect.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Formatting.DealingWithFontSettings
{
public class SettingSubScriptEffect
{
public static void Main(string[] args)
{
//Exstart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Excel object
int i = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[i];
//Accessing the "A1" cell from the worksheet
Aspose.Cells.Cell cell = worksheet.Cells["A1"];
//Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
//Obtaining the style of the cell
Style style = cell.GetStyle();
//Setting subscript effect
style.Font.IsSubscript = true;
//Applying the style to the cell
cell.SetStyle(style);
//Saving the Excel file
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003);
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Formatting.DealingWithFontSettings
{
public class SettingSubScriptEffect
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Adding a new worksheet to the Excel object
int i = workbook.Worksheets.Add();
//Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[i];
//Accessing the "A1" cell from the worksheet
Aspose.Cells.Cell cell = worksheet.Cells["A1"];
//Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
//Obtaining the style of the cell
Style style = cell.GetStyle();
//Setting subscript effect
style.Font.IsSubscript = true;
//Applying the style to the cell
cell.SetStyle(style);
//Saving the Excel file
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003);
}
}
}
|
mit
|
C#
|
8e9993353eae684aadef5216a87b03512912acf0
|
fix metric url issue
|
huoxudong125/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,cvent/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,alhardy/Metrics.NET
|
Src/Adapters/Nancy.Metrics/MetricsModule.cs
|
Src/Adapters/Nancy.Metrics/MetricsModule.cs
|
using System;
using Metrics;
using Metrics.Reporters;
using Metrics.Visualization;
namespace Nancy.Metrics
{
public class MetricsModule : NancyModule
{
private struct ModuleConfig
{
public readonly string ModulePath;
public readonly Action<INancyModule> ModuleConfigAction;
public readonly MetricsRegistry Registry;
public ModuleConfig(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
this.Registry = registry;
this.ModuleConfigAction = moduleConfig;
this.ModulePath = metricsPath;
}
}
private static ModuleConfig Config;
public static void Configure(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
MetricsModule.Config = new ModuleConfig(registry, moduleConfig, metricsPath);
}
public MetricsModule()
: base(Config.ModulePath ?? "/")
{
if (string.IsNullOrEmpty(Config.ModulePath))
{
return;
}
if (Config.ModuleConfigAction != null)
{
Config.ModuleConfigAction(this);
}
Get["/"] = _ => Response.AsText(FlotWebApp.GetFlotApp(new Uri(this.Context.Request.Url, "json")), "text/html");
Get["/text"] = _ => Response.AsText(Metric.GetAsHumanReadable());
Get["/json"] = _ => Response.AsJson(new RegistrySerializer().GetForSerialization(Config.Registry));
}
}
}
|
using System;
using Metrics;
using Metrics.Reporters;
using Metrics.Visualization;
namespace Nancy.Metrics
{
public class MetricsModule : NancyModule
{
private struct ModuleConfig
{
public readonly string ModulePath;
public readonly Action<INancyModule> ModuleConfigAction;
public readonly MetricsRegistry Registry;
public ModuleConfig(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
this.Registry = registry;
this.ModuleConfigAction = moduleConfig;
this.ModulePath = metricsPath;
}
}
private static ModuleConfig Config;
public static void Configure(MetricsRegistry registry, Action<INancyModule> moduleConfig, string metricsPath)
{
MetricsModule.Config = new ModuleConfig(registry, moduleConfig, metricsPath);
}
public MetricsModule()
: base(Config.ModulePath ?? "/")
{
if (string.IsNullOrEmpty(Config.ModulePath))
{
return;
}
if (Config.ModuleConfigAction != null)
{
Config.ModuleConfigAction(this);
}
Get["/"] = _ => Response.AsText(FlotWebApp.GetFlotApp(new Uri(Config.ModulePath + "/json", UriKind.Relative)), "text/html");
Get["/text"] = _ => Response.AsText(Metric.GetAsHumanReadable());
Get["/json"] = _ => Response.AsJson(new RegistrySerializer().GetForSerialization(Config.Registry));
}
}
}
|
apache-2.0
|
C#
|
9f943765fe994932a3c0f32ce8bc73fbf7b9671f
|
fix UIAutomation ConstructFrom timeOut
|
signumsoftware/framework,signumsoftware/framework,AlejandroCano/extensions,signumsoftware/extensions,AlejandroCano/extensions,signumsoftware/extensions,MehdyKarimpour/extensions,MehdyKarimpour/extensions
|
Signum.Windows.Extensions.UIAutomation/Proxies/ProcessExecutionExtensions.cs
|
Signum.Windows.Extensions.UIAutomation/Proxies/ProcessExecutionExtensions.cs
|
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Processes;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Signum.Windows.UIAutomation
{
public static class ProcessExecutionExtensions
{
static int DefaultTimeout = 20 * 1000;
private static void WaitFinished(this NormalWindowProxy<ProcessDN> pe, Func<string> actionDescription, int? timeout = null)
{
pe.Element.Wait(() => pe.ValueLineValue(pe2 => pe2.State) == ProcessState.Finished,
() => "{0}, result state is {1}".Formato((actionDescription != null ? actionDescription() : "Waiting for process to finish"), pe.ValueLineValue(pe2 => pe2.State)),
timeout ?? DefaultTimeout);
}
public static void ConstructProcessPlayAndWait<T>(this NormalWindowProxy<T> normalWnindow, Enum processOperation, int? timeout = null) where T : ModifiableEntity
{
using (var pe = normalWnindow.ConstructFrom<ProcessDN>(processOperation))
{
pe.Execute(ProcessOperation.Execute);
pe.WaitFinished(() => "Waiting for process after {0} to finish".Formato(OperationDN.UniqueKey(processOperation)), timeout);
}
}
public static void ConstructProcessWait<T>(this NormalWindowProxy<T> normalWnindow, Enum processOperation, int? timeout = null) where T : ModifiableEntity
{
using (var pe = normalWnindow.ConstructFrom<ProcessDN>(processOperation))
{
pe.WaitFinished(() => "Waiting for process after {0} to finish".Formato(OperationDN.UniqueKey(processOperation)), timeout);
}
}
}
}
|
using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Entities.Processes;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Signum.Windows.UIAutomation
{
public static class ProcessExecutionExtensions
{
static int DefaultTimeout = 20 * 1000;
private static void WaitFinished(this NormalWindowProxy<ProcessDN> pe, Func<string> actionDescription, int? timeout = null)
{
pe.Element.Wait(() => pe.ValueLineValue(pe2 => pe2.State) == ProcessState.Finished,
() => "{0}, result state is {1}".Formato((actionDescription != null ? actionDescription() : "Waiting for process to finish"), pe.ValueLineValue(pe2 => pe2.State)),
timeout ?? DefaultTimeout);
}
public static void ConstructProcessPlayAndWait<T>(this NormalWindowProxy<T> normalWnindow, Enum processOperation, int? timeout = null) where T : ModifiableEntity
{
using (var pe = normalWnindow.ConstructFrom<ProcessDN>(processOperation))
{
pe.Execute(ProcessOperation.Execute);
pe.WaitFinished(() => "Waiting for process after {0} to finish".Formato(OperationDN.UniqueKey(processOperation)));
}
}
public static void ConstructProcessWait<T>(this NormalWindowProxy<T> normalWnindow, Enum processOperation, int? timeout = null) where T : ModifiableEntity
{
using (var pe = normalWnindow.ConstructFrom<ProcessDN>(processOperation))
{
pe.WaitFinished(() => "Waiting for process after {0} to finish".Formato(OperationDN.UniqueKey(processOperation)));
}
}
}
}
|
mit
|
C#
|
681e8f45e953dee7703a06dabb31306f11b9224c
|
Add Delete button to TabControlSection to test deleting tabs
|
l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1
|
Source/Eto.Test/Eto.Test/Sections/Controls/TabControlSection.cs
|
Source/Eto.Test/Eto.Test/Sections/Controls/TabControlSection.cs
|
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Controls
{
public class TabControlSection : Panel
{
TabControl tabControl;
public TabControlSection ()
{
Create ();
}
protected virtual void Create ()
{
var layout = new DynamicLayout (this);
layout.AddSeparateRow (null, AddTab (), RemoveTab (), null);
layout.AddSeparateRow (tabControl = DefaultTabs ());
}
Control AddTab ()
{
var control = new Button { Text = "Add Tab" };
control.Click += (s, e) => {
var tab = new TabPage { Text = "Tab " + (tabControl.TabPages.Count + 1) };
tabControl.TabPages.Add (tab);
};
return control;
}
Control RemoveTab ()
{
var control = new Button { Text = "Remove Tab" };
control.Click += (s, e) => {
if (tabControl.SelectedIndex >= 0 && tabControl.TabPages.Count > 0) {
tabControl.TabPages.RemoveAt (tabControl.SelectedIndex);
}
};
return control;
}
TabControl DefaultTabs ()
{
var control = new TabControl ();
LogEvents (control);
var page = new TabPage { Text = "Tab 1" };
page.AddDockedControl (TabOne ());
control.TabPages.Add (page);
LogEvents (page);
page = new TabPage {
Text = "Tab 2",
Image = Icon.FromResource ("Eto.Test.TestIcon.ico")
};
LogEvents (page);
page.AddDockedControl (TabTwo ());
control.TabPages.Add (page);
page = new TabPage {
Text = "Tab 3"
};
LogEvents (page);
control.TabPages.Add (page);
return control;
}
Control TabOne ()
{
var control = new Panel ();
control.AddDockedControl (new LabelSection());
return control;
}
Control TabTwo ()
{
var control = new Panel ();
control.AddDockedControl (new TextAreaSection { Border = BorderType.None });
return control;
}
void LogEvents (TabControl control)
{
control.SelectedIndexChanged += delegate {
Log.Write (control, "SelectedIndexChanged, Index: {0}", control.SelectedIndex);
};
}
void LogEvents (TabPage control)
{
control.Click += delegate {
Log.Write (control, "Click, Item: {0}", control.Text);
};
}
}
public class ThemedTabControlSection : TabControlSection
{
protected override void Create ()
{
// Clone the current generator and add handlers
// for TabControl and TabPage. Create a TabControlSection
// using the new generator and then restore the previous generator.
var currentGenerator = Generator.Current;
try {
var generator = Activator.CreateInstance (currentGenerator.GetType ()) as Generator;
Generator.Initialize (generator);
generator.Add<ITabControl> (() => new Eto.Test.Handlers.TabControlHandler ());
generator.Add<ITabPage> (() => new Eto.Test.Handlers.TabPageHandler ());
base.Create ();
} finally {
Generator.Initialize (currentGenerator); // restore
}
}
}
}
|
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Controls
{
public class TabControlSection : Panel
{
public TabControlSection ()
{
Add();
}
protected virtual void Add()
{
var layout = new DynamicLayout(this);
var tabControl = DefaultTabs();
layout.Add(tabControl);
var button = new Button { Text = "Add Tab" };
button.Click += (s, e) => tabControl.TabPages.Add(new TabPage { Text = "Added" });
layout.Add(button);
}
TabControl DefaultTabs ()
{
var control = new TabControl ();
LogEvents (control);
var page = new TabPage { Text = "Tab 1" };
page.AddDockedControl (TabOne ());
control.TabPages.Add (page);
LogEvents (page);
page = new TabPage {
Text = "Tab 2",
Image = Icon.FromResource ("Eto.Test.TestIcon.ico")
};
LogEvents (page);
page.AddDockedControl (TabTwo ());
control.TabPages.Add (page);
page = new TabPage {
Text = "Tab 3"
};
LogEvents (page);
control.TabPages.Add (page);
return control;
}
Control TabOne ()
{
var control = new Panel ();
control.AddDockedControl (new LabelSection());
return control;
}
Control TabTwo ()
{
var control = new Panel ();
control.AddDockedControl (new TextAreaSection { Border = BorderType.None });
return control;
}
void LogEvents (TabControl control)
{
control.SelectedIndexChanged += delegate {
Log.Write (control, "SelectedIndexChanged, Index: {0}", control.SelectedIndex);
};
}
void LogEvents (TabPage control)
{
control.Click += delegate {
Log.Write (control, "Click, Item: {0}", control.Text);
};
}
}
public class ThemedTabControlSection : TabControlSection
{
protected override void Add()
{
// Clone the current generator and add handlers
// for TabControl and TabPage. Create a TabControlSection
// using the new generator and then restore the previous generator.
var currentGenerator = Generator.Current;
var generator = Activator.CreateInstance(currentGenerator.GetType()) as Generator;
Generator.Initialize(generator);
generator.Add<ITabControl>(() => new Eto.Test.Handlers.TabControlHandler());
generator.Add<ITabPage>(() => new Eto.Test.Handlers.TabPageHandler());
base.Add();
Generator.Initialize(currentGenerator); // restore
}
}
}
|
bsd-3-clause
|
C#
|
b020ff8f7df0cef8b70a35c85b03e7edd726c67b
|
Implement IAsyncPageFilter with DbContextTransactionFilter
|
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
|
SupportManager.Web/Infrastructure/DbContextTransactionFilter.cs
|
SupportManager.Web/Infrastructure/DbContextTransactionFilter.cs
|
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;
namespace SupportManager.Web.Infrastructure
{
public class DbContextTransactionFilter : IAsyncActionFilter, IAsyncPageFilter
{
private readonly SupportManagerContext _dbContext;
public DbContextTransactionFilter(SupportManagerContext dbContext)
{
_dbContext = dbContext;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
try
{
_dbContext.BeginTransaction();
await next();
await _dbContext.CommitTransactionAsync();
}
catch (Exception)
{
_dbContext.RollbackTransaction();
throw;
}
}
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) => Task.CompletedTask;
public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
try
{
_dbContext.BeginTransaction();
var actionExecuted = await next();
if (actionExecuted.Exception != null && !actionExecuted.ExceptionHandled)
{
_dbContext.RollbackTransaction();
}
else
{
await _dbContext.CommitTransactionAsync();
}
}
catch (Exception)
{
_dbContext.RollbackTransaction();
throw;
}
}
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;
namespace SupportManager.Web.Infrastructure
{
public class DbContextTransactionFilter : IAsyncActionFilter
{
private readonly SupportManagerContext _dbContext;
public DbContextTransactionFilter(SupportManagerContext dbContext)
{
_dbContext = dbContext;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
try
{
_dbContext.BeginTransaction();
await next();
await _dbContext.CommitTransactionAsync();
}
catch (Exception)
{
_dbContext.RollbackTransaction();
throw;
}
}
}
}
|
mit
|
C#
|
de7ea3af01c7fcdb44f207588a56c6efdd9ed075
|
Use new "RuntimeDependencies" UBT feature to get our DLLs in place.
|
OSVR/OSVR-Unreal,OSVR/OSVR-Unreal,OSVR/OSVR-Unreal,OSVR/OSVR-Unreal
|
OSVRUnreal/Plugins/OSVR/Source/OSVRClientKit/OSVRClientKit.Build.cs
|
OSVRUnreal/Plugins/OSVR/Source/OSVRClientKit/OSVRClientKit.Build.cs
|
using UnrealBuildTool;
using System.IO;
public class OSVRClientKit : ModuleRules
{
private string ModulePath
{
get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
}
public OSVRClientKit(TargetInfo Target)
{
Type = ModuleType.External;
PublicIncludePaths.Add(ModulePath + "/include");
if ((Target.Platform == UnrealTargetPlatform.Win64)
|| (Target.Platform == UnrealTargetPlatform.Win32))
{
string LibraryPath = ModulePath + "/lib";
string DllPath = ModulePath + "/bin";
if (Target.Platform == UnrealTargetPlatform.Win64)
{
LibraryPath += "/Win64";
DllPath += "/Win64";
}
else if (Target.Platform == UnrealTargetPlatform.Win32)
{
LibraryPath += "/Win32";
DllPath += "/Win32";
}
PublicLibraryPaths.Add(LibraryPath);
PublicAdditionalLibraries.Add("osvrClientKit.lib");
PublicDelayLoadDLLs.AddRange(
new string[] {
"osvrClientKit.dll",
"osvrClient.dll",
"osvrCommon.dll",
"osvrUtil.dll"
});
DllPath += "/";
foreach (var dll in PublicDelayLoadDLLs)
{
RuntimeDependencies.Add(new RuntimeDependency(DllPath + dll));
}
}
}
}
|
using UnrealBuildTool;
using System.IO;
public class OSVRClientKit : ModuleRules
{
private string ModulePath
{
get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
}
public OSVRClientKit(TargetInfo Target)
{
Type = ModuleType.External;
PublicIncludePaths.Add(ModulePath + "/include");
if ((Target.Platform == UnrealTargetPlatform.Win64)
|| (Target.Platform == UnrealTargetPlatform.Win32))
{
string LibraryPath = ModulePath + "/lib";
if (Target.Platform == UnrealTargetPlatform.Win64)
{
LibraryPath += "/Win64";
}
else if (Target.Platform == UnrealTargetPlatform.Win32)
{
LibraryPath += "/Win32";
}
PublicLibraryPaths.Add(LibraryPath);
PublicAdditionalLibraries.Add("osvrClientKit.lib");
PublicDelayLoadDLLs.AddRange(
new string[] {
"osvrClientKit.dll",
"osvrClient.dll",
"osvrCommon.dll",
"osvrUtil.dll"
});
}
}
}
|
apache-2.0
|
C#
|
cbf9668e23c23932352419ff2bb0905620cf1532
|
Update brush test
|
bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto
|
Source/Eto.Test/Eto.Test/Sections/Drawing/TextureBrushesSection2.cs
|
Source/Eto.Test/Eto.Test/Sections/Drawing/TextureBrushesSection2.cs
|
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Drawing
{
class TextureBrushesSection2 : Scrollable
{
Bitmap image = TestIcons.Textures;
PointF location = new PointF(100, 100);
public TextureBrushesSection2()
{
var w = image.Size.Width / 3; // same as height
var img = image.Clone(new Rectangle(w, w, w, w));
var textureBrush = new TextureBrush(img);
var solidBrush = new SolidBrush(Colors.Blue);
var linearGradientBrush = new LinearGradientBrush(Colors.White, Colors.Black, PointF.Empty, new PointF(0, 100));
var drawable = new Drawable();
var font = new Font(SystemFont.Default);
this.Content = drawable;
drawable.BackgroundColor = Colors.Green;
drawable.MouseMove += (s, e) => {
location = e.Location;
drawable.Invalidate(); };
drawable.Paint += (s, e) => {
var g = e.Graphics;
g.DrawText(font, Colors.White, 3, 3, "Move the mouse in this area to move the shapes.");
// texture brushes
var temp = location;
DrawShapes(textureBrush, img.Size, g);
// solid brushes
location = temp + new PointF(200, 0);
DrawShapes(solidBrush, img.Size, g);
// linear gradient brushes
location = temp + new PointF(400, 0);
DrawShapes(linearGradientBrush, img.Size, g);
};
}
void DrawShapes(Brush brush, Size size, Graphics g)
{
g.SaveTransform();
g.MultiplyTransform(Matrix.FromRotationAt(20, location));
// rectangle
g.FillRectangle(brush, new RectangleF(location, size));
// ellipse
location += new PointF(0, size.Height + 20);
g.FillEllipse(brush, new RectangleF(location, size));
// pie
location += new PointF(0, size.Height + 20);
g.FillPie(brush, new RectangleF(location, new SizeF(size.Width * 2, size.Height)), 0, 360);
// polygon
location += new PointF(0, size.Height + 20);
var polygon = GetPolygon(location);
g.FillPolygon(brush, polygon);
g.RestoreTransform();
}
static PointF[] GetPolygon(PointF location)
{
var polygon = new PointF[] { new PointF(0, 50), new PointF(50, 100), new PointF(100, 50), new PointF(50, 0) };
for (var i = 0; i < polygon.Length; ++i)
polygon[i] += location;
return polygon;
}
}
}
|
using System;
using Eto.Forms;
using Eto.Drawing;
namespace Eto.Test.Sections.Drawing
{
class TextureBrushesSection2 : Scrollable
{
Bitmap image = TestIcons.Textures;
PointF location = new PointF(100, 100);
public TextureBrushesSection2()
{
var w = image.Size.Width / 3; // same as height
var img = image.Clone(new Rectangle(w, w, w, w));
var textureBrush = new TextureBrush(img);
var solidBrush = new SolidBrush(Colors.Blue);
var linearGradientBrush = new LinearGradientBrush(Colors.White, Colors.Black, PointF.Empty, new PointF(0, 100));
var drawable = new Drawable();
var font = new Font(SystemFont.Default);
this.Content = drawable;
drawable.BackgroundColor = Colors.Green;
drawable.MouseMove += (s, e) => {
location = e.Location;
drawable.Invalidate(); };
drawable.Paint += (s, e) => {
e.Graphics.DrawText(font, Colors.White, 3, 3, "Move the mouse in this area to move the shapes.");
// texture brushes
var temp = location;
DrawShapes(textureBrush, img.Size, e.Graphics);
// solid brushes
location = temp + new PointF(200, 0);
DrawShapes(solidBrush, img.Size, e.Graphics);
// linear gradient brushes
location = temp + new PointF(400, 0);
DrawShapes(linearGradientBrush, img.Size, e.Graphics);
};
}
private void DrawShapes(Brush brush, Size size, Graphics g)
{
// rectangle
g.FillRectangle(brush, new RectangleF(location, size));
// ellipse
location += new PointF(0, size.Height + 20);
g.FillEllipse(brush, new RectangleF(location, size));
// pie
location += new PointF(0, size.Height + 20);
g.FillPie(brush, new RectangleF(location, new SizeF(size.Width * 2, size.Height)), 0, 360);
// polygon
location += new PointF(0, size.Height + 20);
var polygon = GetPolygon(location);
g.FillPolygon(brush, polygon);
}
private static PointF[] GetPolygon(PointF location)
{
var polygon = new PointF[] { new PointF(0, 50), new PointF(50, 100), new PointF(100, 50), new PointF(50, 0) };
for (var i = 0; i < polygon.Length; ++i)
polygon[i] += location;
return polygon;
}
}
}
|
bsd-3-clause
|
C#
|
5d768c136655c81ebba8387ef50295abde521571
|
Add documentation for pagination list results.
|
henrikfroehling/TraktApiSharp
|
Source/Lib/TraktApiSharp/Objects/Basic/TraktPaginationListResult.cs
|
Source/Lib/TraktApiSharp/Objects/Basic/TraktPaginationListResult.cs
|
namespace TraktApiSharp.Objects.Basic
{
using System.Collections.Generic;
/// <summary>
/// Represents results of requests supporting pagination.<para />
/// Contains the current page, the item limitation per page, the total page count, the total item count
/// and can also contain the total user count (e.g. in trending shows and movies requests).
/// </summary>
/// <typeparam name="ListItem">The underlying item type of the list results.</typeparam>
public class TraktPaginationListResult<ListItem>
{
/// <summary>Gets or sets the actual list results.</summary>
public IEnumerable<ListItem> Items { get; set; }
/// <summary>Gets or sets the current page number.</summary>
public int? Page { get; set; }
/// <summary>Gets or sets the item limitation per page.</summary>
public int? Limit { get; set; }
/// <summary>Gets or sets the total page count.</summary>
public int? PageCount { get; set; }
/// <summary>Gets or sets the total item results count.</summary>
public int? ItemCount { get; set; }
/// <summary>
/// Gets or sets the total user count.
/// <para>
/// May be only supported for trending shows and movies requests.
/// </para>
/// </summary>
public int? UserCount { get; set; }
}
}
|
namespace TraktApiSharp.Objects.Basic
{
using System.Collections.Generic;
public class TraktPaginationListResult<ListItem>
{
public IEnumerable<ListItem> Items { get; set; }
public int? Page { get; set; }
public int? Limit { get; set; }
public int? PageCount { get; set; }
public int? ItemCount { get; set; }
public int? UserCount { get; set; }
}
}
|
mit
|
C#
|
b8a1f29d90d37ed6d4c3662ee95e340ace23bc3d
|
clean up
|
dkataskin/bstrkr
|
bstrkr.mobile/bstrkr.core/Services/Location/PositioningService.cs
|
bstrkr.mobile/bstrkr.core/Services/Location/PositioningService.cs
|
using System;
using bstrkr.core;
using bstrkr.core.services.location;
using bstrkr.core.spatial;
namespace bstrkr.core.services.location
{
public class PositioningService : IPositioningService
{
private readonly ILocationService _locationService;
private readonly IAreaPositioningService _areaPositioningService;
public PositioningService(ILocationService locationService, IAreaPositioningService areaPositioningService)
{
_locationService = locationService;
_areaPositioningService = areaPositioningService;
_areaPositioningService.AreaLocated += (s, a) => this.RaiseAreaChangedEvent(
this.CurrentArea,
this.DetectedArea,
_locationService.GetLastLocation());
}
public event EventHandler<AreaChangedEventArgs> AreaChanged;
public Area CurrentArea { get { return _areaPositioningService.Area; } }
public bool DetectedArea { get { return _areaPositioningService.DetectedArea; } }
public GeoPoint GetLastLocation()
{
if (this.CurrentArea == null)
{
return GeoPoint.Empty;
}
if (DetectedArea)
{
return _locationService.GetLastLocation();
}
return new GeoPoint(this.CurrentArea.Latitude, this.CurrentArea.Longitude);
}
public void Start()
{
_areaPositioningService.Start();
}
public void Stop()
{
_areaPositioningService.Stop();
}
private void RaiseAreaChangedEvent(Area area, bool detected, GeoPoint lastLocation)
{
if (this.AreaChanged != null)
{
this.AreaChanged(this, new AreaChangedEventArgs(area, detected, lastLocation));
}
}
}
}
|
using System;
using bstrkr.core;
using bstrkr.core.services.location;
using bstrkr.core.spatial;
namespace Services.Location
{
public class PositioningService : IPositioningService
{
private readonly ILocationService _locationService;
private readonly IAreaPositioningService _areaPositioningService;
public PositioningService(ILocationService locationService, IAreaPositioningService areaPositioningService)
{
_locationService = locationService;
_areaPositioningService = areaPositioningService;
_areaPositioningService.AreaLocated += (s, a) => this.RaiseAreaChangedEvent(
this.CurrentArea,
this.DetectedArea,
_locationService.GetLastLocation());
}
public event EventHandler<AreaChangedEventArgs> AreaChanged;
public Area CurrentArea { get { return _areaPositioningService.Area; } }
public bool DetectedArea { get { return _areaPositioningService.DetectedArea; } }
public GeoPoint GetLastLocation()
{
if (this.CurrentArea == null)
{
return GeoPoint.Empty;
}
if (DetectedArea)
{
return _locationService.GetLastLocation();
}
return new GeoPoint(this.CurrentArea.Latitude, this.CurrentArea.Longitude);
}
public void Start()
{
_areaPositioningService.Start();
}
public void Stop()
{
_areaPositioningService.Stop();
}
private void RaiseAreaChangedEvent(Area area, bool detected, GeoPoint lastLocation)
{
if (this.AreaChanged != null)
{
this.AreaChanged(this, new AreaChangedEventArgs(area, detected, lastLocation));
}
}
}
}
|
bsd-2-clause
|
C#
|
0877c6c295dbae22fb6d7e759f94fb981406e595
|
Fix for WebExceptionResponse
|
NeptuneCenturyStudios/KryptPad
|
KryptPadCSApp/API/Responses/WebExceptionResponse.cs
|
KryptPadCSApp/API/Responses/WebExceptionResponse.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace KryptPadCSApp.API.Responses
{
class WebExceptionResponse : ApiResponse
{
public string Message { get; set; }
public IDictionary<string, string[]> ModelState { get; set; }
/// <summary>
/// Converts this WebExceptionResponse to an Exception object
/// </summary>
/// <returns></returns>
public Exception ToException()
{
var msg = Message;
// Check for model state errors
if (ModelState != null)
{
var modelErrors = new List<string>();
// Build string of model state errors
foreach(var ms in ModelState)
{
// Each model state error can have multiple errors
foreach (var error in ms.Value)
{
modelErrors.Add(error);
}
}
// Set errors to msg
msg = string.Join("\n", modelErrors);
}
return new Exception(msg);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace KryptPadCSApp.API.Responses
{
class WebExceptionResponse : ApiResponse
{
public string Message { get; set; }
public IDictionary<string, string[]> ModelState { get; set; }
/// <summary>
/// Converts this WebExceptionResponse to an Exception object
/// </summary>
/// <returns></returns>
public Exception ToException()
{
var msg = Message + ModelState.ToString();
return new Exception(msg);
}
}
}
|
mit
|
C#
|
deda1c83e67779a748d82138215846519dbcfea7
|
Add failing test case
|
peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu
|
osu.Game.Tests/Visual/UserInterface/TestSceneSettingsToolboxGroup.cs
|
osu.Game.Tests/Visual/UserInterface/TestSceneSettingsToolboxGroup.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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osu.Game.Screens.Play.HUD;
using osu.Game.Screens.Play.PlayerSettings;
using osuTK.Input;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneSettingsToolboxGroup : OsuManualInputManagerTestScene
{
public TestSceneSettingsToolboxGroup()
{
ExampleContainer container;
Add(new PlayerSettingsOverlay
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
State = { Value = Visibility.Visible }
});
Add(container = new ExampleContainer());
AddStep(@"Add button", () => container.Add(new TriangleButton
{
RelativeSizeAxes = Axes.X,
Text = @"Button",
}));
AddStep(@"Add checkbox", () => container.Add(new PlayerCheckbox
{
LabelText = "Checkbox",
}));
AddStep(@"Add textbox", () => container.Add(new FocusedTextBox
{
RelativeSizeAxes = Axes.X,
Height = 30,
PlaceholderText = "Textbox",
HoldFocus = false,
}));
}
[Test]
public void TestClickExpandButtonMultipleTimes()
{
SettingsToolboxGroup group = null;
AddAssert("group expanded by default", () => (group = this.ChildrenOfType<SettingsToolboxGroup>().First()).Expanded.Value);
AddStep("click expand button multiple times", () =>
{
InputManager.MoveMouseTo(group.ChildrenOfType<IconButton>().Single());
Scheduler.AddDelayed(() => InputManager.Click(MouseButton.Left), 100);
Scheduler.AddDelayed(() => InputManager.Click(MouseButton.Left), 200);
Scheduler.AddDelayed(() => InputManager.Click(MouseButton.Left), 300);
});
AddAssert("group contracted", () => !group.Expanded.Value);
}
private class ExampleContainer : PlayerSettingsGroup
{
public ExampleContainer()
: base("example")
{
}
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play.HUD;
using osu.Game.Screens.Play.PlayerSettings;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneSettingsToolboxGroup : OsuTestScene
{
public TestSceneSettingsToolboxGroup()
{
ExampleContainer container;
Add(new PlayerSettingsOverlay
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
State = { Value = Visibility.Visible }
});
Add(container = new ExampleContainer());
AddStep(@"Add button", () => container.Add(new TriangleButton
{
RelativeSizeAxes = Axes.X,
Text = @"Button",
}));
AddStep(@"Add checkbox", () => container.Add(new PlayerCheckbox
{
LabelText = "Checkbox",
}));
AddStep(@"Add textbox", () => container.Add(new FocusedTextBox
{
RelativeSizeAxes = Axes.X,
Height = 30,
PlaceholderText = "Textbox",
HoldFocus = false,
}));
}
private class ExampleContainer : PlayerSettingsGroup
{
public ExampleContainer()
: base("example")
{
}
}
}
}
|
mit
|
C#
|
b50473292265f56bd3fc3e9b6771d97c22f71f2c
|
Allow identity on any DB type that maps to an INTEGER
|
fluentmigrator/fluentmigrator,stsrki/fluentmigrator,stsrki/fluentmigrator,fluentmigrator/fluentmigrator
|
src/FluentMigrator.Runner.SQLite/Generators/SQLite/SQLiteColumn.cs
|
src/FluentMigrator.Runner.SQLite/Generators/SQLite/SQLiteColumn.cs
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators.Base;
namespace FluentMigrator.Runner.Generators.SQLite
{
// ReSharper disable once InconsistentNaming
internal class SQLiteColumn : ColumnBase
{
public SQLiteColumn()
: base(new SQLiteTypeMap(), new SQLiteQuoter())
{
}
/// <inheritdoc />
public override string Generate(IEnumerable<ColumnDefinition> columns, string tableName)
{
var colDefs = columns.ToList();
var foreignKeyColumns = colDefs.Where(x => x.IsForeignKey && x.ForeignKey != null);
var foreignKeyClauses = foreignKeyColumns
.Select(x => ", " + FormatForeignKey(x.ForeignKey, GenerateForeignKeyName));
// Append foreign key definitions after all column definitions and the primary key definition
return base.Generate(colDefs, tableName) + string.Concat(foreignKeyClauses);
}
/// <inheritdoc />
protected override string FormatIdentity(ColumnDefinition column)
{
// SQLite only supports the concept of Identity in combination with a single integer primary key
// see: http://www.sqlite.org/syntaxdiagrams.html#column-constraint syntax details
if (column.IsIdentity && !column.IsPrimaryKey && (!column.Type.HasValue || GetTypeMap(column.Type.Value, null, null) != "INTEGER"))
{
throw new ArgumentException("SQLite only supports identity on a single integer, primary key coulmns");
}
return "AUTOINCREMENT";
}
/// <inheritdoc />
public override bool ShouldPrimaryKeysBeAddedSeparately(IEnumerable<ColumnDefinition> primaryKeyColumns)
{
//If there are no identity column then we can add as a separate constrint
var pkColDefs = primaryKeyColumns.ToList();
return !pkColDefs.Any(x => x.IsIdentity) && pkColDefs.Any(x => x.IsPrimaryKey);
}
/// <inheritdoc />
protected override string FormatPrimaryKey(ColumnDefinition column)
{
if (!column.IsPrimaryKey)
{
return string.Empty;
}
return column.IsIdentity ? "PRIMARY KEY AUTOINCREMENT" : string.Empty;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators.Base;
namespace FluentMigrator.Runner.Generators.SQLite
{
// ReSharper disable once InconsistentNaming
internal class SQLiteColumn : ColumnBase
{
public SQLiteColumn()
: base(new SQLiteTypeMap(), new SQLiteQuoter())
{
}
/// <inheritdoc />
public override string Generate(IEnumerable<ColumnDefinition> columns, string tableName)
{
var colDefs = columns.ToList();
var foreignKeyColumns = colDefs.Where(x => x.IsForeignKey && x.ForeignKey != null);
var foreignKeyClauses = foreignKeyColumns
.Select(x => ", " + FormatForeignKey(x.ForeignKey, GenerateForeignKeyName));
// Append foreign key definitions after all column definitions and the primary key definition
return base.Generate(colDefs, tableName) + string.Concat(foreignKeyClauses);
}
/// <inheritdoc />
protected override string FormatIdentity(ColumnDefinition column)
{
//SQLite only supports the concept of Identity in combination with a single primary key
//see: http://www.sqlite.org/syntaxdiagrams.html#column-constraint syntax details
if (column.IsIdentity && !column.IsPrimaryKey && column.Type != DbType.Int32)
{
throw new ArgumentException("SQLite only supports identity on single integer, primary key coulmns");
}
return string.Empty;
}
/// <inheritdoc />
public override bool ShouldPrimaryKeysBeAddedSeparately(IEnumerable<ColumnDefinition> primaryKeyColumns)
{
//If there are no identity column then we can add as a separate constrint
var pkColDefs = primaryKeyColumns.ToList();
return !pkColDefs.Any(x => x.IsIdentity) && pkColDefs.Any(x => x.IsPrimaryKey);
}
/// <inheritdoc />
protected override string FormatPrimaryKey(ColumnDefinition column)
{
if (!column.IsPrimaryKey)
{
return string.Empty;
}
return column.IsIdentity ? "PRIMARY KEY AUTOINCREMENT" : string.Empty;
}
}
}
|
apache-2.0
|
C#
|
ddfe37336834f50d31cf2137b259ea64dc49eb1d
|
Bump version to 1.0.3.
|
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
|
AssemblyVersion.cs
|
AssemblyVersion.cs
|
using System.Reflection;
[assembly: AssemblyVersion("1.0.3")]
[assembly: AssemblyFileVersion("1.0.3")]
|
using System.Reflection;
[assembly: AssemblyVersion("1.0.2")]
[assembly: AssemblyFileVersion("1.0.2")]
|
mit
|
C#
|
41078384e6c92418e61242dd8d5ce2083f0eec63
|
Add Initial User API tests
|
navalev/nether,stuartleeks/nether,oliviak/nether,vflorusso/nether,navalev/nether,stuartleeks/nether,ankodu/nether,ankodu/nether,navalev/nether,MicrosoftDX/nether,brentstineman/nether,stuartleeks/nether,vflorusso/nether,ankodu/nether,stuartleeks/nether,brentstineman/nether,ankodu/nether,brentstineman/nether,krist00fer/nether,vflorusso/nether,stuartleeks/nether,brentstineman/nether,vflorusso/nether,navalev/nether,brentstineman/nether,vflorusso/nether
|
tests/Nether.Web.IntegrationTests/Identity/UserApiTests.cs
|
tests/Nether.Web.IntegrationTests/Identity/UserApiTests.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Nether.Web.IntegrationTests.Identity
{
public class UserApiTests : WebTestBase
{
private HttpClient _client;
[Fact]
public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers()
{
await AsPlayerAsync();
await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.Forbidden);
}
private async Task<HttpResponseMessage> ResponseForGetAsync(string path, HttpStatusCode hasStatusCode)
{
var response = await _client.GetAsync(path);
Assert.Equal(hasStatusCode, response.StatusCode);
return response;
}
private async Task AsPlayerAsync()
{
_client = await GetClientAsync(username: "testuser", setPlayerGamertag: true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Nether.Web.IntegrationTests.Identity
{
public class UserApiTests : WebTestBase
{
private HttpClient _client;
//[Fact]
//public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers()
//{
// AsPlayer();
// ResponseForGet("/users", hasStatusCode: HttpStatusCode.Forbidden);
//}
//private void ResponseForGet(string path, HttpStatusCode hasStatusCode)
//{
// _client.GetAsync
//}
//private void AsPlayer()
//{
// _client = GetClient(username:"testuser", isPlayer: true);
//}
}
}
|
mit
|
C#
|
db32f5b8a61a3b4d570246ca80bae610c5c58600
|
Rename var
|
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
|
R7.University.Core/Components/UniversityAssembly.cs
|
R7.University.Core/Components/UniversityAssembly.cs
|
using System.Reflection;
namespace R7.University.Components
{
public static class UniversityAssembly
{
public static Assembly GetBaseAssembly ()
{
return Assembly.GetExecutingAssembly ();
}
public static string SafeGetInformationalVersion (int fieldCount)
{
var baseAssembly = GetBaseAssembly ();
var attr = baseAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute> ();
if (attr != null) {
return attr.InformationalVersion;
}
return baseAssembly.GetName ().Version.ToString (fieldCount);
}
}
}
|
using System.Reflection;
namespace R7.University.Components
{
public static class UniversityAssembly
{
public static Assembly GetBaseAssembly ()
{
return Assembly.GetExecutingAssembly ();
}
public static string SafeGetInformationalVersion (int fieldCount)
{
var coreAssembly = GetBaseAssembly ();
var attr = coreAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute> ();
if (attr != null) {
return attr.InformationalVersion;
}
return coreAssembly.GetName ().Version.ToString (fieldCount);
}
}
}
|
agpl-3.0
|
C#
|
93f9848d202956d1b89fc3a79692a8cb3abf25b4
|
Update src/Website/Views/Documentation/v2/HtmlTemplates/JQueryTmpl.cshtml
|
andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette,andrewdavey/cassette,andrewdavey/cassette,damiensawyer/cassette,honestegg/cassette,damiensawyer/cassette,honestegg/cassette
|
src/Website/Views/Documentation/v2/HtmlTemplates/JQueryTmpl.cshtml
|
src/Website/Views/Documentation/v2/HtmlTemplates/JQueryTmpl.cshtml
|
@{
ViewBag.Title = "Cassette | jQuery-tmpl Template Compilation";
}
<h1>jQuery-tmpl Template Compilation</h1>
<p>jQuery-tmpl templates are usually embedded into a page using non-executing script blocks.
The browser then compiles these into JavaScript functions at runtime. This may be fast in modern
browsers, but given a lot of templates and a slower mobile browser, you may notice the slow down.</p>
<p>Cassette enables you to pre-compile jQuery-tmpl templates into JavaScript on the server-side.
The compiled templates are cached and served to the browser as a regular script. This also provides all the
benefits of Cassette's bundle versioning and caching.
</p>
<p>The compiled template functions are loaded directly into jQuery-tmpl, with no runtime overhead.</p>
<h2>Install Cassette.JQueryTmpl</h2>
<p>Install the package from nuget:</p>
<pre><code>Install-Package Cassette.JQueryTmpl</code></pre>
<h2>Bundle configuration</h2>
<p>
No additional bundle configuration is required.
The plug-in replaces the default HTML template pipeline.
</p>
<p>So your configuration will still look similar to this:</p>
<pre><code>bundles.Add<<span class="code-type">HtmlTemplateBundle</span>>(<span class="string">"HtmlTemplates"</span>);</code></pre>
<h2>Using in pages</h2>
<p>In a view page, reference your templates just like any other bundle:</p>
<pre><code><span class="code-tag">@@{</span>
<span class="code-type">Bundles</span>.Reference(<span class="string">"HtmlTemplates"</span>);
}</code></pre>
<p>Also, tell Cassette where to render the HTML required to include the templates:</p>
<pre><code><span class="code-tag">@@</span><span class="razor-expression"><span class="code-type">Bundles</span>.RenderHtmlTemplates()</span></code></pre>
<p>Now when the page runs, instead of embedding the template sources into the page, a single script include is generated:</p>
<pre><code><span class="open-tag"><</span><span class="tag">script</span> <span class="attribute">src</span><span class="attribute-value">="/cassette.axd/htmltemplate/HtmlTemplates_7d879cec"</span> <span class="attribute">type</span><span class="attribute-value">="text/javascript"</span><span class="close-tag">></span><span class="open-tag"></</span><span class="tag">script</span><span class="close-tag">></span></code></pre>
<p>This script contains the templates compiled into JavaScript. Like all Cassette bundles, it is versioned and cached aggresively.
So a browser only needs to download it once.</p>
|
@{
ViewBag.Title = "Cassette | jQuery-tmpl Template Compilation";
}
<h1>jQuery-tmpl Template Compilation</h1>
<p>jQuery-tmpl templates are usually embedded into a page using non-executing script blocks.
The browser then compiles these into JavaScript functions at runtime. This may be fast in modern
browsers, but given a lot of templates and a slower mobile browser, you may notice the slow down.</p>
<p>Cassette enables you to pre-compile jQuery-tmpl templates into JavaScript on the server-side.
The compiled templates are cached and served to the browser as a regular script. This also provides all the
benefits of Cassette's bundle versioning and caching.
</p>
<p>The compiled template functions are loaded directly into jQuery-tmpl, with no runtime overhead.</p>
<h2>Install Cassette.JQueryTmpl</h2>
<p>Install the package from nuget:</p>
<pre><code>Install-Package Cassette.JQueryTmpl</code></pre>
<h2>Bundle configuration</h2>
<p>
No additional bundle configuration is required.
The plug-in replaces the default HTML template pipeline.
</p>
<p>So your configuration will still look similar to this:</p>
<pre><code>bundles.Add<<span class="code-type">HtmlTemplate</span>>(<span class="string">"HtmlTemplates"</span>);</code></pre>
<h2>Using in pages</h2>
<p>In a view page, reference your templates just like any other bundle:</p>
<pre><code><span class="code-tag">@@{</span>
<span class="code-type">Bundles</span>.Reference(<span class="string">"HtmlTemplates"</span>);
}</code></pre>
<p>Also, tell Cassette where to render the HTML required to include the templates:</p>
<pre><code><span class="code-tag">@@</span><span class="razor-expression"><span class="code-type">Bundles</span>.RenderHtmlTemplates()</span></code></pre>
<p>Now when the page runs, instead of embedding the template sources into the page, a single script include is generated:</p>
<pre><code><span class="open-tag"><</span><span class="tag">script</span> <span class="attribute">src</span><span class="attribute-value">="/cassette.axd/htmltemplate/HtmlTemplates_7d879cec"</span> <span class="attribute">type</span><span class="attribute-value">="text/javascript"</span><span class="close-tag">></span><span class="open-tag"></</span><span class="tag">script</span><span class="close-tag">></span></code></pre>
<p>This script contains the templates compiled into JavaScript. Like all Cassette bundles, it is versioned and cached aggresively.
So a browser only needs to download it once.</p>
|
mit
|
C#
|
528b8f1e743b66d5c01a045e51de5196ed4ea9d1
|
Add ConfAwait
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Services/Terminate/TerminateService.cs
|
WalletWasabi/Services/Terminate/TerminateService.cs
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning("Process was signaled for termination.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// This will terminate the application. This is a blocking method and no return after this call as it will exit the application.
/// </summary>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Terminate application was started.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning("Process was signaled for termination.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// This will terminate the application. This is a blocking method and no return after this call as it will exit the application.
/// </summary>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Terminate application was started.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync();
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
|
mit
|
C#
|
679aa2165dbb8f39434d985de8595301c8f65b8f
|
Set default trivia timeout to match help text.
|
Nielk1/NadekoBot,ShadowNoire/NadekoBot,ScarletKuro/NadekoBot
|
NadekoBot.Core/Modules/Games/Common/Trivia/TriviaOptions.cs
|
NadekoBot.Core/Modules/Games/Common/Trivia/TriviaOptions.cs
|
using CommandLine;
using NadekoBot.Core.Common;
namespace NadekoBot.Core.Modules.Games.Common.Trivia
{
public class TriviaOptions : INadekoCommandOptions
{
[Option('p', "pokemon", Required = false, Default = false, HelpText = "Whether it's 'Who's that pokemon?' trivia.")]
public bool IsPokemon { get; set; } = false;
[Option("nohint", Required = false, Default = false, HelpText = "Don't show any hints.")]
public bool NoHint { get; set; } = false;
[Option('w', "win-req", Required = false, Default = 10, HelpText = "Winning requirement. Set 0 for an infinite game. Default 10.")]
public int WinRequirement { get; set; } = 10;
[Option('q', "question-timer", Required = false, Default = 30, HelpText = "How long until the question ends. Default 30.")]
public int QuestionTimer { get; set; } = 30;
[Option('t', "timeout", Required = false, Default = 10, HelpText = "Number of questions of inactivity in order stop. Set 0 for never. Default 10.")]
public int Timeout { get; set; } = 10;
public void NormalizeOptions()
{
if (WinRequirement < 0)
WinRequirement = 10;
if (QuestionTimer < 10 || QuestionTimer > 300)
QuestionTimer = 30;
if (Timeout < 0 || Timeout > 20)
Timeout = 10;
}
}
}
|
using CommandLine;
using NadekoBot.Core.Common;
namespace NadekoBot.Core.Modules.Games.Common.Trivia
{
public class TriviaOptions : INadekoCommandOptions
{
[Option('p', "pokemon", Required = false, Default = false, HelpText = "Whether it's 'Who's that pokemon?' trivia.")]
public bool IsPokemon { get; set; } = false;
[Option("nohint", Required = false, Default = false, HelpText = "Don't show any hints.")]
public bool NoHint { get; set; } = false;
[Option('w', "win-req", Required = false, Default = 10, HelpText = "Winning requirement. Set 0 for an infinite game. Default 10.")]
public int WinRequirement { get; set; } = 10;
[Option('q', "question-timer", Required = false, Default = 30, HelpText = "How long until the question ends. Default 30.")]
public int QuestionTimer { get; set; } = 30;
[Option('t', "timeout", Required = false, Default = 0, HelpText = "Number of questions of inactivity in order stop. Set 0 for never. Default 10.")]
public int Timeout { get; set; } = 10;
public void NormalizeOptions()
{
if (WinRequirement < 0)
WinRequirement = 10;
if (QuestionTimer < 10 || QuestionTimer > 300)
QuestionTimer = 30;
if (Timeout < 0 || Timeout > 20)
Timeout = 10;
}
}
}
|
mit
|
C#
|
0602f5448bc19f206212516a456836521947ae23
|
Add support for `confirmation_method` on `PaymentIntent`
|
stripe/stripe-dotnet,richardlawley/stripe.net
|
src/Stripe.net/Services/PaymentIntents/PaymentIntentCreateOptions.cs
|
src/Stripe.net/Services/PaymentIntents/PaymentIntentCreateOptions.cs
|
namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class PaymentIntentCreateOptions : PaymentIntentSharedOptions
{
[JsonProperty("capture_method")]
public string CaptureMethod { get; set; }
[JsonProperty("confirm")]
public bool? Confirm { get; set; }
[JsonProperty("confirmation_method")]
public string ConfirmationMethod { get; set; }
[JsonProperty("return_url")]
public string ReturnUrl { get; set; }
[JsonProperty("statement_descriptor")]
public string StatementDescriptor { get; set; }
}
}
|
namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class PaymentIntentCreateOptions : PaymentIntentSharedOptions
{
[JsonProperty("capture_method")]
public string CaptureMethod { get; set; }
[JsonProperty("confirm")]
public bool? Confirm { get; set; }
[JsonProperty("return_url")]
public string ReturnUrl { get; set; }
[JsonProperty("statement_descriptor")]
public string StatementDescriptor { get; set; }
}
}
|
apache-2.0
|
C#
|
07d21830cbeb81ccdfc0fd9ae83263c35ddb7ec6
|
Switch to ValueTask
|
shyamnamboodiripad/roslyn,KevinRansom/roslyn,wvdd007/roslyn,sharwell/roslyn,physhi/roslyn,weltkante/roslyn,KevinRansom/roslyn,mavasani/roslyn,eriawan/roslyn,mavasani/roslyn,physhi/roslyn,KevinRansom/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,AmadeusW/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,bartdesmet/roslyn,weltkante/roslyn,mavasani/roslyn,physhi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,dotnet/roslyn,weltkante/roslyn,wvdd007/roslyn,diryboy/roslyn,AmadeusW/roslyn,eriawan/roslyn,bartdesmet/roslyn,dotnet/roslyn
|
src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptVisualStudioProjectFactory.cs
|
src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptVisualStudioProjectFactory.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal interface IVsTypeScriptVisualStudioProjectFactory
{
[Obsolete("Use CreateAndAddToWorkspaceAsync instead")]
VSTypeScriptVisualStudioProjectWrapper CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid);
ValueTask<VSTypeScriptVisualStudioProjectWrapper> CreateAndAddToWorkspaceAsync(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid, CancellationToken cancellationToken);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal interface IVsTypeScriptVisualStudioProjectFactory
{
[Obsolete("Use CreateAndAddToWorkspaceAsync instead")]
VSTypeScriptVisualStudioProjectWrapper CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid);
Task<VSTypeScriptVisualStudioProjectWrapper> CreateAndAddToWorkspaceAsync(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid, CancellationToken cancellationToken);
}
}
|
mit
|
C#
|
82717f2441bb3f081d0f29d8802efebbdb1a1e53
|
Fix bug when pre-registered activator is instance
|
OrleansContrib/Orleankka,OrleansContrib/Orleankka,mhertis/Orleankka,mhertis/Orleankka
|
Source/Orleankka.Runtime/Cluster/ServiceCollectionExtensions.cs
|
Source/Orleankka.Runtime/Cluster/ServiceCollectionExtensions.cs
|
using System;
using System.Linq;
namespace Orleankka.Cluster
{
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
static class ServiceCollectionExtensions
{
public static void Decorate<T>(this IServiceCollection services, Func<T, T> decorator) where T : class
{
var registered = services.First(s => s.ServiceType == typeof(T));
var factory = registered.ImplementationFactory;
if (factory == null && registered.ImplementationType != null)
services.TryAddSingleton(registered.ImplementationType);
services.Replace(new ServiceDescriptor(typeof(T), sp =>
{
var inner = registered.ImplementationInstance;
if (inner != null)
return decorator((T) inner);
inner = factory == null
? sp.GetService(registered.ImplementationType)
: factory(sp);
return decorator((T) inner);
},
registered.Lifetime));
}
}
}
|
using System;
using System.Linq;
namespace Orleankka.Cluster
{
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
static class ServiceCollectionExtensions
{
public static void Decorate<T>(this IServiceCollection services, Func<T, T> decorator) where T : class
{
var registered = services.First(s => s.ServiceType == typeof(T));
var factory = registered.ImplementationFactory;
if (factory == null)
services.TryAddSingleton(registered.ImplementationType);
services.Replace(new ServiceDescriptor(typeof(T), sp =>
{
var inner = factory == null
? sp.GetService(registered.ImplementationType)
: factory(sp);
return decorator((T) inner);
},
registered.Lifetime));
}
}
}
|
apache-2.0
|
C#
|
936aaa17bb22a20450a71a3bae6e9c2f039e2c1d
|
fix tests
|
jezzay/Test-Travis-CI,jezzay/Test-Travis-CI
|
TestWebApp/TestWebApp.Tests/Controllers/ValuesControllerTest.cs
|
TestWebApp/TestWebApp.Tests/Controllers/ValuesControllerTest.cs
|
using System.Collections.Generic;
using System.Linq;
using TestWebApp.Controllers;
using Xunit;
namespace TestWebApp.Tests.Controllers
{
public class ValuesControllerTest
{
[Fact]
public void Get()
{
// Arrange
var controller = new ValuesController();
// Act
IEnumerable<string> result = controller.Get();
// Assert
Assert.NotNull(result);
Assert.Equal(2, result.Count());
Assert.Equal("value1", result.ElementAt(0));
Assert.Equal("value2", result.ElementAt(1));
}
[Fact]
public void GetById()
{
// Arrange
var controller = new ValuesController();
// Act
string result = controller.Get(5);
// Assert
Assert.Equal("value", result);
}
[Fact]
public void Post()
{
// Arrange
var controller = new ValuesController();
// Act
controller.Post("value");
// Assert
}
[Fact]
public void Put()
{
// Arrange
var controller = new ValuesController();
// Act
controller.Put(5, "value");
// Assert
}
[Fact]
public void Delete()
{
// Arrange
var controller = new ValuesController();
// Act
controller.Delete(5);
// Assert
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using TestWebApp.Controllers;
using Xunit;
namespace TestWebApp.Tests.Controllers
{
public class ValuesControllerTest
{
public void Get()
{
// Arrange
var controller = new ValuesController();
// Act
IEnumerable<string> result = controller.Get();
// Assert
Assert.NotNull(result);
Assert.Equal(2, result.Count());
Assert.Equal("value1", result.ElementAt(0));
Assert.Equal("value2", result.ElementAt(1));
}
public void GetById()
{
// Arrange
var controller = new ValuesController();
// Act
string result = controller.Get(5);
// Assert
Assert.Equal("value", result);
}
public void Post()
{
// Arrange
var controller = new ValuesController();
// Act
controller.Post("value");
// Assert
}
public void Put()
{
// Arrange
var controller = new ValuesController();
// Act
controller.Put(5, "value");
// Assert
}
public void Delete()
{
// Arrange
var controller = new ValuesController();
// Act
controller.Delete(5);
// Assert
}
}
}
|
mit
|
C#
|
57c79ced2f70579662a229052f22012472cec015
|
Add XML docs + remove code todo
|
HalidCisse/Humanizer,mexx/Humanizer,schalpat/Humanizer,thunsaker/Humanizer,hazzik/Humanizer,micdenny/Humanizer,nigel-sampson/Humanizer,llehouerou/Humanizer,kikoanis/Humanizer,jaxx-rep/Humanizer,mexx/Humanizer,micdenny/Humanizer,preetksingh80/Humanizer,henriksen/Humanizer,aloisdg/Humanizer,mrchief/Humanizer,CodeFromJordan/Humanizer,llehouerou/Humanizer,mrchief/Humanizer,gyurisc/Humanizer,Flatlineato/Humanizer,preetksingh80/Humanizer,ErikSchierboom/Humanizer,HalidCisse/Humanizer,gyurisc/Humanizer,mrchief/Humanizer,MehdiK/Humanizer,ErikSchierboom/Humanizer,nigel-sampson/Humanizer,kikoanis/Humanizer,llehouerou/Humanizer,thunsaker/Humanizer,CodeFromJordan/Humanizer,Flatlineato/Humanizer,schalpat/Humanizer,henriksen/Humanizer,preetksingh80/Humanizer,HalidCisse/Humanizer,CodeFromJordan/Humanizer,thunsaker/Humanizer
|
src/Humanizer/ByteSizeExtensions.cs
|
src/Humanizer/ByteSizeExtensions.cs
|
using Humanizer.Bytes;
namespace Humanizer
{
public static class ByteSizeExtensions
{
/// <summary>
/// Use value as a quantity of bits
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static ByteSize Bits(this long val)
{
return ByteSize.FromBits(val);
}
/// <summary>
/// Use value as a quantity of bytes
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static ByteSize Bytes(this double val)
{
return ByteSize.FromBytes(val);
}
/// <summary>
/// Use value as a quantity of kilobytes
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static ByteSize Kilobytes(this double val)
{
return ByteSize.FromKiloBytes(val);
}
/// <summary>
/// Use value as a quantity of megabytes
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static ByteSize Megabytes(this double val)
{
return ByteSize.FromMegaBytes(val);
}
/// <summary>
/// Use value as a quantity of gigabytes
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static ByteSize Gigabytes(this double val)
{
return ByteSize.FromGigaBytes(val);
}
/// <summary>
/// Use value as a quantity of terabytes
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static ByteSize Terabytes(this double val)
{
return ByteSize.FromTeraBytes(val);
}
}
public static class HumanizeExtension
{
/// <summary>
/// Turns a byte quantity into human readable form, eg 2 GB
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static string Humanize(this ByteSize val)
{
return val.ToString();
}
}
}
|
using Humanizer.Bytes;
namespace Humanizer
{
public static class ByteSizeExtensions
{
public static ByteSize Bits(this long val)
{
return ByteSize.FromBits(val);
}
public static ByteSize Bytes(this double val)
{
return ByteSize.FromBytes(val);
}
public static ByteSize Kilobytes(this double val)
{
return ByteSize.FromKiloBytes(val);
}
public static ByteSize Megabytes(this double val)
{
return ByteSize.FromMegaBytes(val);
}
public static ByteSize Gigabytes(this double val)
{
return ByteSize.FromGigaBytes(val);
}
public static ByteSize Terabytes(this double val)
{
return ByteSize.FromTeraBytes(val);
}
}
public static class HumanizeExtension
{
// TODO: Overload this to give access to formatting options in a Humanizey way
public static string Humanize(this ByteSize val)
{
return val.ToString();
}
}
}
|
mit
|
C#
|
b6c4440184e278a7ab71fac43d7bc62eabc01d30
|
Fix missing styles
|
ucdavis/Namster,ucdavis/Namster,ucdavis/Namster
|
src/Namster/Views/Home/Index.cshtml
|
src/Namster/Views/Home/Index.cshtml
|
@{
ViewData["Title"] = "Search";
}
@section styles {
<environment names="Staging,Production">
<link rel="stylesheet" href="~/dist/site.min.css" />
<link rel="stylesheet" href="~/dist/1.site.min.css" />
</environment>
}
<div id="app"></div>
@section scripts{
<script type="text/javascript" src="~/dist/vendor.js"></script>
<script type="text/javascript" src="~/dist/main.js"></script>
}
|
@{
ViewData["Title"] = "Search";
}
@section styles {
@*<link rel="stylesheet" href="~/dist/vendor.css" />
<link rel="stylesheet" href="~/dist/app.css" />*@
}
<div id="app"></div>
@section scripts{
<script type="text/javascript" src="~/dist/vendor.js"></script>
<script type="text/javascript" src="~/dist/main.js"></script>
}
|
mit
|
C#
|
2c19a7be073ef1b8150a4b9cb2d05eedb8b504ed
|
Make CIV.Test.Common private
|
lou1306/CIV,lou1306/CIV
|
CIV.Test/Common.cs
|
CIV.Test/Common.cs
|
using System;
using System.Collections.Generic;
using CIV.Ccs;
using CIV.Common;
using Moq;
namespace CIV.Test
{
static class Common
{
/// <summary>
/// Setup a mock process that can only do the given action.
/// </summary>
/// <returns>The mock process.</returns>
/// <param name="action">Action.</param>
public static CcsProcess SetupMockProcess(String action = "action")
{
return Mock.Of<CcsProcess>(p => p.GetTransitions() == new List<Transition>
{
SetupTransition(action)
}
);
}
static Transition SetupTransition(String label)
{
return new Transition
{
Label = label,
Process = Mock.Of<CcsProcess>()
};
}
}
}
|
using System;
using System.Collections.Generic;
using CIV.Ccs;
using CIV.Common;
using Moq;
namespace CIV.Test
{
public static class Common
{
/// <summary>
/// Setup a mock process that can only do the given action.
/// </summary>
/// <returns>The mock process.</returns>
/// <param name="action">Action.</param>
public static CcsProcess SetupMockProcess(String action = "action")
{
return Mock.Of<CcsProcess>(p => p.GetTransitions() == new List<Transition>
{
SetupTransition(action)
}
);
}
static Transition SetupTransition(String label)
{
return new Transition
{
Label = label,
Process = Mock.Of<CcsProcess>()
};
}
}
}
|
mit
|
C#
|
4a941e6cf0cf5cb3635150192bddab81c606dd4c
|
Increase Asteroid bounding range
|
iridinite/shiftdrive
|
Client/Asteroid.cs
|
Client/Asteroid.cs
|
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System;
using System.IO;
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="GameObject"/> representing a single asteroid.
/// </summary>
internal sealed class Asteroid : GameObject {
private float angularVelocity;
public Asteroid() {
type = ObjectType.Asteroid;
facing = Utils.RNG.Next(0, 360);
spritename = "map/asteroid";
color = Color.White;
bounding = 8f;
}
public override void Update(GameState world, float deltaTime) {
base.Update(world, deltaTime);
facing += angularVelocity * deltaTime;
angularVelocity *= (float)Math.Pow(0.8f, deltaTime);
// re-transmit object if it's moving around
changed = changed || angularVelocity > 0.01f;
}
protected override void OnCollision(GameObject other, Vector2 normal, float penetration) {
// spin around!
angularVelocity += (1f + penetration * 4f) * (float)(Utils.RNG.NextDouble() * 2.0 - 1.0);
// asteroids shouldn't move so much if ships bump into them, because
// they should look heavy and sluggish
this.velocity += normal * penetration;
if (other.type != ObjectType.AIShip && other.type != ObjectType.PlayerShip) {
this.position += normal * penetration;
}
}
public override bool IsTerrain() {
return true;
}
public override void Serialize(BinaryWriter writer) {
base.Serialize(writer);
writer.Write(angularVelocity);
}
public override void Deserialize(BinaryReader reader) {
base.Deserialize(reader);
angularVelocity = reader.ReadSingle();
}
}
}
|
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System;
using System.IO;
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="GameObject"/> representing a single asteroid.
/// </summary>
internal sealed class Asteroid : GameObject {
private float angularVelocity;
public Asteroid() {
type = ObjectType.Asteroid;
facing = Utils.RNG.Next(0, 360);
spritename = "map/asteroid";
color = Color.White;
bounding = 7f;
}
public override void Update(GameState world, float deltaTime) {
base.Update(world, deltaTime);
facing += angularVelocity * deltaTime;
angularVelocity *= (float)Math.Pow(0.8f, deltaTime);
// re-transmit object if it's moving around
changed = changed || angularVelocity > 0.01f;
}
protected override void OnCollision(GameObject other, Vector2 normal, float penetration) {
// spin around!
angularVelocity += (1f + penetration * 4f) * (float)(Utils.RNG.NextDouble() * 2.0 - 1.0);
// asteroids shouldn't move so much if ships bump into them, because
// they should look heavy and sluggish
this.velocity += normal * penetration;
if (other.type != ObjectType.AIShip && other.type != ObjectType.PlayerShip) {
this.position += normal * penetration;
}
}
public override bool IsTerrain() {
return true;
}
public override void Serialize(BinaryWriter writer) {
base.Serialize(writer);
writer.Write(angularVelocity);
}
public override void Deserialize(BinaryReader reader) {
base.Deserialize(reader);
angularVelocity = reader.ReadSingle();
}
}
}
|
bsd-3-clause
|
C#
|
2dc9186c72d3ff61f93f41ecd5fcacf7af85ddac
|
Use MediaManagerImplementation for UWP by default
|
martijn00/XamarinMediaManager,modplug/XamarinMediaManager,bubavanhalen/XamarinMediaManager,mike-rowley/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager
|
MediaManager/Plugin.MediaManager.UWP/MediaManagerImplementation.cs
|
MediaManager/Plugin.MediaManager.UWP/MediaManagerImplementation.cs
|
using Plugin.MediaManager.Abstractions;
using Plugin.MediaManager.Abstractions.Implementations;
namespace Plugin.MediaManager
{
/// <summary>
/// Implementation for Feature
/// </summary>
public class MediaManagerImplementation : MediaManagerBase
{
public override IAudioPlayer AudioPlayer { get; set; } = new AudioPlayerImplementation();
public override IVideoPlayer VideoPlayer { get; set; } = new VideoPlayerImplementation();
public override IMediaNotificationManager MediaNotificationManager { get; set; } = new MediaNotificationManagerImplementation();
public override IMediaExtractor MediaExtractor { get; set; } = new MediaExtractorImplementation();
}
}
|
using Plugin.MediaManager.Abstractions;
using Plugin.MediaManager.Abstractions.Implementations;
namespace Plugin.MediaManager
{
/// <summary>
/// Implementation for Feature
/// </summary>
public class MediaManagerImplementation : MediaManagerBase
{
public override IAudioPlayer AudioPlayer { get; set; } = new AudioPlayerImplementation();
public override IVideoPlayer VideoPlayer { get; set; } = new VideoPlayerImplementation();
public override IMediaNotificationManager MediaNotificationManager { get; set; }
public override IMediaExtractor MediaExtractor { get; set; } = new MediaExtractorImplementation();
}
}
|
mit
|
C#
|
e621f1e0513d8c046c3df96c8d7b49be87744f5f
|
fix unit test
|
thedillonb/octokit.net,gdziadkiewicz/octokit.net,ivandrofly/octokit.net,shiftkey/octokit.net,SamTheDev/octokit.net,SmithAndr/octokit.net,shana/octokit.net,hahmed/octokit.net,octokit/octokit.net,chunkychode/octokit.net,eriawan/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,shana/octokit.net,M-Zuber/octokit.net,gdziadkiewicz/octokit.net,rlugojr/octokit.net,ivandrofly/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,khellang/octokit.net,octokit-net-test-org/octokit.net,devkhan/octokit.net,Sarmad93/octokit.net,shiftkey-tester/octokit.net,octokit-net-test-org/octokit.net,dampir/octokit.net,editor-tools/octokit.net,Sarmad93/octokit.net,shiftkey/octokit.net,devkhan/octokit.net,alfhenrik/octokit.net,shiftkey-tester/octokit.net,eriawan/octokit.net,rlugojr/octokit.net,khellang/octokit.net,TattsGroup/octokit.net,hahmed/octokit.net,alfhenrik/octokit.net,thedillonb/octokit.net,chunkychode/octokit.net,editor-tools/octokit.net,adamralph/octokit.net,M-Zuber/octokit.net,SamTheDev/octokit.net,dampir/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,octokit/octokit.net
|
Octokit.Tests/Clients/Enterprise/EnterpriseAdminStatsClientTest.cs
|
Octokit.Tests/Clients/Enterprise/EnterpriseAdminStatsClientTest.cs
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Internal;
using Octokit.Tests.Helpers;
using Xunit;
namespace Octokit.Tests.Clients
{
public class EnterpriseAdminStatsClientTest
{
public class TheGetStatisticsMethod
{
[Fact]
public void RequestsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new EnterpriseAdminStatsClient(connection);
foreach (AdminStatsType adminType in Enum.GetValues(typeof(AdminStatsType)))
{
client.GetStatistics(adminType);
connection.Received().Get<AdminStats>(Arg.Is<Uri>(u => u.ToString() == String.Concat("enterprise/stats/", adminType.ToString().ToLowerInvariant())), null);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Internal;
using Octokit.Tests.Helpers;
using Xunit;
namespace Octokit.Tests.Clients
{
public class EnterpriseAdminStatsClientTest
{
public class TheGetStatisticsMethod
{
[Fact]
public void RequestsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new EnterpriseAdminStatsClient(connection);
foreach (AdminStatsType adminType in Enum.GetValues(typeof(AdminStatsType)))
{
client.GetStatistics(adminType);
connection.Received().Get<AdminStats>(Arg.Is<Uri>(u => u.ToString() == String.Concat("enterprise/stats/", adminType.ToString().ToLowerInvariant())));
}
}
}
}
}
|
mit
|
C#
|
509da85f7fc6bb6323898fd946d7f15b30ed2112
|
Simplify getting frame bones
|
SteamDatabase/ValveResourceFormat
|
ValveResourceFormat/Resource/ResourceTypes/ModelAnimation/Frame.cs
|
ValveResourceFormat/Resource/ResourceTypes/ModelAnimation/Frame.cs
|
using System;
using System.Collections.Generic;
using System.Numerics;
namespace ValveResourceFormat.ResourceTypes.ModelAnimation
{
public class Frame
{
public Dictionary<string, FrameBone> Bones { get; }
public Frame()
{
Bones = new Dictionary<string, FrameBone>();
}
public void SetAttribute(string bone, string attribute, object data)
{
switch (attribute)
{
case "Position":
GetBone(bone).Position = (Vector3)data;
break;
case "Angle":
GetBone(bone).Angle = (Quaternion)data;
break;
case "data":
//ignore
break;
#if DEBUG
default:
Console.WriteLine($"Unknown frame attribute '{attribute}' encountered");
break;
#endif
}
}
private FrameBone GetBone(string name)
{
if (!Bones.TryGetValue(name, out var bone))
{
bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1));
Bones[name] = bone;
}
return bone;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Numerics;
namespace ValveResourceFormat.ResourceTypes.ModelAnimation
{
public class Frame
{
public Dictionary<string, FrameBone> Bones { get; }
public Frame()
{
Bones = new Dictionary<string, FrameBone>();
}
public void SetAttribute(string bone, string attribute, object data)
{
switch (attribute)
{
case "Position":
InsertIfUnknown(bone);
Bones[bone].Position = (Vector3)data;
break;
case "Angle":
InsertIfUnknown(bone);
Bones[bone].Angle = (Quaternion)data;
break;
case "data":
//ignore
break;
#if DEBUG
default:
Console.WriteLine($"Unknown frame attribute '{attribute}' encountered");
break;
#endif
}
}
private void InsertIfUnknown(string name)
{
if (!Bones.ContainsKey(name))
{
Bones[name] = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1));
}
}
}
}
|
mit
|
C#
|
7ba533b7a4a47cf7b2d61b4453b1cd329e7fef51
|
Expand mania to fit vertical screen bounds
|
ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,ppy/osu,EVAST9919/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu
|
osu.Game.Rulesets.Mania/UI/ManiaPlayfieldAdjustmentContainer.cs
|
osu.Game.Rulesets.Mania/UI/ManiaPlayfieldAdjustmentContainer.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Mania.UI
{
public class ManiaPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{
public ManiaPlayfieldAdjustmentContainer()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Mania.UI
{
public class ManiaPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
{
public ManiaPlayfieldAdjustmentContainer()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Size = new Vector2(1, 0.8f);
}
}
}
|
mit
|
C#
|
a4417e62406a07a8842f435aae2ac84cc383f60b
|
Add missing using statement to Blazor hosted template. (#9000)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Components/Blazor/Templates/src/content/BlazorHosted-CSharp/BlazorHosted-CSharp.Server/Startup.cs
|
src/Components/Blazor/Templates/src/content/BlazorHosted-CSharp/BlazorHosted-CSharp.Server/Startup.cs
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using System.Linq;
namespace BlazorHosted_CSharp.Server
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBlazorDebugging();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
app.UseBlazor<Client.Startup>();
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using System.Linq;
namespace BlazorHosted_CSharp.Server
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBlazorDebugging();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
app.UseBlazor<Client.Startup>();
}
}
}
|
apache-2.0
|
C#
|
86ce0b551937f65f5b687430bf792d872a644ba1
|
Make DrawableDate adjustable
|
peppy/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,naoey/osu,naoey/osu,NeoAdonis/osu,smoogipooo/osu,DrabWeb/osu,smoogipoo/osu,ZLima12/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,naoey/osu,peppy/osu,2yangk23/osu,johnneijzen/osu,peppy/osu
|
osu.Game/Graphics/DrawableDate.cs
|
osu.Game/Graphics/DrawableDate.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class DrawableDate : OsuSpriteText, IHasTooltip
{
private DateTimeOffset date;
public DateTimeOffset Date
{
get => date;
set
{
if (date == value)
return;
date = value.ToLocalTime();
if (LoadState >= LoadState.Ready)
updateTime();
}
}
public DrawableDate(DateTimeOffset date)
{
Font = "Exo2.0-RegularItalic";
Date = date;
}
[BackgroundDependencyLoader]
private void load()
{
updateTime();
}
protected override void LoadComplete()
{
base.LoadComplete();
Scheduler.Add(updateTimeWithReschedule);
}
private void updateTimeWithReschedule()
{
updateTime();
var diffToNow = DateTimeOffset.Now.Subtract(Date);
double timeUntilNextUpdate = 1000;
if (diffToNow.TotalSeconds > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalMinutes > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalHours > 24)
timeUntilNextUpdate *= 24;
}
}
Scheduler.AddDelayed(updateTimeWithReschedule, timeUntilNextUpdate);
}
protected virtual string Format() => Date.Humanize();
private void updateTime() => Text = Format();
public virtual string TooltipText => string.Format($"{Date:MMMM d, yyyy h:mm tt \"UTC\"z}");
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Cursor;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Graphics
{
public class DrawableDate : OsuSpriteText, IHasTooltip
{
protected readonly DateTimeOffset Date;
public DrawableDate(DateTimeOffset date)
{
Font = "Exo2.0-RegularItalic";
Date = date.ToLocalTime();
}
[BackgroundDependencyLoader]
private void load()
{
updateTime();
}
protected override void LoadComplete()
{
base.LoadComplete();
Scheduler.Add(updateTimeWithReschedule);
}
private void updateTimeWithReschedule()
{
updateTime();
var diffToNow = DateTimeOffset.Now.Subtract(Date);
double timeUntilNextUpdate = 1000;
if (diffToNow.TotalSeconds > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalMinutes > 60)
{
timeUntilNextUpdate *= 60;
if (diffToNow.TotalHours > 24)
timeUntilNextUpdate *= 24;
}
}
Scheduler.AddDelayed(updateTimeWithReschedule, timeUntilNextUpdate);
}
protected virtual string Format() => Date.Humanize();
private void updateTime() => Text = Format();
public virtual string TooltipText => string.Format($"{Date:MMMM d, yyyy h:mm tt \"UTC\"z}");
}
}
|
mit
|
C#
|
30111d07946f7e41e465eca267beb82d3765531c
|
Read data from underlying stream in chunks if it does not return everything to us in one go.
|
NVentimiglia/WebSocket.Portable
|
WebSocket.Portable/WebSocket.Portable/Internal/DataLayerExtensions.cs
|
WebSocket.Portable/WebSocket.Portable/Internal/DataLayerExtensions.cs
|
using System.Threading;
using System.Threading.Tasks;
using WebSocket.Portable.Interfaces;
namespace WebSocket.Portable.Internal
{
internal static class DataLayerExtensions
{
public static Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken)
{
return layer.ReadAsync(length, cancellationToken, WebSocketErrorCode.CloseInvalidData);
}
public static async Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken, WebSocketErrorCode errorCode)
{
var buffer = new byte[length];
var read = 0;
while (read < length && !cancellationToken.IsCancellationRequested)
{
var chunkOffset = read;
var chunkLength = length - chunkOffset;
var chunkSize = await layer.ReadAsync(buffer, chunkOffset, chunkLength, cancellationToken);
if (chunkSize == 0)
{
break;
}
read += chunkSize;
}
if (read != buffer.Length)
throw new WebSocketException(errorCode);
return buffer;
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WebSocket.Portable.Interfaces;
namespace WebSocket.Portable.Internal
{
internal static class DataLayerExtensions
{
public static Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken)
{
return layer.ReadAsync(length, cancellationToken, WebSocketErrorCode.CloseInvalidData);
}
public static async Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken, WebSocketErrorCode errorCode)
{
var buffer = new byte[length];
var read = await layer.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
if (read != buffer.Length)
throw new WebSocketException(errorCode);
return buffer;
}
}
}
|
apache-2.0
|
C#
|
079f842063808e668fbeac72c53bd5552a389efc
|
Optimize AliasUpdater code path
|
Ermesx/Orchard,NIKASoftwareDevs/Orchard,omidnasri/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,jchenga/Orchard,qt1/orchard4ibn,dcinzona/Orchard,AndreVolksdorf/Orchard,jtkech/Orchard,harmony7/Orchard,KeithRaven/Orchard,hannan-azam/Orchard,bedegaming-aleksej/Orchard,neTp9c/Orchard,SzymonSel/Orchard,OrchardCMS/Orchard-Harvest-Website,li0803/Orchard,phillipsj/Orchard,escofieldnaxos/Orchard,Anton-Am/Orchard,smartnet-developers/Orchard,kouweizhong/Orchard,yonglehou/Orchard,Dolphinsimon/Orchard,DonnotRain/Orchard,TaiAivaras/Orchard,armanforghani/Orchard,jchenga/Orchard,sfmskywalker/Orchard,cooclsee/Orchard,johnnyqian/Orchard,RoyalVeterinaryCollege/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,DonnotRain/Orchard,OrchardCMS/Orchard-Harvest-Website,emretiryaki/Orchard,andyshao/Orchard,salarvand/orchard,xkproject/Orchard,KeithRaven/Orchard,bedegaming-aleksej/Orchard,MpDzik/Orchard,dozoft/Orchard,salarvand/orchard,hhland/Orchard,Ermesx/Orchard,Sylapse/Orchard.HttpAuthSample,jersiovic/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,m2cms/Orchard,alejandroaldana/Orchard,fassetar/Orchard,angelapper/Orchard,planetClaire/Orchard-LETS,fassetar/Orchard,Dolphinsimon/Orchard,harmony7/Orchard,dcinzona/Orchard-Harvest-Website,huoxudong125/Orchard,SeyDutch/Airbrush,SouleDesigns/SouleDesigns.Orchard,xiaobudian/Orchard,mgrowan/Orchard,harmony7/Orchard,cooclsee/Orchard,jagraz/Orchard,luchaoshuai/Orchard,tobydodds/folklife,vairam-svs/Orchard,brownjordaninternational/OrchardCMS,enspiral-dev-academy/Orchard,yersans/Orchard,aaronamm/Orchard,mvarblow/Orchard,dcinzona/Orchard,kouweizhong/Orchard,qt1/Orchard,OrchardCMS/Orchard-Harvest-Website,dburriss/Orchard,TaiAivaras/Orchard,marcoaoteixeira/Orchard,oxwanawxo/Orchard,Morgma/valleyviewknolls,dburriss/Orchard,sebastienros/msc,hannan-azam/Orchard,jimasp/Orchard,luchaoshuai/Orchard,vairam-svs/Orchard,huoxudong125/Orchard,geertdoornbos/Orchard,AndreVolksdorf/Orchard,arminkarimi/Orchard,li0803/Orchard,rtpHarry/Orchard,neTp9c/Orchard,jersiovic/Orchard,ehe888/Orchard,spraiin/Orchard,mvarblow/Orchard,AndreVolksdorf/Orchard,smartnet-developers/Orchard,austinsc/Orchard,salarvand/orchard,planetClaire/Orchard-LETS,kgacova/Orchard,dcinzona/Orchard,Morgma/valleyviewknolls,omidnasri/Orchard,arminkarimi/Orchard,OrchardCMS/Orchard,MetSystem/Orchard,IDeliverable/Orchard,Fogolan/OrchardForWork,emretiryaki/Orchard,Serlead/Orchard,AdvantageCS/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,omidnasri/Orchard,Ermesx/Orchard,jchenga/Orchard,dcinzona/Orchard-Harvest-Website,Cphusion/Orchard,marcoaoteixeira/Orchard,emretiryaki/Orchard,marcoaoteixeira/Orchard,Fogolan/OrchardForWork,vard0/orchard.tan,LaserSrl/Orchard,patricmutwiri/Orchard,salarvand/Portal,IDeliverable/Orchard,salarvand/Portal,SouleDesigns/SouleDesigns.Orchard,Inner89/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,omidnasri/Orchard,Ermesx/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,qt1/orchard4ibn,TaiAivaras/Orchard,Cphusion/Orchard,Sylapse/Orchard.HttpAuthSample,aaronamm/Orchard,armanforghani/Orchard,fassetar/Orchard,yersans/Orchard,omidnasri/Orchard,dcinzona/Orchard-Harvest-Website,jimasp/Orchard,phillipsj/Orchard,Inner89/Orchard,LaserSrl/Orchard,bigfont/orchard-cms-modules-and-themes,OrchardCMS/Orchard-Harvest-Website,hbulzy/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Cphusion/Orchard,RoyalVeterinaryCollege/Orchard,omidnasri/Orchard,Anton-Am/Orchard,mvarblow/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,mgrowan/Orchard,xkproject/Orchard,brownjordaninternational/OrchardCMS,SzymonSel/Orchard,SeyDutch/Airbrush,tobydodds/folklife,oxwanawxo/Orchard,geertdoornbos/Orchard,mvarblow/Orchard,xiaobudian/Orchard,emretiryaki/Orchard,jerryshi2007/Orchard,dcinzona/Orchard-Harvest-Website,SeyDutch/Airbrush,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,JRKelso/Orchard,oxwanawxo/Orchard,phillipsj/Orchard,gcsuk/Orchard,jersiovic/Orchard,Cphusion/Orchard,openbizgit/Orchard,yersans/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard,sebastienros/msc,sfmskywalker/Orchard,openbizgit/Orchard,johnnyqian/Orchard,NIKASoftwareDevs/Orchard,SeyDutch/Airbrush,neTp9c/Orchard,mgrowan/Orchard,TalaveraTechnologySolutions/Orchard,salarvand/orchard,xiaobudian/Orchard,m2cms/Orchard,vairam-svs/Orchard,dburriss/Orchard,MetSystem/Orchard,fortunearterial/Orchard,TalaveraTechnologySolutions/Orchard,xkproject/Orchard,vairam-svs/Orchard,fortunearterial/Orchard,escofieldnaxos/Orchard,openbizgit/Orchard,austinsc/Orchard,hbulzy/Orchard,alejandroaldana/Orchard,jerryshi2007/Orchard,neTp9c/Orchard,tobydodds/folklife,stormleoxia/Orchard,marcoaoteixeira/Orchard,Serlead/Orchard,abhishekluv/Orchard,qt1/Orchard,smartnet-developers/Orchard,patricmutwiri/Orchard,fortunearterial/Orchard,Praggie/Orchard,angelapper/Orchard,NIKASoftwareDevs/Orchard,OrchardCMS/Orchard,TalaveraTechnologySolutions/Orchard,RoyalVeterinaryCollege/Orchard,jtkech/Orchard,infofromca/Orchard,kgacova/Orchard,xiaobudian/Orchard,MpDzik/Orchard,jagraz/Orchard,alejandroaldana/Orchard,Inner89/Orchard,OrchardCMS/Orchard-Harvest-Website,jersiovic/Orchard,xiaobudian/Orchard,harmony7/Orchard,vairam-svs/Orchard,andyshao/Orchard,Lombiq/Orchard,kouweizhong/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,geertdoornbos/Orchard,jchenga/Orchard,Lombiq/Orchard,fortunearterial/Orchard,hannan-azam/Orchard,MetSystem/Orchard,Praggie/Orchard,DonnotRain/Orchard,bigfont/orchard-continuous-integration-demo,NIKASoftwareDevs/Orchard,Codinlab/Orchard,dcinzona/Orchard,bigfont/orchard-continuous-integration-demo,MetSystem/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard,TalaveraTechnologySolutions/Orchard,infofromca/Orchard,RoyalVeterinaryCollege/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,vard0/orchard.tan,Fogolan/OrchardForWork,vard0/orchard.tan,SzymonSel/Orchard,spraiin/Orchard,m2cms/Orchard,li0803/Orchard,alejandroaldana/Orchard,stormleoxia/Orchard,AdvantageCS/Orchard,yonglehou/Orchard,rtpHarry/Orchard,smartnet-developers/Orchard,planetClaire/Orchard-LETS,rtpHarry/Orchard,planetClaire/Orchard-LETS,abhishekluv/Orchard,patricmutwiri/Orchard,dozoft/Orchard,bedegaming-aleksej/Orchard,dburriss/Orchard,mvarblow/Orchard,AdvantageCS/Orchard,abhishekluv/Orchard,li0803/Orchard,austinsc/Orchard,brownjordaninternational/OrchardCMS,yersans/Orchard,cooclsee/Orchard,tobydodds/folklife,Ermesx/Orchard,grapto/Orchard.CloudBust,Serlead/Orchard,sebastienros/msc,spraiin/Orchard,enspiral-dev-academy/Orchard,jimasp/Orchard,DonnotRain/Orchard,infofromca/Orchard,andyshao/Orchard,stormleoxia/Orchard,IDeliverable/Orchard,sfmskywalker/Orchard,arminkarimi/Orchard,cooclsee/Orchard,escofieldnaxos/Orchard,sfmskywalker/Orchard,LaserSrl/Orchard,vard0/orchard.tan,Lombiq/Orchard,phillipsj/Orchard,tobydodds/folklife,dozoft/Orchard,Codinlab/Orchard,rtpHarry/Orchard,SeyDutch/Airbrush,ehe888/Orchard,abhishekluv/Orchard,jerryshi2007/Orchard,enspiral-dev-academy/Orchard,Serlead/Orchard,JRKelso/Orchard,TalaveraTechnologySolutions/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,stormleoxia/Orchard,johnnyqian/Orchard,infofromca/Orchard,jersiovic/Orchard,andyshao/Orchard,yonglehou/Orchard,geertdoornbos/Orchard,TalaveraTechnologySolutions/Orchard,dcinzona/Orchard-Harvest-Website,NIKASoftwareDevs/Orchard,Sylapse/Orchard.HttpAuthSample,MetSystem/Orchard,aaronamm/Orchard,geertdoornbos/Orchard,ehe888/Orchard,Praggie/Orchard,angelapper/Orchard,RoyalVeterinaryCollege/Orchard,Cphusion/Orchard,grapto/Orchard.CloudBust,salarvand/Portal,vard0/orchard.tan,enspiral-dev-academy/Orchard,Serlead/Orchard,bigfont/orchard-cms-modules-and-themes,marcoaoteixeira/Orchard,hbulzy/Orchard,AndreVolksdorf/Orchard,arminkarimi/Orchard,hhland/Orchard,qt1/orchard4ibn,ehe888/Orchard,infofromca/Orchard,Dolphinsimon/Orchard,bigfont/orchard-cms-modules-and-themes,salarvand/orchard,smartnet-developers/Orchard,JRKelso/Orchard,Anton-Am/Orchard,Anton-Am/Orchard,Inner89/Orchard,kgacova/Orchard,omidnasri/Orchard,oxwanawxo/Orchard,Fogolan/OrchardForWork,OrchardCMS/Orchard,escofieldnaxos/Orchard,omidnasri/Orchard,Codinlab/Orchard,enspiral-dev-academy/Orchard,sfmskywalker/Orchard,jtkech/Orchard,SouleDesigns/SouleDesigns.Orchard,SouleDesigns/SouleDesigns.Orchard,LaserSrl/Orchard,gcsuk/Orchard,huoxudong125/Orchard,sebastienros/msc,yonglehou/Orchard,hannan-azam/Orchard,harmony7/Orchard,LaserSrl/Orchard,Anton-Am/Orchard,Dolphinsimon/Orchard,jchenga/Orchard,MpDzik/Orchard,sfmskywalker/Orchard,Praggie/Orchard,yonglehou/Orchard,MpDzik/Orchard,IDeliverable/Orchard,huoxudong125/Orchard,Sylapse/Orchard.HttpAuthSample,salarvand/Portal,jagraz/Orchard,mgrowan/Orchard,qt1/Orchard,patricmutwiri/Orchard,neTp9c/Orchard,hhland/Orchard,bigfont/orchard-cms-modules-and-themes,stormleoxia/Orchard,SouleDesigns/SouleDesigns.Orchard,jtkech/Orchard,kgacova/Orchard,m2cms/Orchard,dcinzona/Orchard,Morgma/valleyviewknolls,jimasp/Orchard,kouweizhong/Orchard,jimasp/Orchard,oxwanawxo/Orchard,DonnotRain/Orchard,TalaveraTechnologySolutions/Orchard,Sylapse/Orchard.HttpAuthSample,jerryshi2007/Orchard,bedegaming-aleksej/Orchard,ehe888/Orchard,IDeliverable/Orchard,qt1/Orchard,spraiin/Orchard,m2cms/Orchard,johnnyqian/Orchard,Fogolan/OrchardForWork,tobydodds/folklife,JRKelso/Orchard,jerryshi2007/Orchard,austinsc/Orchard,alejandroaldana/Orchard,aaronamm/Orchard,cooclsee/Orchard,huoxudong125/Orchard,hhland/Orchard,Morgma/valleyviewknolls,brownjordaninternational/OrchardCMS,vard0/orchard.tan,angelapper/Orchard,Morgma/valleyviewknolls,sfmskywalker/Orchard,abhishekluv/Orchard,luchaoshuai/Orchard,rtpHarry/Orchard,andyshao/Orchard,dcinzona/Orchard-Harvest-Website,qt1/orchard4ibn,OrchardCMS/Orchard-Harvest-Website,openbizgit/Orchard,li0803/Orchard,angelapper/Orchard,qt1/orchard4ibn,mgrowan/Orchard,jtkech/Orchard,gcsuk/Orchard,gcsuk/Orchard,grapto/Orchard.CloudBust,armanforghani/Orchard,fassetar/Orchard,abhishekluv/Orchard,hbulzy/Orchard,planetClaire/Orchard-LETS,openbizgit/Orchard,dburriss/Orchard,kouweizhong/Orchard,grapto/Orchard.CloudBust,jagraz/Orchard,austinsc/Orchard,Lombiq/Orchard,fortunearterial/Orchard,kgacova/Orchard,grapto/Orchard.CloudBust,luchaoshuai/Orchard,hbulzy/Orchard,sebastienros/msc,emretiryaki/Orchard,aaronamm/Orchard,AndreVolksdorf/Orchard,KeithRaven/Orchard,SzymonSel/Orchard,qt1/orchard4ibn,phillipsj/Orchard,arminkarimi/Orchard,grapto/Orchard.CloudBust,Codinlab/Orchard,Dolphinsimon/Orchard,jagraz/Orchard,fassetar/Orchard,JRKelso/Orchard,luchaoshuai/Orchard,dozoft/Orchard,OrchardCMS/Orchard,AdvantageCS/Orchard,xkproject/Orchard,yersans/Orchard,hhland/Orchard,Praggie/Orchard,TaiAivaras/Orchard,Inner89/Orchard,johnnyqian/Orchard,armanforghani/Orchard,gcsuk/Orchard,bigfont/orchard-continuous-integration-demo,Lombiq/Orchard,dozoft/Orchard,hannan-azam/Orchard,MpDzik/Orchard,escofieldnaxos/Orchard,Codinlab/Orchard,brownjordaninternational/OrchardCMS,KeithRaven/Orchard,bedegaming-aleksej/Orchard,bigfont/orchard-cms-modules-and-themes,salarvand/Portal,SzymonSel/Orchard,bigfont/orchard-continuous-integration-demo,spraiin/Orchard,xkproject/Orchard,TalaveraTechnologySolutions/Orchard,KeithRaven/Orchard,TaiAivaras/Orchard,armanforghani/Orchard,MpDzik/Orchard,omidnasri/Orchard,patricmutwiri/Orchard,qt1/Orchard,dmitry-urenev/extended-orchard-cms-v10.1
|
src/Orchard.Web/Modules/Orchard.Alias/Implementation/Updater/AliasUpdater.cs
|
src/Orchard.Web/Modules/Orchard.Alias/Implementation/Updater/AliasUpdater.cs
|
using System;
using System.Linq;
using Orchard.Alias.Implementation.Holder;
using Orchard.Alias.Implementation.Storage;
using Orchard.Environment;
using Orchard.Tasks;
using Orchard.Logging;
namespace Orchard.Alias.Implementation.Updater {
public class AliasHolderUpdater : IOrchardShellEvents, IBackgroundTask {
private readonly IAliasHolder _aliasHolder;
private readonly IAliasStorage _storage;
private readonly IAliasUpdateCursor _cursor;
public ILogger Logger { get; set; }
public AliasHolderUpdater(IAliasHolder aliasHolder, IAliasStorage storage, IAliasUpdateCursor cursor) {
_aliasHolder = aliasHolder;
_storage = storage;
_cursor = cursor;
Logger = NullLogger.Instance;
}
void IOrchardShellEvents.Activated() {
Refresh();
}
void IOrchardShellEvents.Terminating() {
}
private void Refresh() {
try {
// only retreive aliases which have not been processed yet
var aliases = _storage.List(x => x.Id > _cursor.Cursor).ToArray();
// update the last processed id
if (aliases.Any()) {
_cursor.Cursor = aliases.Last().Item5;
_aliasHolder.SetAliases(aliases.Select(alias => new AliasInfo { Path = alias.Item1, Area = alias.Item2, RouteValues = alias.Item3 }));
}
}
catch (Exception ex) {
Logger.Error(ex, "Exception during Alias refresh");
}
}
public void Sweep() {
Refresh();
}
}
}
|
using System;
using System.Linq;
using Orchard.Alias.Implementation.Holder;
using Orchard.Alias.Implementation.Storage;
using Orchard.Environment;
using Orchard.Tasks;
using Orchard.Logging;
namespace Orchard.Alias.Implementation.Updater {
public class AliasHolderUpdater : IOrchardShellEvents, IBackgroundTask {
private readonly IAliasHolder _aliasHolder;
private readonly IAliasStorage _storage;
private readonly IAliasUpdateCursor _cursor;
public ILogger Logger { get; set; }
public AliasHolderUpdater(IAliasHolder aliasHolder, IAliasStorage storage, IAliasUpdateCursor cursor) {
_aliasHolder = aliasHolder;
_storage = storage;
_cursor = cursor;
Logger = NullLogger.Instance;
}
void IOrchardShellEvents.Activated() {
Refresh();
}
void IOrchardShellEvents.Terminating() {
}
private void Refresh() {
try {
// only retreive aliases which have not been processed yet
var aliases = _storage.List(x => x.Id > _cursor.Cursor).ToArray();
// update the last processed id
if (aliases.Any()) {
_cursor.Cursor = aliases.Last().Item5;
}
_aliasHolder.SetAliases(aliases.Select(alias => new AliasInfo { Path = alias.Item1, Area = alias.Item2, RouteValues = alias.Item3 }));
}
catch (Exception ex) {
Logger.Error(ex, "Exception during Alias refresh");
}
}
public void Sweep() {
Refresh();
}
}
}
|
bsd-3-clause
|
C#
|
22de9e4b25eb43e0dcea362ca76994c3d9cb4472
|
add min/max unit tests for range tree
|
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
|
unity/library/UtyMap.Unity.Tests/Infrastructure/Primitives/RangeTreeTests.cs
|
unity/library/UtyMap.Unity.Tests/Infrastructure/Primitives/RangeTreeTests.cs
|
using System.Linq;
using NUnit.Framework;
using UtyMap.Unity.Infrastructure.Primitives;
namespace UtyMap.Unity.Tests.Infrastructure.Primitives
{
[TestFixture]
class RangeTreeTests
{
[Test]
public void CanHandleOneElement()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(0, 10, "1"));
Assert.AreEqual("1", tree[9].First().Value);
}
[Test]
public void CanHandleNoElements()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(0, 10, "1"));
Assert.IsFalse(tree[11].Any());
}
[Test]
public void CanHandleMoreThanOne()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(0, 10, "1"));
tree.Add(new RangeValuePair<float, string>(10, 20, "2"));
Assert.AreEqual("1", tree[5].First().Value);
Assert.AreEqual("2", tree[11].First().Value);
}
[Test]
public void CanGetMinValue()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(100, 200, "1"));
tree.Add(new RangeValuePair<float, string>(300, 400, "2"));
tree.Rebuild();
var value = tree.Min;
Assert.AreEqual(100, value);
}
[Test]
public void CanGetMaxValue()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(100, 200, "1"));
tree.Add(new RangeValuePair<float, string>(300, 400, "2"));
tree.Rebuild();
var value = tree.Max;
Assert.AreEqual(400, value);
}
}
}
|
using System.Linq;
using NUnit.Framework;
using UtyMap.Unity.Infrastructure.Primitives;
namespace UtyMap.Unity.Tests.Infrastructure.Primitives
{
[TestFixture]
class RangeTreeTests
{
[Test]
public void CanHandleOneElement()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(0, 10, "1"));
Assert.AreEqual("1", tree[9].First().Value);
}
[Test]
public void CanHandleNoElements()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(0, 10, "1"));
Assert.IsFalse(tree[11].Any());
}
[Test]
public void CanHandleMoreThanOne()
{
var tree = new RangeTree<float, string>();
tree.Add(new RangeValuePair<float, string>(0, 10, "1"));
tree.Add(new RangeValuePair<float, string>(10, 20, "2"));
Assert.AreEqual("1", tree[5].First().Value);
Assert.AreEqual("2", tree[11].First().Value);
}
}
}
|
apache-2.0
|
C#
|
6f268a98d5adcb672e50d9d0d7e318520ad03edb
|
Add check if dialog is already closing
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/Dialogs/DialogScreenViewModel.cs
|
WalletWasabi.Fluent/ViewModels/Dialogs/DialogScreenViewModel.cs
|
using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class DialogScreenViewModel : ViewModelBase, IScreen
{
private bool _isClosing;
private bool _isDialogOpen;
public DialogScreenViewModel()
{
Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
.Subscribe(_ =>
{
if (!_isClosing)
{
IsDialogOpen = Router.NavigationStack.Count >= 1;
}
});
this.WhenAnyValue(x => x.IsDialogOpen).Subscribe(x =>
{
if (!x)
{
if (!_isClosing)
{
// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
Close();
}
}
});
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public bool IsDialogOpen
{
get => _isDialogOpen;
set => this.RaiseAndSetIfChanged(ref _isDialogOpen, value);
}
public void Close()
{
if (!_isClosing)
{
_isClosing = true;
if (Router.NavigationStack.Count >= 1)
{
foreach (var routable in Router.NavigationStack)
{
// Close all dialogs so the awaited tasks can complete.
// - DialogViewModelBase.ShowDialogAsync()
// - DialogViewModelBase.GetDialogResultAsync()
if (routable is DialogViewModelBase dialog)
{
dialog.IsDialogOpen = false;
}
}
Router.NavigationStack.Clear();
IsDialogOpen = false;
}
_isClosing = false;
}
}
}
}
|
using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class DialogScreenViewModel : ViewModelBase, IScreen
{
private bool _isClosing;
private bool _isDialogOpen;
public DialogScreenViewModel()
{
Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
.Subscribe(_ =>
{
if (!_isClosing)
{
IsDialogOpen = Router.NavigationStack.Count >= 1;
}
});
this.WhenAnyValue(x => x.IsDialogOpen).Subscribe(x =>
{
if (!x)
{
// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
Close();
}
});
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public bool IsDialogOpen
{
get => _isDialogOpen;
set => this.RaiseAndSetIfChanged(ref _isDialogOpen, value);
}
public void Close()
{
if (!_isClosing)
{
_isClosing = true;
if (Router.NavigationStack.Count >= 1)
{
foreach (var routable in Router.NavigationStack)
{
// Close all dialogs so the awaited tasks can complete.
// - DialogViewModelBase.ShowDialogAsync()
// - DialogViewModelBase.GetDialogResultAsync()
if (routable is DialogViewModelBase dialog)
{
dialog.IsDialogOpen = false;
}
}
Router.NavigationStack.Clear();
IsDialogOpen = false;
}
_isClosing = false;
}
}
}
}
|
mit
|
C#
|
904a7e7a12cd7e703b5d128ec738ac216597a04f
|
Add exec method to js regexp
|
kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs,x335/WootzJs
|
WootzJs.Runtime/Runtime/WootzJs/JsRegExp.cs
|
WootzJs.Runtime/Runtime/WootzJs/JsRegExp.cs
|
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
namespace System.Runtime.WootzJs
{
[Js(Export = false, Name = "RegExp")]
public class JsRegExp
{
public JsRegExp(string s)
{
}
public extern bool test(JsString value);
public extern string[] exec(JsString value);
}
}
|
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
namespace System.Runtime.WootzJs
{
[Js(Export = false, Name = "RegExp")]
public class JsRegExp
{
public JsRegExp(string s)
{
}
public extern bool test(JsString value);
public extern string[] match(JsString value);
}
}
|
mit
|
C#
|
5d73a3c324c10c801f7e4333a1828098d3aad9b0
|
Add helper to create a MockAppHost from a MockRequestContext (useful in testing)
|
timba/NServiceKit,timba/NServiceKit,nataren/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,MindTouch/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,meebey/ServiceStack,NServiceKit/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,meebey/ServiceStack
|
src/ServiceStack.ServiceInterface/Testing/MockRequestContext.cs
|
src/ServiceStack.ServiceInterface/Testing/MockRequestContext.cs
|
using System;
using System.Collections.Generic;
using System.Net;
using Funq;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.WebHost.Endpoints;
namespace ServiceStack.ServiceInterface.Testing
{
public class MockRequestContext : IRequestContext
{
public MockRequestContext()
{
this.Cookies = new Dictionary<string, Cookie>();
this.Files = new IFile[0];
this.Container = new Container();
var httpReq = new MockHttpRequest { Container = this.Container };
httpReq.AddSessionCookies();
this.Container.Register<IHttpRequest>(httpReq);
var httpRes = new MockHttpResponse();
this.Container.Register<IHttpResponse>(httpRes);
httpReq.Container = this.Container;
}
public T Get<T>() where T : class
{
return Container.TryResolve<T>();
}
public string IpAddress { get; private set; }
public string GetHeader(string headerName)
{
return Get<IHttpRequest>().Headers[headerName];
}
public Container Container { get; private set; }
public IDictionary<string, Cookie> Cookies { get; private set; }
public EndpointAttributes EndpointAttributes { get; private set; }
public IRequestAttributes RequestAttributes { get; private set; }
public string ContentType { get; private set; }
public string ResponseContentType { get; private set; }
public string CompressionType { get; private set; }
public string AbsoluteUri { get; private set; }
public string PathInfo { get; private set; }
public IFile[] Files { get; private set; }
public AuthUserSession RemoveSession()
{
var httpReq = this.Get<IHttpRequest>();
httpReq.RemoveSession();
return httpReq.GetSession() as AuthUserSession;
}
public AuthUserSession ReloadSession()
{
var httpReq = this.Get<IHttpRequest>();
return httpReq.GetSession() as AuthUserSession;
}
public void Dispose()
{
}
public IAppHost CreateAppHost()
{
return new TestAppHost(this.Container);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using Funq;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
namespace ServiceStack.ServiceInterface.Testing
{
public class MockRequestContext : IRequestContext
{
public MockRequestContext()
{
this.Cookies = new Dictionary<string, Cookie>();
this.Files = new IFile[0];
this.Container = new Container();
var httpReq = new MockHttpRequest { Container = this.Container };
httpReq.AddSessionCookies();
this.Container.Register<IHttpRequest>(httpReq);
var httpRes = new MockHttpResponse();
this.Container.Register<IHttpResponse>(httpRes);
httpReq.Container = this.Container;
}
public T Get<T>() where T : class
{
return Container.TryResolve<T>();
}
public string IpAddress { get; private set; }
public string GetHeader(string headerName)
{
return Get<IHttpRequest>().Headers[headerName];
}
public Container Container { get; private set; }
public IDictionary<string, Cookie> Cookies { get; private set; }
public EndpointAttributes EndpointAttributes { get; private set; }
public IRequestAttributes RequestAttributes { get; private set; }
public string ContentType { get; private set; }
public string ResponseContentType { get; private set; }
public string CompressionType { get; private set; }
public string AbsoluteUri { get; private set; }
public string PathInfo { get; private set; }
public IFile[] Files { get; private set; }
public AuthUserSession RemoveSession()
{
var httpReq = this.Get<IHttpRequest>();
httpReq.RemoveSession();
return httpReq.GetSession() as AuthUserSession;
}
public AuthUserSession ReloadSession()
{
var httpReq = this.Get<IHttpRequest>();
return httpReq.GetSession() as AuthUserSession;
}
public void Dispose()
{
}
}
}
|
bsd-3-clause
|
C#
|
cb5c42dbcb8636d047e04de547f7bb99ee9022c4
|
Hide details label if diagnostic error doesn't have any details link (#966)
|
tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools
|
src/dotnet/APIView/APIViewWeb/Pages/Assemblies/_CodeLine.cshtml
|
src/dotnet/APIView/APIViewWeb/Pages/Assemblies/_CodeLine.cshtml
|
@using ApiView
@using APIView.DIff
@model APIViewWeb.Models.CodeLineModel
@{
bool isRemoved = Model.Kind == DiffLineKind.Removed;
string lineClass = Model.Kind switch
{
DiffLineKind.Removed => "code-removed",
DiffLineKind.Added => "code-added",
_ => ""
};
}
<tr class="code-line" data-line-id="@(isRemoved ? string.Empty : Model.CodeLine.ElementId)">
<td class="line-comment-button-cell">
@if (!isRemoved && Model.CodeLine.ElementId != null)
{
<a class="line-comment-button">+</a>
}
</td>
<td class="code @lineClass"><span class="code-inner">@Html.Raw(Model.CodeLine.DisplayString)</span></td>
</tr>
@if (Model.Diagnostics.Any())
{
<tr class="code-diagnostics" data-line-id="@Model.CodeLine.ElementId">
<td colspan="2">
@foreach (var lineDiagnostic in Model.Diagnostics)
{
<p>
@if (lineDiagnostic.Text.StartsWith("DO"))
{
@:✅ <b>DO</b> @lineDiagnostic.Text.Substring(2)
}
else
{
@lineDiagnostic.Text
}
@if (!string.IsNullOrEmpty(lineDiagnostic.HelpLinkUri))
{
<a href="@lineDiagnostic.HelpLinkUri">Details</a>
}
</p>
}
</td>
</tr>
}
@if (Model.CommentThread != null)
{
<partial name="_CommentThreadPartial" model="@Model.CommentThread" />
}
|
@using ApiView
@using APIView.DIff
@model APIViewWeb.Models.CodeLineModel
@{
bool isRemoved = Model.Kind == DiffLineKind.Removed;
string lineClass = Model.Kind switch
{
DiffLineKind.Removed => "code-removed",
DiffLineKind.Added => "code-added",
_ => ""
};
}
<tr class="code-line" data-line-id="@(isRemoved ? string.Empty : Model.CodeLine.ElementId)">
<td class="line-comment-button-cell">
@if (!isRemoved && Model.CodeLine.ElementId != null)
{
<a class="line-comment-button">+</a>
}
</td>
<td class="code @lineClass"><span class="code-inner">@Html.Raw(Model.CodeLine.DisplayString)</span></td>
</tr>
@if (Model.Diagnostics.Any())
{
<tr class="code-diagnostics" data-line-id="@Model.CodeLine.ElementId">
<td colspan="2">
@foreach (var lineDiagnostic in Model.Diagnostics)
{
<p>
@if (lineDiagnostic.Text.StartsWith("DO"))
{
@:✅ <b>DO</b> @lineDiagnostic.Text.Substring(2)
}
else
{
@lineDiagnostic.Text
}
<a href="@lineDiagnostic.HelpLinkUri">Details</a>
</p>
}
</td>
</tr>
}
@if (Model.CommentThread != null)
{
<partial name="_CommentThreadPartial" model="@Model.CommentThread" />
}
|
mit
|
C#
|
414daa7d8e52ff9bd6024e22f60a32d5eb65bfe4
|
Make spacer use scale
|
MatterHackers/agg-sharp,larsbrubaker/agg-sharp
|
Gui/FlowSpacers.cs
|
Gui/FlowSpacers.cs
|
/*
Copyright (c) 2014, Kevin Pope
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
namespace MatterHackers.Agg.UI
{
public class HorizontalSpacer : GuiWidget
{
public HorizontalSpacer()
{
HAnchor = HAnchor.Stretch;
}
}
public class VerticalSpacer : GuiWidget
{
public VerticalSpacer()
{
VAnchor = VAnchor.Stretch;
}
}
public class HorizontalLine : GuiWidget
{
public HorizontalLine()
: base(1, 1 * DeviceScale)
{
HAnchor = HAnchor.Stretch;
}
public HorizontalLine(Color color)
: this()
{
BackgroundColor = color;
}
}
public class VerticalLine : GuiWidget
{
public VerticalLine()
: base(1 * DeviceScale, 1)
{
VAnchor = VAnchor.Stretch;
}
public VerticalLine(Color color)
: this()
{
BackgroundColor = color;
}
}
}
|
/*
Copyright (c) 2014, Kevin Pope
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
namespace MatterHackers.Agg.UI
{
public class HorizontalSpacer : GuiWidget
{
public HorizontalSpacer()
{
HAnchor = HAnchor.Stretch;
}
}
public class VerticalSpacer : GuiWidget
{
public VerticalSpacer()
{
VAnchor = VAnchor.Stretch;
}
}
public class HorizontalLine : GuiWidget
{
public HorizontalLine()
: base(1, 1)
{
HAnchor = HAnchor.Stretch;
}
public HorizontalLine(Color color)
: this()
{
BackgroundColor = color;
}
}
public class VerticalLine : GuiWidget
{
public VerticalLine()
: base(1, 1)
{
VAnchor = VAnchor.Stretch;
}
public VerticalLine(Color color)
: this()
{
BackgroundColor = color;
}
}
}
|
bsd-2-clause
|
C#
|
da36d2629f722556f29232543f86f4a48a14169e
|
fix onboarding helper test
|
zmira/abremir.AllMyBricks
|
abremir.AllMyBricks.Onboarding.Tests/Helpers/RandomKeyOptionGeneratorTests.cs
|
abremir.AllMyBricks.Onboarding.Tests/Helpers/RandomKeyOptionGeneratorTests.cs
|
using abremir.AllMyBricks.Core.Enumerations;
using abremir.AllMyBricks.Onboarding.Helpers;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace abremir.AllMyBricks.Onboarding.Tests.Helpers
{
[TestClass]
public class RandomKeyOptionGeneratorTests
{
[TestMethod]
public void GetRandomKeyOption()
{
const int count = 1000;
var algorithmTypeEnumList = new List<AlgorithmTypeEnum>();
for (int i = 0; i < count; i++)
{
var next = RandomKeyOptionGenerator.GetRandomKeyOption();
algorithmTypeEnumList.Add(next);
}
algorithmTypeEnumList.Should().HaveCount(count);
algorithmTypeEnumList.Should().OnlyContain(algoType => algoType != 0);
}
}
}
|
using abremir.AllMyBricks.Core.Enumerations;
using abremir.AllMyBricks.Onboarding.Helpers;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace abremir.AllMyBricks.Onboarding.Tests.Helpers
{
[TestClass]
public class RandomKeyOptionGeneratorTests
{
[TestMethod]
public void GetRandomKeyOption()
{
const int count = 1000;
var algorithmTypeEnumList = new List<AlgorithmTypeEnum>();
for (int i = 0; i < count; i++)
{
var next = RandomKeyOptionGenerator.GetRandomKeyOption();
algorithmTypeEnumList.Add(next);
}
algorithmTypeEnumList.Should().HaveCount(count);
algorithmTypeEnumList.Should().OnlyContain(algoType => algoType is AlgorithmTypeEnum);
}
}
}
|
mit
|
C#
|
15d4781cf729e63086125e5418960dac017e0459
|
modify the registration of the BlazorWebView and its devtools in the TodoTemplate project #1959 (#1961)
|
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
|
src/Tooling/Bit.Tooling.Templates/TodoTemplate/App/MauiProgram.cs
|
src/Tooling/Bit.Tooling.Templates/TodoTemplate/App/MauiProgram.cs
|
using System.Reflection;
using Microsoft.Extensions.FileProviders;
namespace TodoTemplate.App;
public static class MauiProgram
{
public static MauiAppBuilder CreateMauiAppBuilder()
{
#if !BlazorHybrid
throw new InvalidOperationException("Please switch to blazor hybrid as described in readme.md");
#endif
var builder = MauiApp.CreateBuilder();
var assembly = typeof(MauiProgram).GetTypeInfo().Assembly;
builder
.UseMauiApp<App>()
.Configuration.AddJsonFile(new EmbeddedFileProvider(assembly), "appsettings.json", optional: false, false);
var services = builder.Services;
services.AddMauiBlazorWebView();
#if DEBUG
services.AddBlazorWebViewDeveloperTools();
#endif
services.AddTransient<IAuthTokenProvider, ClientSideAuthTokenProvider>();
services.AddTodoTemplateSharedServices();
services.AddTodoTemplateAppServices();
return builder;
}
}
|
using System.Reflection;
using Microsoft.Extensions.FileProviders;
namespace TodoTemplate.App;
public static class MauiProgram
{
public static MauiAppBuilder CreateMauiAppBuilder()
{
#if !BlazorHybrid
throw new InvalidOperationException("Please switch to blazor hybrid as described in readme.md");
#endif
var builder = MauiApp.CreateBuilder();
var assembly = typeof(MauiProgram).GetTypeInfo().Assembly;
builder
.UseMauiApp<App>()
.Configuration.AddJsonFile(new EmbeddedFileProvider(assembly), "appsettings.json", optional: false, false);
var services = builder.Services;
services.AddMauiBlazorWebView()
#if DEBUG
.AddBlazorWebViewDeveloperTools()
#endif
;
services.AddTransient<IAuthTokenProvider, ClientSideAuthTokenProvider>();
services.AddTodoTemplateSharedServices();
services.AddTodoTemplateAppServices();
return builder;
}
}
|
mit
|
C#
|
b60a6ab24dc435c4a4391eb65cb12ef22547d644
|
Update LVMoFCoE.Designer.cs
|
geosharath/xenadmin,xenserver/xenadmin,robhoes/xenadmin,jijiang/xenadmin,cheng-z/xenadmin,cheng-z/xenadmin,minli1/xenadmin,agimofcarmen/xenadmin,GaborApatiNagy/xenadmin,stephen-turner/xenadmin,kc284/xenadmin,kc284/xenadmin,MihaelaStoica/xenadmin,ushamandya/xenadmin,letsboogey/xenadmin,minli1/xenadmin,cheng--zhang/xenadmin,geosharath/xenadmin,ushamandya/xenadmin,GaborApatiNagy/xenadmin,letsboogey/xenadmin,stephen-turner/xenadmin,geosharath/xenadmin,qlw/xenadmin,minli1/xenadmin,jijiang/xenadmin,kc284/xenadmin,qlw/xenadmin,GaborApatiNagy/xenadmin,Frezzle/xenadmin,geosharath/xenadmin,cheng--zhang/xenadmin,robhoes/xenadmin,cheng--zhang/xenadmin,minli1/xenadmin,cheng--zhang/xenadmin,stephen-turner/xenadmin,MihaelaStoica/xenadmin,letsboogey/xenadmin,letsboogey/xenadmin,geosharath/xenadmin,robhoes/xenadmin,qlw/xenadmin,huizh/xenadmin,Frezzle/xenadmin,stephen-turner/xenadmin,cheng-z/xenadmin,jijiang/xenadmin,cheng-z/xenadmin,agimofcarmen/xenadmin,robhoes/xenadmin,letsboogey/xenadmin,robhoes/xenadmin,huizh/xenadmin,kc284/xenadmin,robhoes/xenadmin,GaborApatiNagy/xenadmin,huizh/xenadmin,ushamandya/xenadmin,huizh/xenadmin,letsboogey/xenadmin,cheng-z/xenadmin,qlw/xenadmin,xenserver/xenadmin,MihaelaStoica/xenadmin,geosharath/xenadmin,huizh/xenadmin,ushamandya/xenadmin,kc284/xenadmin,Frezzle/xenadmin,ushamandya/xenadmin,GaborApatiNagy/xenadmin,ushamandya/xenadmin,Frezzle/xenadmin,qlw/xenadmin,jijiang/xenadmin,minli1/xenadmin,huizh/xenadmin,agimofcarmen/xenadmin,cheng-z/xenadmin,GaborApatiNagy/xenadmin,cheng--zhang/xenadmin,jijiang/xenadmin,Frezzle/xenadmin,cheng--zhang/xenadmin,agimofcarmen/xenadmin,minli1/xenadmin,agimofcarmen/xenadmin,stephen-turner/xenadmin,jijiang/xenadmin,stephen-turner/xenadmin,Frezzle/xenadmin,MihaelaStoica/xenadmin,MihaelaStoica/xenadmin,xenserver/xenadmin,MihaelaStoica/xenadmin
|
XenAdmin/Wizards/NewSRWizard_Pages/Frontends/LVMoFCoE.Designer.cs
|
XenAdmin/Wizards/NewSRWizard_Pages/Frontends/LVMoFCoE.Designer.cs
|
namespace XenAdmin.Wizards.NewSRWizard_Pages.Frontends
{
partial class LVMoFCoE
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
}
#endregion
}
}
|
namespace XenAdmin.Wizards.NewSRWizard_Pages.Frontends
{
partial class LVMoFCoE
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}
|
bsd-2-clause
|
C#
|
2735a162b7ecbfcea184e76de9a1d59cb8a174a6
|
test to prove the bug
|
undergroundwires/SafeOrbit
|
src/tests/IntegrationTests/Memory/SafeString/SafeStringTests.cs
|
src/tests/IntegrationTests/Memory/SafeString/SafeStringTests.cs
|
using System.Threading;
using NUnit.Framework;
namespace SafeOrbit.Memory
{
/// <seealso cref="SafeString" />
/// <seealso cref="ISafeString" />
[TestFixture]
public class SafeStringTests
{
[Test]
public void SafeString_Returns_AppendedText()
{
var expected = "test";
var sut = new SafeString();
sut.Append("t");
sut.Append("es");
sut.Append('t');
using (var sm = new SafeStringToStringMarshaler(sut))
{
var actual = sm.String;
Assert.That(actual, Is.EqualTo(expected));
}
}
[Test]
public void SafeString_ModifiedByAnotherThread_ReturnsAppendedText()
{
var expected = "test";
var sut = new SafeString();
sut.Append("t");
var thread = new Thread(() =>
{
sut.Append("es");
sut.Append('t');
});
thread.Start();
thread.Join();
using (var sm = new SafeStringToStringMarshaler(sut))
{
var actual = sm.String;
Assert.That(actual, Is.EqualTo(expected));
}
}
[Test]
public void Equals_TwoStringsWithDifferentLength_ReturnsFalse()
{
var sut1 = new SafeString();
sut1.Append("hej");
var sut2 = new SafeString();
sut2.Append("sup");
Assert.False(sut1.Equals(sut2));
Assert.False(sut2.Equals(sut1));
}
}
}
|
using System.Threading;
using NUnit.Framework;
namespace SafeOrbit.Memory
{
/// <seealso cref="SafeString" />
/// <seealso cref="ISafeString" />
[TestFixture]
public class SafeStringTests
{
[Test]
public void SafeString_Returns_AppendedText()
{
var expected = "test";
var sut = new SafeString();
sut.Append("t");
sut.Append("es");
sut.Append('t');
using (var sm = new SafeStringToStringMarshaler(sut))
{
var actual = sm.String;
Assert.That(actual, Is.EqualTo(expected));
}
}
[Test]
public void SafeString_ModifiedByAnotherThread_ReturnsAppendedText()
{
var expected = "test";
var sut = new SafeString();
sut.Append("t");
var thread = new Thread(() =>
{
sut.Append("es");
sut.Append('t');
});
thread.Start();
thread.Join();
using (var sm = new SafeStringToStringMarshaler(sut))
{
var actual = sm.String;
Assert.That(actual, Is.EqualTo(expected));
}
}
}
}
|
mit
|
C#
|
4bedfb52eafb355e58aa1ca35906a6e545eff904
|
Update InProcessServer.cs
|
cake-build/bakery,cake-build/bakery
|
src/Cake.Scripting.Transport.Tests/Fixtures/Tcp/InProcessServer.cs
|
src/Cake.Scripting.Transport.Tests/Fixtures/Tcp/InProcessServer.cs
|
using Cake.Scripting.Abstractions;
using Cake.Scripting.Transport.Tcp.Client;
using Cake.Scripting.Transport.Tcp.Server;
using Microsoft.Extensions.Logging;
namespace Cake.Scripting.Transport.Tests.Fixtures.Tcp
{
internal sealed class InProcessServer : IScriptGenerationProcess
{
private readonly IScriptGenerationService _service;
private ScriptGenerationServer _server;
private readonly ILoggerFactory _loggerFactory;
public InProcessServer(IScriptGenerationService service, ILoggerFactory loggerFactory)
{
_service = service;
_loggerFactory = loggerFactory;
}
public void Dispose()
{
_server?.Dispose();
}
public string ServerExecutablePath { get; set; }
public void Start(int port, string workingDirectory)
{
_server = new ScriptGenerationServer(_service, port, _loggerFactory);
}
}
}
|
using Cake.Scripting.Abstractions;
using Cake.Scripting.Transport.Tcp.Client;
using Cake.Scripting.Transport.Tcp.Server;
using Microsoft.Extensions.Logging;
namespace Cake.Scripting.Transport.Tests.Fixtures.Tcp
{
internal sealed class InProcessServer : IScriptGenerationProcess
{
private readonly IScriptGenerationService _service;
private ScriptGenerationServer _server;
private readonly ILoggerFactory _loggerFactory;
public InProcessServer(IScriptGenerationService service, ILoggerFactory loggerFactory)
{
_service = service;
_loggerFactory = loggerFactory;
}
public void Dispose()
{
_server?.Dispose();
}
public string ServerExecutablePath { get; set; }
public void Start(int port)
{
_server = new ScriptGenerationServer(_service, port, _loggerFactory);
}
}
}
|
mit
|
C#
|
bf147121335bc413020bdd7169ebaa8fb380c2f2
|
Add range limits to BookEditViewModel ISBN.
|
Programazing/Open-School-Library,Programazing/Open-School-Library
|
src/Open-School-Library/Models/BookViewModels/BookEditViewModel.cs
|
src/Open-School-Library/Models/BookViewModels/BookEditViewModel.cs
|
using Microsoft.AspNetCore.Mvc.Rendering;
using Open_School_Library.Data.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.BookViewModels
{
public class BookEditViewModel
{
public int BookID { get; set; }
[Required(ErrorMessage = "Title is Required!")]
public string Title { get; set; }
public string SubTitle { get; set; }
[Required(ErrorMessage = "Author is Required!")]
public string Author { get; set; }
public int GenreID { get; set; }
public SelectList GenreList { get; set; }
public int DeweyID { get; set; }
public SelectList DeweyList { get; set; }
[Required(ErrorMessage = "ISBN is Required!")]
[MaxLength(13), MinLength(10)]
public int ISBN { get; set; }
public string Availability { get; set; }
}
}
|
using Microsoft.AspNetCore.Mvc.Rendering;
using Open_School_Library.Data.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.BookViewModels
{
public class BookEditViewModel
{
public int BookID { get; set; }
[Required(ErrorMessage = "Title is Required!")]
public string Title { get; set; }
public string SubTitle { get; set; }
[Required(ErrorMessage = "Author is Required!")]
public string Author { get; set; }
public int GenreID { get; set; }
public SelectList GenreList { get; set; }
public int DeweyID { get; set; }
public SelectList DeweyList { get; set; }
[Required(ErrorMessage = "Author is Required!")]
public int ISBN { get; set; }
public string Availability { get; set; }
}
}
|
mit
|
C#
|
d74dbc6847d7a3c1595ad87a44df198f5dbed85f
|
Add InitializeParams type
|
PowerShell/PowerShellEditorServices
|
src/PowerShellEditorServices.Protocol/LanguageServer/Initialize.cs
|
src/PowerShellEditorServices.Protocol/LanguageServer/Initialize.cs
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class InitializeRequest
{
public static readonly
RequestType<InitializeParams, InitializeResult, object, object> Type =
RequestType<InitializeParams, InitializeResult, object, object>.Create("initialize");
}
public enum TraceType {
Off,
Messages,
Verbose
}
public class InitializeParams {
/// <summary>
/// The process Id of the parent process that started the server
/// </summary>
public int ProcessId { get; set; }
/// <summary>
/// The root path of the workspace. It is null if no folder is open.
///
/// This property has been deprecated in favor of RootUri.
/// </summary>
public string RootPath { get; set; }
/// <summary>
/// The root uri of the workspace. It is null if not folder is open. If both
/// `RootUri` and `RootPath` are non-null, `RootUri` should be used.
/// </summary>
public string RootUri { get; set; }
/// <summary>
/// The capabilities provided by the client.
/// </summary>
public ClientCapabilities Capabilities { get; set; }
/// <summary>
/// User provided initialization options.
///
/// This is defined as `any` type on the client side.
/// </summary>
public object InitializeOptions { get; set; }
// TODO We need to verify if the deserializer will map the type defined in the client
// to an enum.
/// <summary>
/// The initial trace setting. If omitted trace is disabled.
/// </summary>
public TraceType Trace { get; set; } = TraceType.Off;
}
public class InitializeResult
{
/// <summary>
/// Gets or sets the capabilities provided by the language server.
/// </summary>
public ServerCapabilities Capabilities { get; set; }
}
public class InitializeError
{
/// <summary>
/// Gets or sets a boolean indicating whether the client should retry
/// sending the Initialize request after showing the error to the user.
/// </summary>
public bool Retry { get; set;}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class InitializeRequest
{
public static readonly
RequestType<InitializeRequest, InitializeResult, object, object> Type =
RequestType<InitializeRequest, InitializeResult, object, object>.Create("initialize");
/// <summary>
/// Gets or sets the root path of the editor's open workspace.
/// If null it is assumed that a file was opened without having
/// a workspace open.
/// </summary>
public string RootPath { get; set; }
/// <summary>
/// Gets or sets the capabilities provided by the client (editor).
/// </summary>
public ClientCapabilities Capabilities { get; set; }
}
public class InitializeResult
{
/// <summary>
/// Gets or sets the capabilities provided by the language server.
/// </summary>
public ServerCapabilities Capabilities { get; set; }
}
public class InitializeError
{
/// <summary>
/// Gets or sets a boolean indicating whether the client should retry
/// sending the Initialize request after showing the error to the user.
/// </summary>
public bool Retry { get; set;}
}
}
|
mit
|
C#
|
85949867ecb0a3140c75ed9a541241d447c1ef9f
|
Fix IsMoyaTestRunner to check for correct interface to implement.
|
Hammerstad/Moya
|
Moya/Utility/Guard.cs
|
Moya/Utility/Guard.cs
|
namespace Moya.Utility
{
using System;
using Exceptions;
using Extensions;
using Runners;
public class Guard
{
public static void IsMoyaAttribute(Type type)
{
if (!Reflection.TypeIsMoyaAttribute(type))
{
throw new MoyaException("{0} is not a Moya Attribute.".FormatWith(type));
}
}
public static void IsMoyaTestRunner(Type type)
{
if (!typeof(IMoyaTestRunner).IsAssignableFrom(type))
{
throw new MoyaException("{0} is not a Moya Test Runner.".FormatWith(type));
}
}
}
}
|
namespace Moya.Utility
{
using System;
using Exceptions;
using Extensions;
using Runners;
public class Guard
{
public static void IsMoyaAttribute(Type type)
{
if (!Reflection.TypeIsMoyaAttribute(type))
{
throw new MoyaException("{0} is not a Moya Attribute.".FormatWith(type));
}
}
public static void IsMoyaTestRunner(Type type)
{
if (!typeof(ITestRunner).IsAssignableFrom(type))
{
throw new MoyaException("{0} is not a Moya Test Runner.".FormatWith(type));
}
}
}
}
|
mit
|
C#
|
e75146e0f1c63bfb963d0750217c67179a99248b
|
Fix scraper to scrape pick a brick facets correctly
|
rolledback/LegoSharp
|
Scraper/Scraper.cs
|
Scraper/Scraper.cs
|
using LegoSharp;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Scraper
{
class Scraper
{
static async Task Main(string[] args)
{
foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets())
{
Console.WriteLine(entry.Key);
foreach (var label in entry.Value)
{
Console.WriteLine(label.name + " " + label.value);
}
Console.WriteLine();
}
Console.WriteLine("\n-----------------------------------------\n");
foreach (var entry in await (new FacetScraper<PickABrickQuery, PickABrickResult>(new List<PickABrickQuery> { new PickABrickQuery() }, new PickABrickFacetExtractor())).scrapeFacets())
{
Console.WriteLine(entry.Key);
foreach (var label in entry.Value)
{
Console.WriteLine(label.name + " " + label.value);
}
Console.WriteLine();
}
}
}
}
|
using LegoSharp;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Scraper
{
class Scraper
{
static async Task Main(string[] args)
{
foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets())
{
Console.WriteLine(entry.Key);
foreach (var label in entry.Value)
{
Console.WriteLine(label.name + " " + label.value);
}
Console.WriteLine();
}
Console.WriteLine("\n-----------------------------------------\n");
foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets())
{
Console.WriteLine(entry.Key);
foreach (var label in entry.Value)
{
Console.WriteLine(label.name + " " + label.value);
}
Console.WriteLine();
}
}
}
}
|
mit
|
C#
|
b1a1a6c4abf094dcf96823277d0373b5c4c2a3b3
|
Update version number to 0.6 for dev.
|
victorbush/ego.nefsedit
|
SharedAssemblyInfo.cs
|
SharedAssemblyInfo.cs
|
// See LICENSE.txt for license information.
using System.Reflection;
[assembly: AssemblyCopyright("Copyright © VictorBush 2020")]
// 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.6.0.0")]
[assembly: AssemblyFileVersion("0.6.0.0")]
|
// See LICENSE.txt for license information.
using System.Reflection;
[assembly: AssemblyCopyright("Copyright © VictorBush 2020")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
|
mit
|
C#
|
8d7491b0ac6f7569f5a04587e5e0e3165066c5e6
|
Fix mscorlib asmmeta and add SecurityCritical attribute to the two new functions in AssemblyExtensions
|
bartonjs/coreclr,bartonjs/coreclr,sagood/coreclr,bitcrazed/coreclr,SlavaRa/coreclr,Dmitry-Me/coreclr,pgavlin/coreclr,krixalis/coreclr,benpye/coreclr,xoofx/coreclr,Samana/coreclr,dasMulli/coreclr,AlfredoMS/coreclr,naamunds/coreclr,chrishaly/coreclr,bartonjs/coreclr,shahid-pk/coreclr,taylorjonl/coreclr,ktos/coreclr,James-Ko/coreclr,swgillespie/coreclr,cydhaselton/coreclr,taylorjonl/coreclr,manu-silicon/coreclr,JosephTremoulet/coreclr,Lucrecious/coreclr,xoofx/coreclr,krytarowski/coreclr,ragmani/coreclr,YongseopKim/coreclr,krk/coreclr,taylorjonl/coreclr,tijoytom/coreclr,benpye/coreclr,ruben-ayrapetyan/coreclr,alexperovich/coreclr,sjsinju/coreclr,mokchhya/coreclr,jhendrixMSFT/coreclr,neurospeech/coreclr,gkhanna79/coreclr,ZhichengZhu/coreclr,vinnyrom/coreclr,Alcaro/coreclr,mmitche/coreclr,geertdoornbos/coreclr,SlavaRa/coreclr,YongseopKim/coreclr,chuck-mitchell/coreclr,shahid-pk/coreclr,manu-silicon/coreclr,martinwoodward/coreclr,ktos/coreclr,KrzysztofCwalina/coreclr,JosephTremoulet/coreclr,chaos7theory/coreclr,jamesqo/coreclr,cshung/coreclr,cydhaselton/coreclr,xoofx/coreclr,bitcrazed/coreclr,blackdwarf/coreclr,cydhaselton/coreclr,James-Ko/coreclr,ericeil/coreclr,botaberg/coreclr,zmaruo/coreclr,cshung/coreclr,krk/coreclr,krixalis/coreclr,manu-silicon/coreclr,wkchoy74/coreclr,geertdoornbos/coreclr,ramarag/coreclr,Samana/coreclr,bartdesmet/coreclr,naamunds/coreclr,gkhanna79/coreclr,gkhanna79/coreclr,taylorjonl/coreclr,Sridhar-MS/coreclr,taylorjonl/coreclr,shahid-pk/coreclr,benpye/coreclr,kyulee1/coreclr,naamunds/coreclr,Dmitry-Me/coreclr,sperling/coreclr,sejongoh/coreclr,kyulee1/coreclr,perfectphase/coreclr,Godin/coreclr,tijoytom/coreclr,wateret/coreclr,hseok-oh/coreclr,benpye/coreclr,cmckinsey/coreclr,wateret/coreclr,alexperovich/coreclr,naamunds/coreclr,jamesqo/coreclr,krk/coreclr,jamesqo/coreclr,OryJuVog/coreclr,vinnyrom/coreclr,yeaicc/coreclr,Dmitry-Me/coreclr,ruben-ayrapetyan/coreclr,yeaicc/coreclr,krixalis/coreclr,vinnyrom/coreclr,cmckinsey/coreclr,wkchoy74/coreclr,qiudesong/coreclr,taylorjonl/coreclr,mokchhya/coreclr,yeaicc/coreclr,schellap/coreclr,ktos/coreclr,wkchoy74/coreclr,rartemev/coreclr,benpye/coreclr,YongseopKim/coreclr,mokchhya/coreclr,krk/coreclr,JonHanna/coreclr,JonHanna/coreclr,gkhanna79/coreclr,sagood/coreclr,stormleoxia/coreclr,orthoxerox/coreclr,zmaruo/coreclr,swgillespie/coreclr,mmitche/coreclr,sperling/coreclr,Alcaro/coreclr,mskvortsov/coreclr,dpodder/coreclr,ericeil/coreclr,dpodder/coreclr,xoofx/coreclr,bartonjs/coreclr,yizhang82/coreclr,russellhadley/coreclr,mskvortsov/coreclr,Alcaro/coreclr,mocsy/coreclr,naamunds/coreclr,ericeil/coreclr,russellhadley/coreclr,bartdesmet/coreclr,jhendrixMSFT/coreclr,wateret/coreclr,Djuffin/coreclr,qiudesong/coreclr,poizan42/coreclr,SlavaRa/coreclr,OryJuVog/coreclr,josteink/coreclr,sejongoh/coreclr,DasAllFolks/coreclr,josteink/coreclr,Lucrecious/coreclr,yeaicc/coreclr,Dmitry-Me/coreclr,martinwoodward/coreclr,yizhang82/coreclr,jamesqo/coreclr,dpodder/coreclr,Sridhar-MS/coreclr,mocsy/coreclr,cmckinsey/coreclr,serenabenny/coreclr,perfectphase/coreclr,orthoxerox/coreclr,mocsy/coreclr,Sridhar-MS/coreclr,schellap/coreclr,poizan42/coreclr,Djuffin/coreclr,jamesqo/coreclr,KrzysztofCwalina/coreclr,manu-silicon/coreclr,roncain/coreclr,cmckinsey/coreclr,wtgodbe/coreclr,chrishaly/coreclr,botaberg/coreclr,ktos/coreclr,krk/coreclr,bitcrazed/coreclr,parjong/coreclr,jhendrixMSFT/coreclr,geertdoornbos/coreclr,gkhanna79/coreclr,iamjasonp/coreclr,sperling/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,AlexGhiondea/coreclr,ramarag/coreclr,yizhang82/coreclr,martinwoodward/coreclr,Djuffin/coreclr,AlfredoMS/coreclr,OryJuVog/coreclr,wtgodbe/coreclr,cshung/coreclr,hseok-oh/coreclr,Lucrecious/coreclr,AlfredoMS/coreclr,krixalis/coreclr,LLITCHEV/coreclr,parjong/coreclr,dasMulli/coreclr,pgavlin/coreclr,KrzysztofCwalina/coreclr,ZhichengZhu/coreclr,kyulee1/coreclr,SlavaRa/coreclr,mskvortsov/coreclr,jamesqo/coreclr,martinwoodward/coreclr,MCGPPeters/coreclr,zmaruo/coreclr,Sridhar-MS/coreclr,ramarag/coreclr,sjsinju/coreclr,rartemev/coreclr,martinwoodward/coreclr,blackdwarf/coreclr,YongseopKim/coreclr,wkchoy74/coreclr,Dmitry-Me/coreclr,LLITCHEV/coreclr,jhendrixMSFT/coreclr,pgavlin/coreclr,josteink/coreclr,yizhang82/coreclr,qiudesong/coreclr,poizan42/coreclr,pgavlin/coreclr,andschwa/coreclr,swgillespie/coreclr,zmaruo/coreclr,cshung/coreclr,AlexGhiondea/coreclr,cmckinsey/coreclr,James-Ko/coreclr,JosephTremoulet/coreclr,tijoytom/coreclr,ruben-ayrapetyan/coreclr,ramarag/coreclr,Godin/coreclr,MCGPPeters/coreclr,bitcrazed/coreclr,wkchoy74/coreclr,Alcaro/coreclr,benpye/coreclr,Dmitry-Me/coreclr,SlavaRa/coreclr,orthoxerox/coreclr,kyulee1/coreclr,tijoytom/coreclr,jhendrixMSFT/coreclr,krytarowski/coreclr,qiudesong/coreclr,iamjasonp/coreclr,Samana/coreclr,Samana/coreclr,serenabenny/coreclr,swgillespie/coreclr,OryJuVog/coreclr,geertdoornbos/coreclr,sejongoh/coreclr,manu-silicon/coreclr,jhendrixMSFT/coreclr,wateret/coreclr,chrishaly/coreclr,stormleoxia/coreclr,KrzysztofCwalina/coreclr,MCGPPeters/coreclr,yizhang82/coreclr,AlexGhiondea/coreclr,alexperovich/coreclr,mocsy/coreclr,KrzysztofCwalina/coreclr,perfectphase/coreclr,ragmani/coreclr,cmckinsey/coreclr,chaos7theory/coreclr,schellap/coreclr,pgavlin/coreclr,dasMulli/coreclr,martinwoodward/coreclr,russellhadley/coreclr,dpodder/coreclr,rartemev/coreclr,chuck-mitchell/coreclr,dpodder/coreclr,rartemev/coreclr,cshung/coreclr,schellap/coreclr,Lucrecious/coreclr,parjong/coreclr,neurospeech/coreclr,ericeil/coreclr,AlexGhiondea/coreclr,wtgodbe/coreclr,LLITCHEV/coreclr,cydhaselton/coreclr,bartdesmet/coreclr,sejongoh/coreclr,poizan42/coreclr,chuck-mitchell/coreclr,alexperovich/coreclr,andschwa/coreclr,mmitche/coreclr,AlfredoMS/coreclr,sagood/coreclr,MCGPPeters/coreclr,dasMulli/coreclr,sjsinju/coreclr,botaberg/coreclr,Alcaro/coreclr,roncain/coreclr,chaos7theory/coreclr,swgillespie/coreclr,LLITCHEV/coreclr,Sridhar-MS/coreclr,shahid-pk/coreclr,kyulee1/coreclr,wateret/coreclr,yeaicc/coreclr,sejongoh/coreclr,krk/coreclr,roncain/coreclr,ragmani/coreclr,bartonjs/coreclr,zmaruo/coreclr,roncain/coreclr,dasMulli/coreclr,Godin/coreclr,Djuffin/coreclr,James-Ko/coreclr,ramarag/coreclr,DasAllFolks/coreclr,ktos/coreclr,Lucrecious/coreclr,josteink/coreclr,schellap/coreclr,roncain/coreclr,parjong/coreclr,bitcrazed/coreclr,hseok-oh/coreclr,LLITCHEV/coreclr,sjsinju/coreclr,sperling/coreclr,wkchoy74/coreclr,Godin/coreclr,blackdwarf/coreclr,Lucrecious/coreclr,andschwa/coreclr,stormleoxia/coreclr,gkhanna79/coreclr,perfectphase/coreclr,parjong/coreclr,mokchhya/coreclr,mmitche/coreclr,chaos7theory/coreclr,ruben-ayrapetyan/coreclr,swgillespie/coreclr,ktos/coreclr,ZhichengZhu/coreclr,stormleoxia/coreclr,KrzysztofCwalina/coreclr,mmitche/coreclr,russellhadley/coreclr,perfectphase/coreclr,mskvortsov/coreclr,russellhadley/coreclr,Lucrecious/coreclr,xoofx/coreclr,sperling/coreclr,chaos7theory/coreclr,ragmani/coreclr,James-Ko/coreclr,ZhichengZhu/coreclr,DasAllFolks/coreclr,blackdwarf/coreclr,josteink/coreclr,dasMulli/coreclr,bartdesmet/coreclr,tijoytom/coreclr,chrishaly/coreclr,botaberg/coreclr,chuck-mitchell/coreclr,iamjasonp/coreclr,botaberg/coreclr,iamjasonp/coreclr,sperling/coreclr,orthoxerox/coreclr,geertdoornbos/coreclr,sejongoh/coreclr,wtgodbe/coreclr,Samana/coreclr,DasAllFolks/coreclr,bartdesmet/coreclr,YongseopKim/coreclr,chuck-mitchell/coreclr,Djuffin/coreclr,poizan42/coreclr,Godin/coreclr,YongseopKim/coreclr,sperling/coreclr,sagood/coreclr,taylorjonl/coreclr,bartdesmet/coreclr,parjong/coreclr,neurospeech/coreclr,josteink/coreclr,yeaicc/coreclr,Samana/coreclr,ragmani/coreclr,chrishaly/coreclr,naamunds/coreclr,bartdesmet/coreclr,roncain/coreclr,serenabenny/coreclr,AlfredoMS/coreclr,ktos/coreclr,hseok-oh/coreclr,sjsinju/coreclr,serenabenny/coreclr,xoofx/coreclr,andschwa/coreclr,martinwoodward/coreclr,yizhang82/coreclr,stormleoxia/coreclr,rartemev/coreclr,krixalis/coreclr,andschwa/coreclr,JonHanna/coreclr,KrzysztofCwalina/coreclr,roncain/coreclr,MCGPPeters/coreclr,JosephTremoulet/coreclr,mskvortsov/coreclr,DasAllFolks/coreclr,yeaicc/coreclr,James-Ko/coreclr,vinnyrom/coreclr,LLITCHEV/coreclr,dpodder/coreclr,chuck-mitchell/coreclr,bitcrazed/coreclr,tijoytom/coreclr,JonHanna/coreclr,andschwa/coreclr,mokchhya/coreclr,cydhaselton/coreclr,stormleoxia/coreclr,mokchhya/coreclr,wateret/coreclr,sjsinju/coreclr,Djuffin/coreclr,blackdwarf/coreclr,AlexGhiondea/coreclr,krytarowski/coreclr,kyulee1/coreclr,stormleoxia/coreclr,dasMulli/coreclr,chaos7theory/coreclr,neurospeech/coreclr,ruben-ayrapetyan/coreclr,hseok-oh/coreclr,Dmitry-Me/coreclr,bitcrazed/coreclr,iamjasonp/coreclr,andschwa/coreclr,vinnyrom/coreclr,AlexGhiondea/coreclr,ZhichengZhu/coreclr,neurospeech/coreclr,orthoxerox/coreclr,OryJuVog/coreclr,krytarowski/coreclr,wtgodbe/coreclr,vinnyrom/coreclr,jhendrixMSFT/coreclr,rartemev/coreclr,orthoxerox/coreclr,shahid-pk/coreclr,bartonjs/coreclr,krytarowski/coreclr,neurospeech/coreclr,swgillespie/coreclr,serenabenny/coreclr,blackdwarf/coreclr,Godin/coreclr,serenabenny/coreclr,iamjasonp/coreclr,mocsy/coreclr,JonHanna/coreclr,sagood/coreclr,geertdoornbos/coreclr,Sridhar-MS/coreclr,cmckinsey/coreclr,schellap/coreclr,mocsy/coreclr,mocsy/coreclr,ruben-ayrapetyan/coreclr,wkchoy74/coreclr,ragmani/coreclr,JosephTremoulet/coreclr,josteink/coreclr,cydhaselton/coreclr,benpye/coreclr,poizan42/coreclr,mskvortsov/coreclr,MCGPPeters/coreclr,qiudesong/coreclr,shahid-pk/coreclr,manu-silicon/coreclr,ramarag/coreclr,Godin/coreclr,naamunds/coreclr,LLITCHEV/coreclr,bartonjs/coreclr,vinnyrom/coreclr,ramarag/coreclr,chrishaly/coreclr,alexperovich/coreclr,ZhichengZhu/coreclr,russellhadley/coreclr,zmaruo/coreclr,hseok-oh/coreclr,chuck-mitchell/coreclr,sagood/coreclr,ZhichengZhu/coreclr,sejongoh/coreclr,ericeil/coreclr,mokchhya/coreclr,manu-silicon/coreclr,JonHanna/coreclr,alexperovich/coreclr,DasAllFolks/coreclr,blackdwarf/coreclr,perfectphase/coreclr,krytarowski/coreclr,OryJuVog/coreclr,geertdoornbos/coreclr,SlavaRa/coreclr,qiudesong/coreclr,krixalis/coreclr,wtgodbe/coreclr,botaberg/coreclr,shahid-pk/coreclr,ericeil/coreclr,schellap/coreclr,cshung/coreclr,AlfredoMS/coreclr,Alcaro/coreclr,pgavlin/coreclr
|
src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
|
src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Reflection.Metadata
{
public static class AssemblyExtensions
{
[DllImport(JitHelpers.QCall)]
[SecurityCritical] // unsafe method
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);
// Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader.
// - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET
// native images, etc.
// - Callers should not write to the metadata blob
// - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is
// associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
// metadata blob.
[CLSCompliant(false)] // out byte* blob
[SecurityCritical] // unsafe method
public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
blob = null;
length = 0;
return InternalTryGetRawMetadata((RuntimeAssembly)assembly, ref blob, ref length);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Reflection.Metadata
{
public static class AssemblyExtensions
{
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);
// Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader.
// - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET
// native images, etc.
// - Callers should not write to the metadata blob
// - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is
// associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
// metadata blob.
[CLSCompliant(false)] // out byte* blob
public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
blob = null;
length = 0;
return InternalTryGetRawMetadata((RuntimeAssembly)assembly, ref blob, ref length);
}
}
}
|
mit
|
C#
|
11c59a141f24aebf68f21fb7d79f88980b1233f1
|
Add background to rankings header
|
ppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,smoogipooo/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,EVAST9919/osu
|
osu.Game/Overlays/Rankings/RankingsOverlayHeader.cs
|
osu.Game/Overlays/Rankings/RankingsOverlayHeader.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets;
using osu.Game.Users;
namespace osu.Game.Overlays.Rankings
{
public class RankingsOverlayHeader : TabControlOverlayHeader<RankingsScope>
{
public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
public readonly Bindable<Country> Country = new Bindable<Country>();
protected override ScreenTitle CreateTitle() => new RankingsTitle
{
Scope = { BindTarget = Current }
};
protected override Drawable CreateTitleContent() => new OverlayRulesetSelector
{
Current = Ruleset
};
protected override Drawable CreateContent() => new CountryFilter
{
Current = Country
};
protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/rankings");
private class RankingsTitle : ScreenTitle
{
public readonly Bindable<RankingsScope> Scope = new Bindable<RankingsScope>();
public RankingsTitle()
{
Title = "ranking";
}
protected override void LoadComplete()
{
base.LoadComplete();
Scope.BindValueChanged(scope => Section = scope.NewValue.ToString().ToLowerInvariant(), true);
}
protected override Drawable CreateIcon() => new ScreenTitleTextureIcon(@"Icons/rankings");
}
}
public enum RankingsScope
{
Performance,
Spotlights,
Score,
Country
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets;
using osu.Game.Users;
namespace osu.Game.Overlays.Rankings
{
public class RankingsOverlayHeader : TabControlOverlayHeader<RankingsScope>
{
public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
public readonly Bindable<Country> Country = new Bindable<Country>();
protected override ScreenTitle CreateTitle() => new RankingsTitle
{
Scope = { BindTarget = Current }
};
protected override Drawable CreateTitleContent() => new OverlayRulesetSelector
{
Current = Ruleset
};
protected override Drawable CreateContent() => new CountryFilter
{
Current = Country
};
private class RankingsTitle : ScreenTitle
{
public readonly Bindable<RankingsScope> Scope = new Bindable<RankingsScope>();
public RankingsTitle()
{
Title = "ranking";
}
protected override void LoadComplete()
{
base.LoadComplete();
Scope.BindValueChanged(scope => Section = scope.NewValue.ToString().ToLowerInvariant(), true);
}
protected override Drawable CreateIcon() => new ScreenTitleTextureIcon(@"Icons/rankings");
}
}
public enum RankingsScope
{
Performance,
Spotlights,
Score,
Country
}
}
|
mit
|
C#
|
f46209c8caf8d7e5e1e506b14ff409e57c92911a
|
add engine to aplication
|
ivayloivanof/Libbon_Tank_Game
|
TankGame/StartGame.cs
|
TankGame/StartGame.cs
|
namespace TankGame
{
using System;
using System.Windows.Forms;
public static class StartGame
{
[STAThread]
public static void Main()
{
Engine engine = new Engine();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(engine));
}
}
}
|
namespace TankGame
{
using System;
using System.Windows.Forms;
public static class StartGame
{
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
|
cc0-1.0
|
C#
|
3c3c58a8cc3c4fe778233ce78f39d2cf0bedae84
|
Move test up
|
physhi/roslyn,KevinRansom/roslyn,sharwell/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,dotnet/roslyn,sharwell/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,mavasani/roslyn,eriawan/roslyn,eriawan/roslyn,physhi/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,wvdd007/roslyn,sharwell/roslyn,mavasani/roslyn,physhi/roslyn,weltkante/roslyn,KevinRansom/roslyn,diryboy/roslyn,dotnet/roslyn,diryboy/roslyn,wvdd007/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn
|
src/VisualStudio/CSharp/Test/PersistentStorage/CloudCachePersistentStorageTests.cs
|
src/VisualStudio/CSharp/Test/PersistentStorage/CloudCachePersistentStorageTests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
public class CloudCachePersistentStorageTests : AbstractPersistentStorageTests
{
internal override AbstractPersistentStorageService GetStorageService(
OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase)
{
var threadingContext = exportProvider.GetExports<IThreadingContext>().Single().Value;
return new MockCloudCachePersistentStorageService(
locationService,
relativePathBase,
cs =>
{
if (cs is IAsyncDisposable asyncDisposable)
{
threadingContext.JoinableTaskFactory.Run(
() => asyncDisposable.DisposeAsync().AsTask());
}
else if (cs is IDisposable disposable)
{
disposable.Dispose();
}
});
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
public class CloudCachePersistentStorageTests : AbstractPersistentStorageTests
{
internal override AbstractPersistentStorageService GetStorageService(
OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase)
{
var threadingContext = exportProvider.GetExports<IThreadingContext>().Single().Value;
return new MockCloudCachePersistentStorageService(
locationService,
relativePathBase,
cs =>
{
if (cs is IAsyncDisposable asyncDisposable)
{
threadingContext.JoinableTaskFactory.Run(
() => asyncDisposable.DisposeAsync().AsTask());
}
else if (cs is IDisposable disposable)
{
disposable.Dispose();
}
});
}
}
}
|
mit
|
C#
|
65a3df1597f9ccd8f2b6e9b39e98b5bad68cfe9e
|
Make position ctors public
|
xamarin/Xamarin.Mobile,moljac/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,nexussays/Xamarin.Mobile,xamarin/Xamarin.Mobile,orand/Xamarin.Mobile
|
Shared/Position.cs
|
Shared/Position.cs
|
using System;
namespace Xamarin.Geolocation
{
public class Position
{
public Position()
{
}
public Position (Position position)
{
Timestamp = position.Timestamp;
Latitude = position.Latitude;
Longitude = position.Longitude;
Altitude = position.AltitudeAccuracy;
AltitudeAccuracy = position.AltitudeAccuracy;
Accuracy = position.Accuracy;
Heading = position.Heading;
Speed = position.Speed;
}
public DateTimeOffset Timestamp
{
get;
set;
}
/// <summary>
/// Gets or sets the latitude.
/// </summary>
public double Latitude
{
get;
set;
}
/// <summary>
/// Gets or sets the longitude.
/// </summary>
public double Longitude
{
get;
set;
}
/// <summary>
/// Gets or sets the altitude in meters relative to sea level.
/// </summary>
public double Altitude
{
get;
set;
}
/// <summary>
/// Gets or sets the potential position error radius in meters.
/// </summary>
public double Accuracy
{
get;
set;
}
/// <summary>
/// Gets or sets the potential altitude error range in meters.
/// </summary>
/// <remarks>
/// Not supported on Android, will always read 0.
/// </remarks>
public double AltitudeAccuracy
{
get;
set;
}
/// <summary>
/// Gets or sets the heading in degrees relative to true North.
/// </summary>
public double Heading
{
get;
set;
}
/// <summary>
/// Gets or sets the speed in meters per second.
/// </summary>
public double Speed
{
get;
set;
}
}
public class PositionEventArgs
: EventArgs
{
public PositionEventArgs (Position position)
{
if (position == null)
throw new ArgumentNullException ("position");
Position = position;
}
public Position Position
{
get;
private set;
}
}
public class GeolocationException
: Exception
{
public GeolocationException()
: base()
{
}
public GeolocationException (string message)
: base (message)
{
}
}
public class PositionErrorEventArgs
: EventArgs
{
public PositionErrorEventArgs (PositionErrorCode error)
{
Error = error;
}
public PositionErrorCode Error
{
get;
private set;
}
}
public enum PositionErrorCode
{
/// <summary>
/// The provider was unable to retrieve any position data.
/// </summary>
PositionUnavailable,
/// <summary>
/// The app is not, or no longer, authorized to receive location data.
/// </summary>
Unauthorized
}
}
|
using System;
namespace Xamarin.Geolocation
{
public class Position
{
internal Position()
{
}
internal Position (Position position)
{
Timestamp = position.Timestamp;
Latitude = position.Latitude;
Longitude = position.Longitude;
Altitude = position.AltitudeAccuracy;
AltitudeAccuracy = position.AltitudeAccuracy;
Accuracy = position.Accuracy;
Heading = position.Heading;
Speed = position.Speed;
}
public DateTimeOffset Timestamp
{
get;
set;
}
/// <summary>
/// Gets or sets the latitude.
/// </summary>
public double Latitude
{
get;
set;
}
/// <summary>
/// Gets or sets the longitude.
/// </summary>
public double Longitude
{
get;
set;
}
/// <summary>
/// Gets or sets the altitude in meters relative to sea level.
/// </summary>
public double Altitude
{
get;
set;
}
/// <summary>
/// Gets or sets the potential position error radius in meters.
/// </summary>
public double Accuracy
{
get;
set;
}
/// <summary>
/// Gets or sets the potential altitude error range in meters.
/// </summary>
/// <remarks>
/// Not supported on Android, will always read 0.
/// </remarks>
public double AltitudeAccuracy
{
get;
set;
}
/// <summary>
/// Gets or sets the heading in degrees relative to true North.
/// </summary>
public double Heading
{
get;
set;
}
/// <summary>
/// Gets or sets the speed in meters per second.
/// </summary>
public double Speed
{
get;
set;
}
}
public class PositionEventArgs
: EventArgs
{
public PositionEventArgs (Position position)
{
if (position == null)
throw new ArgumentNullException ("position");
Position = position;
}
public Position Position
{
get;
private set;
}
}
public class GeolocationException
: Exception
{
public GeolocationException()
: base()
{
}
public GeolocationException (string message)
: base (message)
{
}
}
public class PositionErrorEventArgs
: EventArgs
{
public PositionErrorEventArgs (PositionErrorCode error)
{
Error = error;
}
public PositionErrorCode Error
{
get;
private set;
}
}
public enum PositionErrorCode
{
/// <summary>
/// The provider was unable to retrieve any position data.
/// </summary>
PositionUnavailable,
/// <summary>
/// The app is not, or no longer, authorized to receive location data.
/// </summary>
Unauthorized
}
}
|
apache-2.0
|
C#
|
cb2f0f4aca8ea9a80da79c38cd1bb0cbd8d385e6
|
Update SymbolPriceChangeTickerResponse.cs
|
glitch100/BinanceDotNet
|
BinanceExchange.API/Models/Response/SymbolPriceChangeTickerResponse.cs
|
BinanceExchange.API/Models/Response/SymbolPriceChangeTickerResponse.cs
|
using System;
using System.Runtime.Serialization;
using BinanceExchange.API.Converter;
using Newtonsoft.Json;
namespace BinanceExchange.API.Models.Response
{
[DataContract]
public class SymbolPriceChangeTickerResponse
{
[DataMember(Order = 1)]
public decimal PriceChange { get; set; }
[DataMember(Order = 2)]
public decimal PriceChangePercent { get; set; }
[DataMember(Order = 3)]
[JsonProperty(PropertyName = "weightedAvgPrice")]
public decimal WeightedAveragePercent { get; set; }
[DataMember(Order = 4)]
[JsonProperty(PropertyName = "prevClosePrice")]
public decimal PreviousClosePrice { get; set; }
[DataMember(Order = 5)]
public decimal LastPrice { get; set; }
[DataMember(Order = 6)]
public decimal BidPrice { get; set; }
[DataMember(Order = 7)]
public decimal AskPrice { get; set; }
[DataMember(Order = 8)]
public decimal OpenPrice { get; set; }
[DataMember(Order = 9)]
public decimal HighPrice { get; set; }
[DataMember(Order = 10)]
public decimal LowPrice { get; set; }
[DataMember(Order = 11)]
public decimal Volume { get; set; }
[DataMember(Order = 12)]
[JsonConverter(typeof(EpochTimeConverter))]
public DateTime OpenTime { get; set; }
[DataMember(Order = 13)]
[JsonConverter(typeof(EpochTimeConverter))]
public DateTime CloseTime { get; set; }
[DataMember(Order = 14)]
[JsonProperty(PropertyName = "firstId")]
public long FirstTradeId { get; set; }
[DataMember(Order = 15)]
[JsonProperty(PropertyName = "lastId")]
public long LastId { get; set; }
[DataMember(Order = 16)]
[JsonProperty(PropertyName = "count")]
public int TradeCount { get; set; }
}
}
|
using System;
using System.Runtime.Serialization;
using BinanceExchange.API.Converter;
using Newtonsoft.Json;
namespace BinanceExchange.API.Models.Response
{
[DataContract]
public class SymbolPriceChangeTickerResponse
{
[DataMember(Order = 1)]
public decimal PriceChange { get; set; }
[DataMember(Order = 2)]
public decimal PriceChangePercent { get; set; }
[DataMember(Order = 3)]
[JsonProperty(PropertyName = "weightedAvgPrice")]
public decimal WeightedAveragePercent { get; set; }
[DataMember(Order = 4)]
[JsonProperty(PropertyName = "prevClosePrice")]
public decimal PreviousClosePrice { get; set; }
[DataMember(Order = 5)]
public decimal LastPrice { get; set; }
[DataMember(Order = 6)]
public decimal BidPrice { get; set; }
[DataMember(Order = 7)]
public decimal AskPrice { get; set; }
[DataMember(Order = 8)]
public decimal OpenPrice { get; set; }
[DataMember(Order = 8)]
public decimal HighPrice { get; set; }
[DataMember(Order = 9)]
public decimal Volume { get; set; }
[DataMember(Order = 10)]
[JsonConverter(typeof(EpochTimeConverter))]
public DateTime OpenTime { get; set; }
[DataMember(Order = 11)]
[JsonConverter(typeof(EpochTimeConverter))]
public DateTime CloseTime { get; set; }
[DataMember(Order = 12)]
[JsonProperty(PropertyName = "firstId")]
public long FirstTradeId { get; set; }
[DataMember(Order = 13)]
[JsonProperty(PropertyName = "lastId")]
public long LastId { get; set; }
[DataMember(Order = 14)]
[JsonProperty(PropertyName = "count")]
public int TradeCount { get; set; }
}
}
|
mit
|
C#
|
eb407ee00f581dd16cb91b9df46d6941047492e2
|
Fix compile error by commenting out offending code.
|
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
|
Client/Systems/VesselFlightStateSys/VesselFlightStateMessageHandler.cs
|
Client/Systems/VesselFlightStateSys/VesselFlightStateMessageHandler.cs
|
using System.Collections.Concurrent;
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.VesselFlightStateSys
{
public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler
{
public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>();
public void HandleMessage(IMessageData messageData)
{
var msgData = messageData as VesselFlightStateMsgData;
if (msgData == null) return;
var flightState = new FlightCtrlState
{
mainThrottle = msgData.MainThrottle,
wheelThrottleTrim = msgData.WheelThrottleTrim,
X = msgData.X,
Y = msgData.Y,
Z = msgData.Z,
killRot = msgData.KillRot,
gearUp = msgData.GearUp,
gearDown = msgData.GearDown,
headlight = msgData.Headlight,
wheelThrottle = msgData.WheelThrottle,
roll = msgData.Roll,
yaw = msgData.Yaw,
pitch = msgData.Pitch,
rollTrim = msgData.RollTrim,
yawTrim = msgData.YawTrim,
pitchTrim = msgData.PitchTrim,
wheelSteer = msgData.WheelSteer,
wheelSteerTrim = msgData.WheelSteerTrim
};
//System.FlightState = flightState;
}
}
}
|
using System.Collections.Concurrent;
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.VesselFlightStateSys
{
public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler
{
public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>();
public void HandleMessage(IMessageData messageData)
{
var msgData = messageData as VesselFlightStateMsgData;
if (msgData == null) return;
var flightState = new FlightCtrlState
{
mainThrottle = msgData.MainThrottle,
wheelThrottleTrim = msgData.WheelThrottleTrim,
X = msgData.X,
Y = msgData.Y,
Z = msgData.Z,
killRot = msgData.KillRot,
gearUp = msgData.GearUp,
gearDown = msgData.GearDown,
headlight = msgData.Headlight,
wheelThrottle = msgData.WheelThrottle,
roll = msgData.Roll,
yaw = msgData.Yaw,
pitch = msgData.Pitch,
rollTrim = msgData.RollTrim,
yawTrim = msgData.YawTrim,
pitchTrim = msgData.PitchTrim,
wheelSteer = msgData.WheelSteer,
wheelSteerTrim = msgData.WheelSteerTrim
};
System.FlightState = flightState;
}
}
}
|
mit
|
C#
|
12c6a2c2cde74f2d4c8a47fccb8cc7bb43e89a47
|
remove now-unused ToursDir BaseModel attribute
|
WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website
|
src/WWTMVC5/Models/BaseModel.cs
|
src/WWTMVC5/Models/BaseModel.cs
|
using WWTMVC5.WebServices;
using System.Web.Configuration;
using Microsoft.Live;
namespace WWTMVC5.Models
{
public class BaseModel
{
private readonly string _contentDir;
private readonly string _imgDir;
private readonly string _jsDir;
private readonly string _cssDir;
private readonly string _resVer;
private ProfileDetails _profile;
public BaseModel()
{
_cssDir = "/Content/CSS";
_jsDir = "/Scripts";
_contentDir = "//wwtweb.blob.core.windows.net";
_imgDir = ContentDir + "/images";
_resVer = ConfigReader<string>.GetSetting("ResourcesVersion");
}
public string CssDir
{
get { return _cssDir; }
}
public string JsDir
{
get { return _jsDir; }
}
public string ContentDir
{
get { return _contentDir; }
}
public string ImgDir
{
get { return _imgDir; }
}
public string ResVer
{
get { return _resVer; }
}
public ProfileDetails User
{
get
{
if (_profile != null)
{
return _profile;
}
var profileDetails = SessionWrapper.Get<ProfileDetails>("ProfileDetails");
return profileDetails;
}
set { _profile = value; }
}
}
}
|
using WWTMVC5.WebServices;
using System.Web.Configuration;
using Microsoft.Live;
namespace WWTMVC5.Models
{
public class BaseModel
{
private readonly string _contentDir;
private readonly string _imgDir;
private readonly string _jsDir;
private readonly string _cssDir;
private readonly string _toursDir;
private readonly string _resVer;
private ProfileDetails _profile;
public BaseModel()
{
_cssDir = "/Content/CSS";
_jsDir = "/Scripts";
_contentDir = "//wwtweb.blob.core.windows.net";
_imgDir = ContentDir + "/images";
_toursDir = ContentDir + "/WebControlTours";
_resVer = ConfigReader<string>.GetSetting("ResourcesVersion");
}
public string CssDir
{
get { return _cssDir; }
}
public string JsDir
{
get { return _jsDir; }
}
public string ContentDir
{
get { return _contentDir; }
}
public string ImgDir
{
get { return _imgDir; }
}
public string ToursDir
{
get { return _toursDir; }
}
public string ResVer
{
get { return _resVer; }
}
public ProfileDetails User
{
get
{
if (_profile != null)
{
return _profile;
}
var profileDetails = SessionWrapper.Get<ProfileDetails>("ProfileDetails");
return profileDetails;
}
set { _profile = value; }
}
}
}
|
mit
|
C#
|
5963783740192b7e8a6cc8f98bf6bef18a0ff3b1
|
Add Play Requirement to TransfigurationExam
|
StefanoFiumara/Harry-Potter-Unity
|
Assets/Scripts/HarryPotterUnity/Cards/Transfiguration/Spells/TransfigurationExam.cs
|
Assets/Scripts/HarryPotterUnity/Cards/Transfiguration/Spells/TransfigurationExam.cs
|
using System.Collections.Generic;
using System.Linq;
using HarryPotterUnity.Cards.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Transfiguration.Spells
{
[UsedImplicitly]
public class TransfigurationExam : GenericSpell
{
protected override bool MeetsAdditionalPlayRequirements()
{
return Player.InPlay.GetCreaturesInPlay()
.Concat(Player.OppositePlayer.InPlay.GetCreaturesInPlay())
.Any();
}
protected override void SpellAction(List<GenericCard> targets)
{
var playerCreatures = Player.InPlay.GetCreaturesInPlay();
var enemyCreatures = Player.OppositePlayer.InPlay.GetCreaturesInPlay();
Player.OppositePlayer.Discard.AddAll(enemyCreatures);
Player.Discard.AddAll(playerCreatures);
Player.OppositePlayer.InPlay.RemoveAll(enemyCreatures);
Player.InPlay.RemoveAll(playerCreatures);
}
}
}
|
using System.Collections.Generic;
using HarryPotterUnity.Cards.Generic;
using JetBrains.Annotations;
namespace HarryPotterUnity.Cards.Transfiguration.Spells
{
[UsedImplicitly]
public class TransfigurationExam : GenericSpell
{
protected override void SpellAction(List<GenericCard> targets)
{
var playerCreatures = Player.InPlay.GetCreaturesInPlay();
var enemyCreatures = Player.OppositePlayer.InPlay.GetCreaturesInPlay();
Player.OppositePlayer.Discard.AddAll(enemyCreatures);
Player.Discard.AddAll(playerCreatures);
Player.OppositePlayer.InPlay.RemoveAll(enemyCreatures);
Player.InPlay.RemoveAll(playerCreatures);
}
}
}
|
mit
|
C#
|
b48ba0d35438effb6ddb3018a81fdb6aa62f3862
|
Add dummy text and fullscreen background image
|
tuelsch/schreinerei-gfeller,tuelsch/schreinerei-gfeller,tuelsch/schreinerei-gfeller
|
schreinerei-gfeller/Views/Home/Index.cshtml
|
schreinerei-gfeller/Views/Home/Index.cshtml
|
@{
ViewBag.Title = "Willkommen";
}
@section background {
<div class="background-size-cover fixed hidden-xs fill" style="background-image: url(//placehold.it/1920x1080)"></div>
}
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum adipisci ipsum, voluptatum, tempore ipsam esse! Accusamus rerum perspiciatis minima doloremque dolorum, ipsam in magnam laudantium illo. Libero tempore, tenetur asperiores eum alias quae optio, praesentium perspiciatis veniam consectetur omnis officiis accusamus voluptas nemo, necessitatibus minus deserunt natus eius ut. Suscipit nihil adipisci est eos eveniet accusantium doloremque amet dignissimos ea vero cupiditate, harum repellendus sint quidem excepturi. Explicabo nisi numquam recusandae quisquam iste earum nihil in totam animi impedit mollitia, temporibus aliquid quae repellendus eaque corrupti dolor ipsum odio laudantium illo harum omnis sed debitis ratione vel. Quos, maxime amet? Nemo officia animi illo quos at et eum architecto praesentium itaque voluptates, commodi soluta aspernatur eveniet quod, culpa ipsa facere quas odio aliquam officiis eius, voluptatem tempore beatae! Similique fuga nulla dicta vel, provident. Quidem earum impedit quam, possimus, dicta laudantium voluptate officiis, culpa dolorem sequi corporis consequatur asperiores repellat odit labore. Accusamus earum molestias dicta porro, dolore beatae sequi nobis, cum. Porro impedit dicta obcaecati, quos reprehenderit quidem dolore quia sapiente eveniet dolorem non dolor. Esse beatae hic velit voluptatem doloremque debitis laborum provident ea repellendus expedita obcaecati asperiores sit pariatur facilis neque voluptatum sapiente, consectetur cumque a minima ut. Dolorem, repellendus, officiis. Esse culpa quasi ut tenetur maxime ea harum numquam commodi, quam possimus aliquid totam excepturi asperiores distinctio maiores optio, error, sapiente doloribus! Illum et ipsum a saepe quasi magnam dignissimos officia consectetur fugit maiores quia hic explicabo quam, numquam ut adipisci sapiente sequi, qui, accusamus recusandae consequatur. Debitis laudantium nulla voluptatem repellat ipsa quis ipsum sapiente laboriosam id! Quis, in vitae possimus incidunt rem cupiditate ad quam asperiores sit perferendis vero delectus temporibus non tempore! Vel quo, temporibus sunt quisquam explicabo facilis aspernatur eius quia consequatur sequi harum inventore ullam laborum, nam excepturi cupiditate nemo facere.</p>
</div>
|
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div>
|
mit
|
C#
|
9a2d69c8f0b6e2493853a660c494d5ef36db69c2
|
Update OMCode.cs
|
ADAPT/ADAPT
|
source/ADAPT/Documents/OMCode.cs
|
source/ADAPT/Documents/OMCode.cs
|
/*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
* 20190710 R. Andres Ferreyra: Added documentation
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class OMCode // Go-to way of expressing the meaning of an Obs (observation)
{
public OMCode()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; } // Each OmCode has its own CompoundIdentifier
public string Code { get; set; } // This is the key for key,value representations of an observation.
public string Description { get; set; } // Human-readable description of what the OMCode means.
public List<int> CodeComponentIds { get; set; } // These are the units of meaning stat specify aspects of the OMCode's
// meaning, such as feature of interest, observed property, observation method, aggregation method, etc.
public List<ContextItem> ContextItems { get; set; }
}
}
|
/*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class OMCode
{
public OMCode()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Code { get; set; }
public string Description { get; set; }
public List<int> CodeComponentIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
|
epl-1.0
|
C#
|
f5d5417e31b4ff5b1f7259ca0bc0fc8156b8d67b
|
fix Upgrade_20210828_ExtensionsLoveFramework
|
signumsoftware/framework,signumsoftware/framework
|
Signum.Upgrade/Upgrades/Upgrade_20210828_ExtensionsLoveFramework.cs
|
Signum.Upgrade/Upgrades/Upgrade_20210828_ExtensionsLoveFramework.cs
|
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Upgrade.Upgrades
{
class Upgrade_20210828_ExtensionsLoveFramework : CodeUpgradeBase
{
public override string Description => "Extensions ❤️ Framework";
public override void Execute(UpgradeContext uctx)
{
uctx.ForeachCodeFile(@"*.csproj", file =>
{
file.Replace(@"\Extensions\", @"\Framework\");
});
uctx.ForeachCodeFile(@"*.sln", file =>
{
file.Replace(@"""Extensions\", @"""Framework\");
});
uctx.ChangeCodeFile(@"Southwind.React\webpack.config.js", file =>
{
file.Replace(@"/Extensions/", @"/Framework/");
});
uctx.ChangeCodeFile(@"Southwind.React/tsconfig.json", file =>
{
file.Replace(@"/Extensions/", @"/Framework/");
});
uctx.ChangeCodeFile(@"Southwind.React/package.json", file =>
{
file.Replace(@"/Extensions/", @"/Framework/");
});
uctx.ChangeCodeFile(@".gitmodules", file =>
{
file.RemoveAllLines(a => a.Contains("extensions", StringComparison.InvariantCultureIgnoreCase));
});
if (SafeConsole.Ask("Do you want to delete 'Extensions' folder with all his content?"))
{
Directory.Delete(Path.Combine(uctx.RootFolder, "Extensions"), true);
Console.WriteLine("deleted");
}
}
}
}
|
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Upgrade.Upgrades
{
class Upgrade_20210828_ExtensionsLoveFramework : CodeUpgradeBase
{
public override string Description => "Extensions ❤️ Framework";
public override void Execute(UpgradeContext uctx)
{
uctx.ForeachCodeFile(@"*.csproj", file =>
{
file.Replace(@"\Extensions\", @"\Framework\");
});
uctx.ForeachCodeFile(@"*.sln", file =>
{
file.Replace(@"""Extensions\", @"""Framework\");
});
uctx.ChangeCodeFile(@"Southwind.React\webpack.config.js", file =>
{
file.Replace(@"\Extensions\", @"\Framework\");
});
uctx.ChangeCodeFile(@"Southwind.React/tsconfig.json", file =>
{
file.Replace(@"/Extensions/", @"/Framework/");
});
uctx.ChangeCodeFile(@"Southwind.React/package.json", file =>
{
file.Replace(@"/Extensions/", @"/Framework/");
});
uctx.ChangeCodeFile(@".gitmodules", file =>
{
file.RemoveAllLines(a => a.Contains("extensions", StringComparison.InvariantCultureIgnoreCase));
});
if (SafeConsole.Ask("Do you want to delete 'Extensions' folder with all his content?"))
{
Directory.Delete(Path.Combine(uctx.RootFolder, "Extensions"), true);
Console.WriteLine("deleted");
}
}
}
}
|
mit
|
C#
|
35a7226cd82120207014a652567a5e87febc25e2
|
Add newline
|
peppy/osu-new,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu
|
osu.Game/Screens/Play/HUD/HealthDisplay.cs
|
osu.Game/Screens/Play/HUD/HealthDisplay.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Screens.Play.HUD
{
/// <summary>
/// A container for components displaying the current player health.
/// Gets bound automatically to the <see cref="Rulesets.Scoring.HealthProcessor"/> when inserted to <see cref="DrawableRuleset.Overlays"/> hierarchy.
/// </summary>
public abstract class HealthDisplay : Container
{
[Resolved]
protected HealthProcessor HealthProcessor { get; private set; }
public Bindable<double> Current { get; } = new BindableDouble(1)
{
MinValue = 0,
MaxValue = 1
};
protected virtual void Flash(JudgementResult result)
{
}
[BackgroundDependencyLoader]
private void load()
{
Current.BindTo(HealthProcessor.Health);
HealthProcessor.NewJudgement += onNewJudgement;
}
private void onNewJudgement(JudgementResult judgement)
{
if (judgement.IsHit && judgement.Type != HitResult.IgnoreHit)
Flash(judgement);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (HealthProcessor != null)
HealthProcessor.NewJudgement -= onNewJudgement;
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Screens.Play.HUD
{
/// <summary>
/// A container for components displaying the current player health.
/// Gets bound automatically to the <see cref="Rulesets.Scoring.HealthProcessor"/> when inserted to <see cref="DrawableRuleset.Overlays"/> hierarchy.
/// </summary>
public abstract class HealthDisplay : Container
{
[Resolved]
protected HealthProcessor HealthProcessor { get; private set; }
public Bindable<double> Current { get; } = new BindableDouble(1)
{
MinValue = 0,
MaxValue = 1
};
protected virtual void Flash(JudgementResult result)
{
}
[BackgroundDependencyLoader]
private void load()
{
Current.BindTo(HealthProcessor.Health);
HealthProcessor.NewJudgement += onNewJudgement;
}
private void onNewJudgement(JudgementResult judgement)
{
if (judgement.IsHit && judgement.Type != HitResult.IgnoreHit) Flash(judgement);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (HealthProcessor != null)
HealthProcessor.NewJudgement -= onNewJudgement;
}
}
}
|
mit
|
C#
|
c64e57dcc85cef1be5e86b40a9bf78d1aaccc3ee
|
Bump version to 2.0.0-alpha01. Version for Cronus 2.0
|
Elders/Cronus.Transport.RabbitMQ,Elders/Cronus.Transport.RabbitMQ
|
src/Elders.Cronus.Transport.RabbitMQ/Properties/AssemblyInfo.cs
|
src/Elders.Cronus.Transport.RabbitMQ/Properties/AssemblyInfo.cs
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyTitleAttribute("Elders.Cronus.Transport.RabbitMQ")]
[assembly: AssemblyDescriptionAttribute("Elders.Cronus.Transport.RabbitMQ")]
[assembly: AssemblyProductAttribute("Elders.Cronus.Transport.RabbitMQ")]
[assembly: AssemblyVersionAttribute("2.0.0")]
[assembly: AssemblyInformationalVersionAttribute("2.0.0")]
[assembly: AssemblyFileVersionAttribute("2.0.0")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "2.0.0";
}
}
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyTitleAttribute("Elders.Cronus.Transport.RabbitMQ")]
[assembly: AssemblyDescriptionAttribute("Elders.Cronus.Transport.RabbitMQ")]
[assembly: AssemblyProductAttribute("Elders.Cronus.Transport.RabbitMQ")]
[assembly: AssemblyVersionAttribute("1.2.5")]
[assembly: AssemblyInformationalVersionAttribute("1.2.5")]
[assembly: AssemblyFileVersionAttribute("1.2.5")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.2.5";
}
}
|
apache-2.0
|
C#
|
cfa44f90a19b235114429af1cca4095b11f2812a
|
Update documentation for Append/Prepend
|
thomaslevesque/Linq.Extras
|
src/Linq.Extras/AppendPrepend.cs
|
src/Linq.Extras/AppendPrepend.cs
|
#if !FEATURE_APPEND_PREPEND
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Linq.Extras.Internal;
namespace Linq.Extras
{
partial class XEnumerable
{
/// <summary>
/// Appends the specified element to the specified sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <c>source</c>.</typeparam>
/// <param name="source">The sequence to append an element to.</param>
/// <param name="item">The element to append.</param>
/// <returns>The source sequence followed by the appended element.</returns>
/// <remarks>
/// Linq already has this method in .NET Core, .NET Framework 4.7.1 and higher, and .NET Standard 1.6 and higher,
/// so it's not included in Linq.Extras for these frameworks.
/// </remarks>
[Pure]
public static IEnumerable<TSource> Append<TSource>(
[NotNull] this IEnumerable<TSource> source,
TSource item)
{
source.CheckArgumentNull(nameof(source));
return source.Concat(new[] { item });
}
/// <summary>
/// Prepends the specified element to the specified sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <c>source</c>.</typeparam>
/// <param name="source">The sequence to prepend an element to.</param>
/// <param name="item">The element to prepend.</param>
/// <returns>The source sequence preceded by the prepended element.</returns>
/// <remarks>
/// Linq already has this method in .NET Core, .NET Framework 4.7.1 and higher, and .NET Standard 1.6 and higher,
/// so it's not included in Linq.Extras for these frameworks.
/// </remarks>
[Pure]
public static IEnumerable<TSource> Prepend<TSource>(
[NotNull] this IEnumerable<TSource> source,
TSource item)
{
source.CheckArgumentNull(nameof(source));
return new[] { item }.Concat(source);
}
}
}
#endif
|
#if !FEATURE_APPEND_PREPEND
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Linq.Extras.Internal;
namespace Linq.Extras
{
partial class XEnumerable
{
/// <summary>
/// Appends the specified element to the specified sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <c>source</c>.</typeparam>
/// <param name="source">The sequence to append an element to.</param>
/// <param name="item">The element to append.</param>
/// <returns>The source sequence followed by the appended element.</returns>
[Pure]
public static IEnumerable<TSource> Append<TSource>(
[NotNull] this IEnumerable<TSource> source,
TSource item)
{
source.CheckArgumentNull(nameof(source));
return source.Concat(new[] { item });
}
/// <summary>
/// Prepends the specified element to the specified sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <c>source</c>.</typeparam>
/// <param name="source">The sequence to prepend an element to.</param>
/// <param name="item">The element to prepend.</param>
/// <returns>The source sequence preceded by the prepended element.</returns>
[Pure]
public static IEnumerable<TSource> Prepend<TSource>(
[NotNull] this IEnumerable<TSource> source,
TSource item)
{
source.CheckArgumentNull(nameof(source));
return new[] { item }.Concat(source);
}
}
}
#endif
|
apache-2.0
|
C#
|
7a7b893c227cffe421e6ca8e57c841fe91edf2f0
|
add lock statement in CurrentManager property.
|
xoofx/NuGet,pratikkagda/nuget,alluran/node.net,jmezach/NuGet2,mono/nuget,mrward/NuGet.V2,mrward/nuget,ctaggart/nuget,jholovacs/NuGet,RichiCoder1/nuget-chocolatey,OneGet/nuget,alluran/node.net,chocolatey/nuget-chocolatey,jholovacs/NuGet,xoofx/NuGet,antiufo/NuGet2,antiufo/NuGet2,oliver-feng/nuget,oliver-feng/nuget,OneGet/nuget,GearedToWar/NuGet2,oliver-feng/nuget,jholovacs/NuGet,RichiCoder1/nuget-chocolatey,rikoe/nuget,zskullz/nuget,chocolatey/nuget-chocolatey,chocolatey/nuget-chocolatey,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,ctaggart/nuget,mrward/NuGet.V2,mono/nuget,dolkensp/node.net,zskullz/nuget,pratikkagda/nuget,alluran/node.net,GearedToWar/NuGet2,mono/nuget,alluran/node.net,ctaggart/nuget,jholovacs/NuGet,zskullz/nuget,indsoft/NuGet2,jholovacs/NuGet,dolkensp/node.net,rikoe/nuget,jmezach/NuGet2,mrward/NuGet.V2,dolkensp/node.net,xoofx/NuGet,mrward/NuGet.V2,xoofx/NuGet,antiufo/NuGet2,mrward/NuGet.V2,indsoft/NuGet2,pratikkagda/nuget,GearedToWar/NuGet2,pratikkagda/nuget,mrward/nuget,rikoe/nuget,GearedToWar/NuGet2,dolkensp/node.net,indsoft/NuGet2,jmezach/NuGet2,OneGet/nuget,mrward/NuGet.V2,indsoft/NuGet2,jmezach/NuGet2,xoofx/NuGet,mrward/nuget,RichiCoder1/nuget-chocolatey,oliver-feng/nuget,jmezach/NuGet2,mrward/nuget,indsoft/NuGet2,akrisiun/NuGet,chocolatey/nuget-chocolatey,pratikkagda/nuget,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,rikoe/nuget,antiufo/NuGet2,akrisiun/NuGet,ctaggart/nuget,oliver-feng/nuget,GearedToWar/NuGet2,xoofx/NuGet,antiufo/NuGet2,GearedToWar/NuGet2,oliver-feng/nuget,zskullz/nuget,mrward/nuget,mrward/nuget,antiufo/NuGet2,jholovacs/NuGet,chocolatey/nuget-chocolatey,OneGet/nuget,jmezach/NuGet2,mono/nuget,RichiCoder1/nuget-chocolatey
|
src/Core/Http/SendingRequestEventManager.cs
|
src/Core/Http/SendingRequestEventManager.cs
|
using System;
using System.Threading;
using System.Windows;
namespace NuGet
{
// Implement weak event pattern. Read more here:
// http://msdn.microsoft.com/en-us/library/aa970850(v=vs.100).aspx
public class SendingRequestEventManager : WeakEventManager
{
private static readonly object _managerLock = new object();
public static void AddListener(IHttpClientEvents source, IWeakEventListener listener)
{
SendingRequestEventManager.CurrentManager.ProtectedAddListener(source, listener);
}
public static void RemoveListener(IHttpClientEvents source, IWeakEventListener listener)
{
SendingRequestEventManager.CurrentManager.ProtectedRemoveListener(source, listener);
}
private static SendingRequestEventManager CurrentManager
{
get
{
Type managerType = typeof(SendingRequestEventManager);
lock (_managerLock)
{
SendingRequestEventManager manager = (SendingRequestEventManager)WeakEventManager.GetCurrentManager(managerType);
if (manager == null)
{
manager = new SendingRequestEventManager();
WeakEventManager.SetCurrentManager(managerType, manager);
}
return manager;
}
}
}
protected override void StartListening(object source)
{
var clientEvents = (IHttpClientEvents)source;
clientEvents.SendingRequest += OnSendingRequest;
}
protected override void StopListening(object source)
{
var clientEvents = (IHttpClientEvents)source;
clientEvents.SendingRequest -= OnSendingRequest;
}
private void OnSendingRequest(object sender, WebRequestEventArgs e)
{
base.DeliverEvent(sender, e);
}
}
}
|
using System;
using System.Windows;
namespace NuGet
{
// Implement weak event pattern. Read more here:
// http://msdn.microsoft.com/en-us/library/aa970850(v=vs.100).aspx
public class SendingRequestEventManager : WeakEventManager
{
public static void AddListener(IHttpClientEvents source, IWeakEventListener listener)
{
SendingRequestEventManager.CurrentManager.ProtectedAddListener(source, listener);
}
public static void RemoveListener(IHttpClientEvents source, IWeakEventListener listener)
{
SendingRequestEventManager.CurrentManager.ProtectedRemoveListener(source, listener);
}
private static SendingRequestEventManager CurrentManager
{
get
{
Type managerType = typeof(SendingRequestEventManager);
SendingRequestEventManager manager = (SendingRequestEventManager)WeakEventManager.GetCurrentManager(managerType);
if (manager == null)
{
manager = new SendingRequestEventManager();
WeakEventManager.SetCurrentManager(managerType, manager);
}
return manager;
}
}
protected override void StartListening(object source)
{
var clientEvents = (IHttpClientEvents)source;
clientEvents.SendingRequest += OnSendingRequest;
}
protected override void StopListening(object source)
{
var clientEvents = (IHttpClientEvents)source;
clientEvents.SendingRequest -= OnSendingRequest;
}
private void OnSendingRequest(object sender, WebRequestEventArgs e)
{
base.DeliverEvent(sender, e);
}
}
}
|
apache-2.0
|
C#
|
9987f6675221c1a3e773277a7a85fc23cfc8ffb8
|
Update designer.cs
|
michael-jia-sage/google-apis,xamarin/google-apis
|
samples/GoogleApis.Android.Sample/Resources/Resource.Designer.cs
|
samples/GoogleApis.Android.Sample/Resources/Resource.Designer.cs
|
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: Android.Runtime.ResourceDesignerAttribute("Google.Apis.Android.Sample.Resource", IsApplication=true)]
namespace Google.Apis.Android.Sample
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues ();
}
public static void UpdateIdValues()
{
}
public partial class Attribute
{
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int Icon = 2130837504;
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f050002
public const int ListItem = 2131034114;
// aapt resource value: 0x7f050000
public const int MyButton = 2131034112;
// aapt resource value: 0x7f050001
public const int Name = 2131034113;
private Id()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
// aapt resource value: 0x7f030001
public const int NameDialog = 2130903041;
// aapt resource value: 0x7f030002
public const int TaskItem = 2130903042;
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040001
public const int ApplicationName = 2130968577;
// aapt resource value: 0x7f040000
public const int Hello = 2130968576;
private String()
{
}
}
}
}
#pragma warning restore 1591
|
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18010
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: Android.Runtime.ResourceDesignerAttribute("Google.Apis.Android.Sample.Resource", IsApplication=true)]
namespace Google.Apis.Android.Sample
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Novell.MonoDroid.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
public static void UpdateIdValues()
{
}
public partial class Attribute
{
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int Icon = 2130837504;
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f050002
public const int ListItem = 2131034114;
// aapt resource value: 0x7f050000
public const int MyButton = 2131034112;
// aapt resource value: 0x7f050001
public const int Name = 2131034113;
private Id()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
// aapt resource value: 0x7f030001
public const int NameDialog = 2130903041;
// aapt resource value: 0x7f030002
public const int TaskItem = 2130903042;
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040001
public const int ApplicationName = 2130968577;
// aapt resource value: 0x7f040000
public const int Hello = 2130968576;
private String()
{
}
}
}
}
#pragma warning restore 1591
|
apache-2.0
|
C#
|
b68c48e2653c51862231d079d8ecbb7706ba83d5
|
Rollback previous changes
|
ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks
|
src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs
|
src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs
|
using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location;
var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value;
return value.ToFingerPrintMd5Hash();
}
}
}
|
using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
return ComputerId.Value.ToFingerPrintMd5Hash();
}
}
}
|
apache-2.0
|
C#
|
0c940aa0f971ac3fe3465e3f34158f24bc2a25ff
|
Call Configure() dumb ass!
|
phatboyg/Stact,phatboyg/Stact,phatboyg/Stact,phatboyg/Stact
|
src/Magnum.Infrastructure/Repository/NHibernateRepositoryFactory.cs
|
src/Magnum.Infrastructure/Repository/NHibernateRepositoryFactory.cs
|
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Magnum.Infrastructure.Repository
{
using System;
using Common.Repository;
using NHibernate;
using NHibernate.Cfg;
public class NHibernateRepositoryFactory : IRepositoryFactory
{
private readonly ISessionFactory _sessionFactory;
public NHibernateRepositoryFactory(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
public void Dispose()
{
_sessionFactory.Dispose();
}
public IRepository GetRepository()
{
return new NHibernateRepository(_sessionFactory);
}
public IRepository<T, Guid> GetRepository<T>() where T : class, IAggregateRoot
{
return new NHibernateRepository<T, Guid>(_sessionFactory);
}
public IRepository<T, K> GetRepository<T, K>() where T : class, IAggregateRoot<K>
{
return new NHibernateRepository<T, K>(_sessionFactory);
}
public static IRepositoryFactory Build()
{
Configuration configuration = new Configuration().Configure();
configuration.AddAssembly(typeof (NHibernateRepositoryFactory).Assembly);
return new NHibernateRepositoryFactory(configuration.BuildSessionFactory());
}
}
}
|
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Magnum.Infrastructure.Repository
{
using System;
using Common.Repository;
using NHibernate;
using NHibernate.Cfg;
public class NHibernateRepositoryFactory : IRepositoryFactory
{
private readonly ISessionFactory _sessionFactory;
public NHibernateRepositoryFactory(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
public void Dispose()
{
_sessionFactory.Dispose();
}
public IRepository GetRepository()
{
return new NHibernateRepository(_sessionFactory);
}
public IRepository<T, Guid> GetRepository<T>() where T : class, IAggregateRoot
{
return new NHibernateRepository<T, Guid>(_sessionFactory);
}
public IRepository<T, K> GetRepository<T, K>() where T : class, IAggregateRoot<K>
{
return new NHibernateRepository<T, K>(_sessionFactory);
}
public static IRepositoryFactory Build()
{
Configuration configuration = new Configuration();
configuration.AddAssembly(typeof (NHibernateRepositoryFactory).Assembly);
return new NHibernateRepositoryFactory(configuration.BuildSessionFactory());
}
}
}
|
apache-2.0
|
C#
|
44392270f649e35d7ef2b7291619317229569379
|
Delete unused experiment names added in merge.
|
diryboy/roslyn,jasonmalinowski/roslyn,agocke/roslyn,sharwell/roslyn,KevinRansom/roslyn,davkean/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,physhi/roslyn,physhi/roslyn,abock/roslyn,dotnet/roslyn,stephentoub/roslyn,agocke/roslyn,tannergooding/roslyn,aelij/roslyn,AmadeusW/roslyn,gafter/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,jmarolf/roslyn,tmat/roslyn,physhi/roslyn,agocke/roslyn,AmadeusW/roslyn,gafter/roslyn,AlekseyTs/roslyn,diryboy/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,dotnet/roslyn,reaction1989/roslyn,genlu/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,abock/roslyn,weltkante/roslyn,weltkante/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,sharwell/roslyn,stephentoub/roslyn,gafter/roslyn,abock/roslyn,wvdd007/roslyn,davkean/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,eriawan/roslyn,mavasani/roslyn,KevinRansom/roslyn,jmarolf/roslyn,aelij/roslyn,genlu/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,mavasani/roslyn,heejaechang/roslyn,tannergooding/roslyn,aelij/roslyn,reaction1989/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,weltkante/roslyn,genlu/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,jmarolf/roslyn,tmat/roslyn,davkean/roslyn,tmat/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,brettfo/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn
|
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
|
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string RoslynToggleBlockComment = "Roslyn.ToggleBlockComment";
public const string RoslynToggleLineComment = "Roslyn.ToggleLineComment";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
}
}
|
mit
|
C#
|
17486826bb10409e1d49bcbf5f8e7029e3540cf8
|
add kris to AssemblyInfo
|
thyxkris1/test
|
src/MyWindowsService/MyWindowsService/Properties/AssemblyInfo.cs
|
src/MyWindowsService/MyWindowsService/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("MyWindowsServicekris")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MyWindowsService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9467f6b1-a815-48db-9215-24e08ab359d4")]
// 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.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("MyWindowsService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MyWindowsService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9467f6b1-a815-48db-9215-24e08ab359d4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
fd734af3f11b3e4b46bb9460ffaba62d2ea71f4d
|
update wrong namespace name
|
wikibus/Argolis
|
src/Lernaean.Hydra.Tests.Integration/Properties/AssemblyInfo.cs
|
src/Lernaean.Hydra.Tests.Integration/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("Lernaean.Hydra.Tests.Integration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lernaean.Hydra.Tests.Integration")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("41f8c2f5-8b83-430b-9afe-21dcfd84af54")]
// 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.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("Lernean.Hydra.Tests.Integration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lernean.Hydra.Tests.Integration")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("41f8c2f5-8b83-430b-9afe-21dcfd84af54")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
613d329a9118625071703de8ec3988c261bc060f
|
Add temp platform define for shaderlab injects
|
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
|
resharper/resharper-unity/src/HlslSupport/ShaderLabInclusionContextProvider.cs
|
resharper/resharper-unity/src/HlslSupport/ShaderLabInclusionContextProvider.cs
|
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Properties.VCXProj;
using JetBrains.ReSharper.Feature.Services.Cpp.Injections;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Cpp.Caches;
using JetBrains.ReSharper.Psi.Cpp.Language;
using JetBrains.ReSharper.Psi.Cpp.Parsing.Preprocessor;
using JetBrains.ReSharper.Psi.Cpp.Symbols;
using JetBrains.ReSharper.Psi.Cpp.Util;
namespace JetBrains.ReSharper.Plugins.Unity.HlslSupport
{
[Language(typeof(ShaderLabLanguage))]
public class ShaderLabInclusionContextProvider : IInclusionContextProvider
{
public CppInclusionContextResult CreateInclusionContextResult(CppGlobalSymbolCache cache,
CppFileLocation rootFile,
FileProcessingOptions options, long cacheVersion, Lifetime lifetime)
{
var locationTracker = cache.Solution.GetComponent<ShaderLabCppFileLocationTracker>();
if (!locationTracker.IsValid(rootFile))
{
return CppInclusionContextResult.Fail(CppInclusionContextResult.Status.UNSUITABLE_PROJECT_FILE);
}
var properties = new CppCompilationProperties()
{
LanguageKind = CppLanguageKind.HLSL, ClrSupport = VCXCompileAsManagedOptions.ManagedNotSet,
};
properties.PredefinedMacros.Add(CppPPDefineSymbol.ParsePredefinedMacro("SHADER_API_D3D11"));
var cgIncludeFolder =
CgIncludeDirectoryTracker.GetCgIncludeFolderPath(cache.Solution.GetComponent<UnityVersion>());
if (!cgIncludeFolder.IsEmpty)
{
properties.IncludePaths.Add(cgIncludeFolder);
properties.IncludePaths.Add(cache.Solution.SolutionDirectory);
properties.IncludePaths.Add(cache.Solution.SolutionDirectory.Combine("Library"));
}
var shaderCache = cache.Solution.GetComponent<ShaderLabCppFileLocationTracker>();
// TODO 1) is cache ready? what will happen under document transaction? check for bad moment?
// TODO 2) what will happen under psi transaction? include in cache could be out-of date. Try use include quickfix when cginclude is after cgprogram where QF is used
var includeLocation = shaderCache.GetIncludes(rootFile);
return InjectInclusionContextProviderUtil.CreateInclusionContextResult(cache, rootFile,
includeLocation, options, properties, null, cacheVersion, lifetime);
}
}
}
|
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Properties.VCXProj;
using JetBrains.ReSharper.Feature.Services.Cpp.Injections;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Cpp.Caches;
using JetBrains.ReSharper.Psi.Cpp.Language;
using JetBrains.ReSharper.Psi.Cpp.Parsing.Preprocessor;
using JetBrains.ReSharper.Psi.Cpp.Util;
namespace JetBrains.ReSharper.Plugins.Unity.HlslSupport
{
[Language(typeof(ShaderLabLanguage))]
public class ShaderLabInclusionContextProvider : IInclusionContextProvider
{
public CppInclusionContextResult CreateInclusionContextResult(CppGlobalSymbolCache cache,
CppFileLocation rootFile,
FileProcessingOptions options, long cacheVersion, Lifetime lifetime)
{
var locationTracker = cache.Solution.GetComponent<ShaderLabCppFileLocationTracker>();
if (!locationTracker.IsValid(rootFile))
{
return CppInclusionContextResult.Fail(CppInclusionContextResult.Status.UNSUITABLE_PROJECT_FILE);
}
var properties = new CppCompilationProperties()
{
LanguageKind = CppLanguageKind.HLSL, ClrSupport = VCXCompileAsManagedOptions.ManagedNotSet,
};
var cgIncludeFolder =
CgIncludeDirectoryTracker.GetCgIncludeFolderPath(cache.Solution.GetComponent<UnityVersion>());
if (!cgIncludeFolder.IsEmpty)
{
properties.IncludePaths.Add(cgIncludeFolder);
properties.IncludePaths.Add(cache.Solution.SolutionDirectory);
properties.IncludePaths.Add(cache.Solution.SolutionDirectory.Combine("Library"));
}
var shaderCache = cache.Solution.GetComponent<ShaderLabCppFileLocationTracker>();
// TODO 1) is cache ready? what will happen under document transaction? check for bad moment?
// TODO 2) what will happen under psi transaction? include in cache could be out-of date. Try use include quickfix when cginclude is after cgprogram where QF is used
var includeLocation = shaderCache.GetIncludes(rootFile);
return InjectInclusionContextProviderUtil.CreateInclusionContextResult(cache, rootFile,
includeLocation, options, properties, null, cacheVersion, lifetime);
}
}
}
|
apache-2.0
|
C#
|
a86624d3869d5e55b2886c8a5dd80e07a36bd3f2
|
change to non-static entrypoint, which klr is looking for
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
samples/RoutingSample/Program.cs
|
samples/RoutingSample/Program.cs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Owin.Hosting;
namespace RoutingSample
{
public class Program
{
public static void Main(string[] args)
{
string url = "http://localhost:30000/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("Listening on {0}", url);
Console.WriteLine("Press ENTER to quit");
Console.ReadLine();
}
}
}
}
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Owin.Hosting;
namespace RoutingSample
{
internal static class Program
{
public static void Main(string[] args)
{
string url = "http://localhost:30000/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("Listening on {0}", url);
Console.WriteLine("Press ENTER to quit");
Console.ReadLine();
}
}
}
}
|
apache-2.0
|
C#
|
98111ca490aafd94ce98635d418861a583e833ad
|
Fix to Compare Resource in Lowercase
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerAccounts.Web/Authorization/DefaultAuthorizationHandler.cs
|
src/SFA.DAS.EmployerAccounts.Web/Authorization/DefaultAuthorizationHandler.cs
|
using SFA.DAS.Authorization.Context;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using SFA.DAS.Authorization.Results;
using System.Collections.Generic;
using SFA.DAS.Authorization.Handlers;
using static SFA.DAS.EmployerAccounts.Web.Authorization.ImpersonationAuthorizationContext;
namespace SFA.DAS.EmployerAccounts.Web.Authorization
{
public class DefaultAuthorizationHandler : IDefaultAuthorizationHandler
{
public Task<AuthorizationResult> GetAuthorizationResult(IReadOnlyCollection<string> options, IAuthorizationContext authorizationContext)
{
var authorizationResult = new AuthorizationResult();
authorizationContext.TryGet<Resource>("Resource", out var resource);
authorizationContext.TryGet<ClaimsIdentity>("ClaimsIdentity", out var claimsIdentity);
var resourceValue = resource != null ? resource.Value : "default";
var userRoleClaims = claimsIdentity?.Claims.Where(c => c.Type == claimsIdentity?.RoleClaimType);
if (userRoleClaims == null || userRoleClaims.All(claim => claim.Value != AuthorizationConstants.Tier2User))
return Task.FromResult(authorizationResult);
if (!CheckAllowedResourceList(resourceValue)) {
authorizationResult.AddError(new Tier2UserAccesNotGranted());
}
return Task.FromResult(authorizationResult);
}
public bool CheckAllowedResourceList(string resourceValue)
{
var resourceList = ResourceList.GetListOfAllowedResources();
return resourceList.Any(res => res.ToLower().ToString() == resourceValue.ToLower());
}
}
public static class ResourceList
{
public static IList<string> GetListOfAllowedResources()
{
var resourceList = new List<string> { AuthorizationConstants.TeamViewRoute, AuthorizationConstants.TeamInvite, AuthorizationConstants.TeamReview };
return resourceList;
}
}
}
|
using SFA.DAS.Authorization.Context;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using SFA.DAS.Authorization.Results;
using System.Collections.Generic;
using SFA.DAS.Authorization.Handlers;
using static SFA.DAS.EmployerAccounts.Web.Authorization.ImpersonationAuthorizationContext;
namespace SFA.DAS.EmployerAccounts.Web.Authorization
{
public class DefaultAuthorizationHandler : IDefaultAuthorizationHandler
{
public Task<AuthorizationResult> GetAuthorizationResult(IReadOnlyCollection<string> options, IAuthorizationContext authorizationContext)
{
var authorizationResult = new AuthorizationResult();
authorizationContext.TryGet<Resource>("Resource", out var resource);
authorizationContext.TryGet<ClaimsIdentity>("ClaimsIdentity", out var claimsIdentity);
var resourceValue = resource != null ? resource.Value : "default";
var userRoleClaims = claimsIdentity?.Claims.Where(c => c.Type == claimsIdentity?.RoleClaimType);
if (userRoleClaims == null || userRoleClaims.All(claim => claim.Value != AuthorizationConstants.Tier2User))
return Task.FromResult(authorizationResult);
if (!CheckAllowedResourceList(resourceValue)) {
authorizationResult.AddError(new Tier2UserAccesNotGranted());
}
return Task.FromResult(authorizationResult);
}
public bool CheckAllowedResourceList(string resourceValue)
{
var resourceList = ResourceList.GetListOfAllowedResources();
return resourceList.Any(res => res == resourceValue);
}
}
public static class ResourceList
{
public static IList<string> GetListOfAllowedResources()
{
var resourceList = new List<string> { AuthorizationConstants.TeamViewRoute, AuthorizationConstants.TeamInvite, AuthorizationConstants.TeamReview };
return resourceList;
}
}
}
|
mit
|
C#
|
352c5f8eb4c656b765f8a99aaa40861da8c2a210
|
clean up SampleApp
|
eeaquino/DotNetShipping,kylewest/DotNetShipping
|
SampleApp/Program.cs
|
SampleApp/Program.cs
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using DotNetShipping.ShippingProviders;
namespace DotNetShipping.SampleApp
{
internal class Program
{
#region Methods
private static void Main()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// You will need a license #, userid and password to utilize the UPS provider.
string upsLicenseNumber = appSettings["UPSLicenseNumber"];
string upsUserId = appSettings["UPSUserId"];
string upsPassword = appSettings["UPSPassword"];
// You will need an account # and meter # to utilize the FedEx provider.
string fedexKey = appSettings["FedExKey"];
string fedexPassword = appSettings["FedExPassword"];
string fedexAccountNumber = appSettings["FedExAccountNumber"];
string fedexMeterNumber = appSettings["FedExMeterNumber"];
// TODO: USPSProvider
// You will need a userId and password to use the USPS provider. Your account will also need access to the production servers.
//string uspsUserId = appSettings["USPSUserId"];
//string uspsPassword = appSettings["USPSPassword"];
// Setup package and destination/origin addresses
var packages = new List<Package>();
packages.Add(new Package(12, 12, 12, 35, 150));
packages.Add(new Package(4, 4, 6, 15, 250));
var origin = new Address("", "", "06405", "US");
var destination = new Address("", "", "20852", "US"); // US Address
//var destination = new Address("", "", "L4W 1S2", "CA"); // Canada Address
//var destination = new Address("", "", "BA11HX", "GB"); // European Address
// Create RateManager
var rateManager = new RateManager();
// Add desired DotNetShippingProviders
rateManager.AddProvider(new UPSProvider(upsLicenseNumber, upsUserId, upsPassword));
rateManager.AddProvider(new FedExProvider(fedexKey, fedexPassword, fedexAccountNumber, fedexMeterNumber));
// TODO: USPSProvider
//rateManager.AddProvider(new USPSProvider(uspsUserId, uspsPassword));
// (Optional) Add RateAdjusters
rateManager.AddRateAdjuster(new PercentageRateAdjuster(.9M));
// Call GetRates()
Shipment shipment = rateManager.GetRates(origin, destination, packages);
// Iterate through the rates returned
foreach (Rate rate in shipment.Rates)
{
Console.WriteLine(rate);
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using DotNetShipping.ShippingProviders;
namespace DotNetShipping.SampleApp
{
internal class Program
{
#region Methods
private static void Main(string[] args)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// You will need a license #, userid and password to utilize the UPS provider.
string upsLicenseNumber = appSettings["UPSLicenseNumber"];
string upsUserId = appSettings["UPSUserId"];
string upsPassword = appSettings["UPSPassword"];
// You will need an account # and meter # to utilize the FedEx provider.
string fedexKey = appSettings["FedExKey"];
string fedexPassword = appSettings["FedExPassword"];
string fedexAccountNumber = appSettings["FedExAccountNumber"];
string fedexMeterNumber = appSettings["FedExMeterNumber"];
// You will need a userId and password to use the USPS provider. Your account will also need access to the production servers.
string uspsUserId = appSettings["USPSUserId"];
string uspsPassword = appSettings["USPSPassword"];
// Setup package and destination/origin addresses
var packages = new List<Package>();
packages.Add(new Package(0, 0, 0, 35, 0));
packages.Add(new Package(0, 0, 0, 15, 0));
var origin = new Address("", "", "06405", "US");
var destination = new Address("", "", "20852", "US"); // US Address
//var destination = new Address("", "", "L4W 1S2", "CA"); // Canada Address
//var destination = new Address("Bath", "", "BA11HX", "GB"); // European Address
// Create RateManager
var rateManager = new RateManager();
// Add desired DotNetShippingProviders
rateManager.AddProvider(new UPSProvider(upsLicenseNumber, upsUserId, upsPassword));
rateManager.AddProvider(new FedExProvider(fedexKey, fedexPassword, fedexAccountNumber, fedexMeterNumber));
rateManager.AddProvider(new USPSProvider(uspsUserId, uspsPassword));
// (Optional) Add RateAdjusters
rateManager.AddRateAdjuster(new PercentageRateAdjuster(.9M));
// Call GetRates()
Shipment shipment = rateManager.GetRates(origin, destination, packages);
// Iterate through the rates returned
foreach (Rate rate in shipment.Rates)
{
Console.WriteLine(rate);
}
}
#endregion
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.