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 |
|---|---|---|---|---|---|---|---|---|
b2133a3b8644499da5c75c1009807155527753b9 | Update changelog. | MrJoy/UnityColorBlindness,MrJoy/UnityColorBlindness,MrJoy/UnityColorBlindness | Assets/UnityColorBlindness/ColorBlindnessEffect.cs | Assets/UnityColorBlindness/ColorBlindnessEffect.cs | /*
Red/Green Color-Blindness Simulation Effect
(C)Copyright 2008-2013, MrJoy Inc, All rights reserved.
Version: 1.0.1, 2013-03-01
Changes:
-2013-03-01, jfrisby: Fix deprecation.
-2008-04-28, jfrisby: Initial version.
Notes: This is intended to help you look for problems that may make it
difficult for users of your game to play if they suffer from red/green color
blindness. This is NOT based on a specific study of how red/green color
blindness behaves but is a coarse approximation and should be treated as
such.
Specifically, this may be useful in spotting major color issues but NOT
finding issues with it does not mean you have no color issues and this should
absolutely not be used for "fine tuning" the color palette of your game!
License: Feel free to use this code however you wish, but please give credit
where credit is due.
*/
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Color Blindness")]
public class ColorBlindnessEffect : ImageEffectBase {
// Called by camera to apply image effect
void OnRenderImage (RenderTexture source, RenderTexture destination) {
Graphics.Blit(source, destination, material);
}
}
| /*
Red/Green Color-Blindness Simulation Effect
(C)Copyright 2008, MrJoy Inc, All rights reserved.
Version: 1.0, 2008-04-28
Changes:
-2008-04-28, jfrisby: Initial version.
Notes: This is intended to help you look for problems that may make it
difficult for users of your game to play if they suffer from red/green color
blindness. This is NOT based on a specific study of how red/green color
blindness behaves but is a coarse approximation and should be treated as
such.
Specifically, this may be useful in spotting major color issues but NOT
finding issues with it does not mean you have no color issues and this should
absolutely not be used for "fine tuning" the color palette of your game!
License: Feel free to use this code however you wish, but please give credit
where credit is due.
*/
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Color Blindness")]
public class ColorBlindnessEffect : ImageEffectBase {
// Called by camera to apply image effect
void OnRenderImage (RenderTexture source, RenderTexture destination) {
Graphics.Blit(source, destination, material);
}
}
| mit | C# |
89f67a1417409b6a696cd1b92f5de15821b7fea7 | Fix building destruction patch | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | LmpClient/Harmony/DestructibleBuilding_OnCollisionEnter.cs | LmpClient/Harmony/DestructibleBuilding_OnCollisionEnter.cs | using Harmony;
using LmpClient.Systems.Lock;
using LmpClient.Systems.SettingsSys;
using LmpCommon.Enums;
using UnityEngine;
// ReSharper disable All
namespace LmpClient.Harmony
{
/// <summary>
/// This harmony patch is intended to skip the destruction of a building
/// if the vessel that crashes against it is controlled/updated by another player
/// </summary>
[HarmonyPatch(typeof(DestructibleBuilding))]
[HarmonyPatch("OnCollisionEnter")]
public class DestructibleBuilding_OnCollisionEnter
{
[HarmonyPrefix]
private static bool PrefixOnCollisionEnter(Collision c)
{
if (MainSystem.NetworkState < ClientState.Connected) return true;
var crashingVessel = c.gameObject.GetComponentUpwards<Part>()?.vessel;
if (crashingVessel != null)
{
if (crashingVessel.rootPart != null)
return !float.IsPositiveInfinity(crashingVessel.rootPart.crashTolerance);
if (!LockSystem.LockQuery.UpdateLockExists(crashingVessel.id)) return true;
return LockSystem.LockQuery.UpdateLockBelongsToPlayer(crashingVessel.id, SettingsSystem.CurrentSettings.PlayerName);
}
return true;
}
}
}
| using Harmony;
using LmpClient.Systems.Lock;
using LmpClient.Systems.SettingsSys;
using LmpCommon.Enums;
using UnityEngine;
// ReSharper disable All
namespace LmpClient.Harmony
{
/// <summary>
/// This harmony patch is intended to skip the destruction of a building
/// if the vessel that crashes against it is controlled/updated by another player
/// </summary>
[HarmonyPatch(typeof(DestructibleBuilding))]
[HarmonyPatch("OnCollisionEnter")]
public class DestructibleBuilding_OnCollisionEnter
{
[HarmonyPrefix]
private static bool PrefixOnCollisionEnter(Collision c)
{
if (MainSystem.NetworkState < ClientState.Connected) return true;
var crashingVessel = c.gameObject.GetComponentUpwards<Part>()?.vessel;
if (crashingVessel != null)
{
if (crashingVessel.rootPart != null)
return float.IsPositiveInfinity(crashingVessel.rootPart.crashTolerance);
if (!LockSystem.LockQuery.UpdateLockExists(crashingVessel.id)) return true;
return LockSystem.LockQuery.UpdateLockBelongsToPlayer(crashingVessel.id, SettingsSystem.CurrentSettings.PlayerName);
}
return true;
}
}
}
| mit | C# |
36be6f9a16363774af9584f14a938f6397374b74 | Clear sort and start when search changes (same as Web Forms). Cleaner to take data from StateContext instead of parameters because most can change within the method | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | NavigationSample/Controllers/PersonController.cs | NavigationSample/Controllers/PersonController.cs | using Navigation.Sample.Models;
using System;
using System.Web.Mvc;
namespace Navigation.Sample.Controllers
{
public class PersonController : Controller
{
public ActionResult Index(PersonSearchModel model)
{
DateTime outDate;
if (model.MinDateOfBirth == null || DateTime.TryParse(model.MinDateOfBirth, out outDate))
{
if (StateContext.Bag.name != model.Name || StateContext.Bag.minDateOfBirth != model.MinDateOfBirth)
{
StateContext.Bag.startRowIndex = null;
StateContext.Bag.sortExpression = null;
}
StateContext.Bag.name = model.Name;
StateContext.Bag.minDateOfBirth = model.MinDateOfBirth;
}
else
{
ModelState.AddModelError("MinDateOfBirth", "date error");
}
model.People = new PersonSearch().Search(StateContext.Bag.name, StateContext.Bag.minDateOfBirth,
StateContext.Bag.sortExpression, StateContext.Bag.startRowIndex, StateContext.Bag.maximumRows);
return View("Listing", model);
}
public ActionResult GetDetails(int id)
{
return View("Details", new PersonSearch().GetDetails(id));
}
}
} | using Navigation.Sample.Models;
using System;
using System.Web.Mvc;
namespace Navigation.Sample.Controllers
{
public class PersonController : Controller
{
public ActionResult Index(PersonSearchModel model, string sortExpression, int startRowIndex, int maximumRows)
{
DateTime outDate;
if (model.MinDateOfBirth == null || DateTime.TryParse(model.MinDateOfBirth, out outDate))
{
StateContext.Bag.name = model.Name;
StateContext.Bag.minDateOfBirth = model.MinDateOfBirth;
}
else
{
ModelState.AddModelError("MinDateOfBirth", "date error");
}
model.People = new PersonSearch().Search(StateContext.Bag.name, StateContext.Bag.minDateOfBirth,
sortExpression, startRowIndex, maximumRows);
return View("Listing", model);
}
public ActionResult GetDetails(int id)
{
return View("Details", new PersonSearch().GetDetails(id));
}
}
} | apache-2.0 | C# |
06afdd29dc84228a33ccb7a76655c69d5e3f0d9e | Rename lastElement to previousElement. | jholovacs/NuGet,mrward/NuGet.V2,chocolatey/nuget-chocolatey,dolkensp/node.net,chester89/nugetApi,oliver-feng/nuget,OneGet/nuget,alluran/node.net,ctaggart/nuget,GearedToWar/NuGet2,jholovacs/NuGet,GearedToWar/NuGet2,ctaggart/nuget,xoofx/NuGet,alluran/node.net,jmezach/NuGet2,indsoft/NuGet2,antiufo/NuGet2,GearedToWar/NuGet2,antiufo/NuGet2,rikoe/nuget,ctaggart/nuget,OneGet/nuget,rikoe/nuget,kumavis/NuGet,mrward/nuget,rikoe/nuget,mono/nuget,mrward/nuget,mrward/nuget,oliver-feng/nuget,themotleyfool/NuGet,mono/nuget,pratikkagda/nuget,jmezach/NuGet2,pratikkagda/nuget,kumavis/NuGet,jholovacs/NuGet,jmezach/NuGet2,oliver-feng/nuget,pratikkagda/nuget,GearedToWar/NuGet2,indsoft/NuGet2,mrward/NuGet.V2,chocolatey/nuget-chocolatey,zskullz/nuget,chocolatey/nuget-chocolatey,alluran/node.net,OneGet/nuget,themotleyfool/NuGet,RichiCoder1/nuget-chocolatey,anurse/NuGet,GearedToWar/NuGet2,atheken/nuget,antiufo/NuGet2,indsoft/NuGet2,jmezach/NuGet2,alluran/node.net,pratikkagda/nuget,indsoft/NuGet2,indsoft/NuGet2,zskullz/nuget,akrisiun/NuGet,atheken/nuget,oliver-feng/nuget,mrward/NuGet.V2,GearedToWar/NuGet2,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,dolkensp/node.net,zskullz/nuget,dolkensp/node.net,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,jholovacs/NuGet,zskullz/nuget,antiufo/NuGet2,xoofx/NuGet,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,ctaggart/nuget,oliver-feng/nuget,akrisiun/NuGet,xoofx/NuGet,jholovacs/NuGet,jmezach/NuGet2,mrward/nuget,mrward/NuGet.V2,mono/nuget,mrward/nuget,xero-github/Nuget,RichiCoder1/nuget-chocolatey,dolkensp/node.net,jholovacs/NuGet,mrward/NuGet.V2,xoofx/NuGet,xoofx/NuGet,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,mono/nuget,jmezach/NuGet2,antiufo/NuGet2,OneGet/nuget,mrward/nuget,chocolatey/nuget-chocolatey,oliver-feng/nuget,pratikkagda/nuget,indsoft/NuGet2,anurse/NuGet,themotleyfool/NuGet,antiufo/NuGet2,chester89/nugetApi,xoofx/NuGet,rikoe/nuget | NuPack.Dialog/Extensions/EnumerableExtensions.cs | NuPack.Dialog/Extensions/EnumerableExtensions.cs | using System.Collections.Generic;
namespace NuGet.Dialog.Extensions {
internal static class EnumerableExtensions {
/// <summary>
/// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurence
/// of each element instead of picking the first. This method assumes that similar items occur in order.
/// </summary>
internal static IEnumerable<TElement> DistinctLast<TElement>(this IEnumerable<TElement> source,
IEqualityComparer<TElement> comparer) {
bool first = true;
var previousElement = default(TElement);
foreach (TElement element in source) {
if (!first && !comparer.Equals(element, previousElement)) {
yield return previousElement;
}
previousElement = element;
first = false;
}
if (!first) {
yield return previousElement;
}
}
}
} | using System.Collections.Generic;
namespace NuGet.Dialog.Extensions {
internal static class EnumerableExtensions {
/// <summary>
/// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurence
/// of each element instead of picking the first. This method assumes that similar items occur in order.
/// </summary>
internal static IEnumerable<TElement> DistinctLast<TElement>(this IEnumerable<TElement> source,
IEqualityComparer<TElement> comparer) {
bool first = true;
var lastElement = default(TElement);
foreach (TElement element in source) {
if (!first && !comparer.Equals(element, lastElement)) {
yield return lastElement;
}
lastElement = element;
first = false;
}
if (!first) {
yield return lastElement;
}
}
}
} | apache-2.0 | C# |
ceeb39885114bc40d7de90485f6c42eed79d0ba1 | fix #234 | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Controls/Classes/ValkyrieLayout.xaml.cs | TCC.Core/Controls/Classes/ValkyrieLayout.xaml.cs | using System;
using System.Windows;
using System.Windows.Media.Animation;
using TCC.ViewModels;
namespace TCC.Controls.Classes
{
/// <summary>
/// Logica di interazione per ValkyrieLayout.xaml
/// </summary>
public partial class ValkyrieLayout
{
private ValkyrieLayoutVM _dc;
private DoubleAnimation _an;
private DoubleAnimation _rag;
public ValkyrieLayout()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
_dc = (ValkyrieLayoutVM)DataContext;
_an = new DoubleAnimation(_dc.StaminaTracker.Factor * 359.99 + 40, TimeSpan.FromMilliseconds(150));
_rag = new DoubleAnimation(318, 42, TimeSpan.FromMilliseconds(0));
_dc.StaminaTracker.PropertyChanged += ST_PropertyChanged;
_dc.Ragnarok.Buff.Started += OnRagnarokStarted;
}
private void OnRagnarokStarted(Data.CooldownMode obj)
{
_rag.Duration = TimeSpan.FromMilliseconds(_dc.Ragnarok.Buff.OriginalDuration);
RagArc.BeginAnimation(Arc.EndAngleProperty, _rag);
}
private void ST_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(_dc.StaminaTracker.Factor)) return;
if (!_dc.Ragnarok.Buff.IsAvailable) return;
var to = _dc.StaminaTracker.Factor * (359.99 - MainReArc.StartAngle * 2) + MainReArc.StartAngle;
_an.To = double.IsNaN(to) ? 0 : to;
MainReArc.BeginAnimation(Arc.EndAngleProperty, _an);
}
}
}
| using System;
using System.Windows;
using System.Windows.Media.Animation;
using TCC.ViewModels;
namespace TCC.Controls.Classes
{
/// <summary>
/// Logica di interazione per ValkyrieLayout.xaml
/// </summary>
public partial class ValkyrieLayout
{
private ValkyrieLayoutVM _dc;
private DoubleAnimation _an;
private DoubleAnimation _rag;
public ValkyrieLayout()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
_dc = (ValkyrieLayoutVM)DataContext;
_an = new DoubleAnimation(_dc.StaminaTracker.Factor * 359.99 + 40, TimeSpan.FromMilliseconds(150));
_rag = new DoubleAnimation(318, 42, TimeSpan.FromMilliseconds(0));
_dc.StaminaTracker.PropertyChanged += ST_PropertyChanged;
_dc.Ragnarok.Buff.Started += OnRagnarokStarted;
}
private void OnRagnarokStarted(Data.CooldownMode obj)
{
_rag.Duration = TimeSpan.FromMilliseconds(_dc.Ragnarok.Buff.OriginalDuration);
RagArc.BeginAnimation(Arc.EndAngleProperty, _rag);
}
private void ST_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(_dc.StaminaTracker.Factor)) return;
if (!_dc.Ragnarok.Buff.IsAvailable) return;
_an.To = _dc.StaminaTracker.Factor * (359.99 - MainReArc.StartAngle*2) + MainReArc.StartAngle;
MainReArc.BeginAnimation(Arc.EndAngleProperty, _an);
}
}
}
| mit | C# |
3e4d6d339360f8e9c71a8d7ad7304923da912580 | fix the find textbox | DebajyotiMondal/automatic-graph-layout,DebajyotiMondal/automatic-graph-layout,DebajyotiMondal/automatic-graph-layout,DebajyotiMondal/automatic-graph-layout | GraphLayout/Test/TestGraphmaps/AppWindow.xaml.cs | GraphLayout/Test/TestGraphmaps/AppWindow.xaml.cs | using System;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Msagl.GraphmapsWpfControl;
namespace TestGraphmaps
{
/// <summary>
/// Interaction logic for AppWindow.xaml
/// </summary>
public partial class AppWindow : Window
{
public AppWindow()
{
InitializeComponent();
}
internal GraphmapsViewer GraphViewer { get; set; }
public DockPanel GetMainDockPanel()
{
return dockPanel;
}
public DockPanel GetGraphViewerPanel()
{
return graphViewerPanel;
}
public TextBox GetStatusTextBox()
{
return statusTextBox;
}
//protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
//{
// if (e.Property.Name.Equals("ViewLayersMode"))
// {
// int x = 10;
// }
//}
//Find node operation on 'Enter'
void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.OemMinus)
{
_searchBox.Text = string.Concat(_searchBox.Text, "_");
_searchBox.CaretIndex = _searchBox.Text.Length;
}
if (e.Key == Key.Return) {
GraphViewer.FindNodeAndSelectIt(_searchBox.Text);
}
}
}
}
| using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Msagl.GraphmapsWpfControl;
namespace TestGraphmaps
{
/// <summary>
/// Interaction logic for AppWindow.xaml
/// </summary>
public partial class AppWindow : Window
{
public AppWindow()
{
InitializeComponent();
}
internal GraphmapsViewer GraphViewer { get; set; }
public DockPanel GetMainDockPanel()
{
return dockPanel;
}
public DockPanel GetGraphViewerPanel()
{
return graphViewerPanel;
}
public TextBox GetStatusTextBox()
{
return statusTextBox;
}
//protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
//{
// if (e.Property.Name.Equals("ViewLayersMode"))
// {
// int x = 10;
// }
//}
//Find node operation on 'Enter'
void OnKeyDownHandler(object sender, KeyEventArgs e) {
if (e.Key == Key.Return) {
GraphViewer.FindNodeAndSelectIt(_searchBox.Text);
}
}
}
}
| mit | C# |
647d8adb568935f38246403416673d2a67f36537 | Fix unit test by making the Data property writable | gabornemeth/restsharp.portable | RestSharp.Portable.Test/HttpBin/HttpBinResponse.cs | RestSharp.Portable.Test/HttpBin/HttpBinResponse.cs | using System.Collections.Generic;
namespace RestSharp.Portable.Test.HttpBin
{
public class HttpBinResponse
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Form { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Data { get; set; }
public object Json { get; set; }
}
}
| using System.Collections.Generic;
namespace RestSharp.Portable.Test.HttpBin
{
public class HttpBinResponse
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Form { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Data { get; }
public object Json { get; set; }
}
}
| bsd-2-clause | C# |
2b0e551b6bbe2d08f1930e3065dc3a77384d1079 | Add status | SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk | SnapMD.ConnectedCare.ApiModels/GlobalStatusCode.cs | SnapMD.ConnectedCare.ApiModels/GlobalStatusCode.cs | namespace SnapMD.ConnectedCare.ApiModels
{
/// <summary>
/// Requested by daniel.bouganim@snap.md
/// </summary>
public enum GlobalStatusCode
{
None,
Active,
Deleted,
Suspended,
Inactive
}
}
| namespace SnapMD.ConnectedCare.ApiModels
{
/// <summary>
/// Requested by daniel.bouganim@snap.md
/// </summary>
public enum GlobalStatusCode
{
None,
Active,
Deleted,
Suspended
}
}
| apache-2.0 | C# |
f49f386941f7e6a7be0bcc0ee26821647c04a319 | Update of Exception | LucidOcean/multichain,LucidOcean/multichain | LucidOcean.MultiChain/Properties/AssemblyInfo.cs | LucidOcean.MultiChain/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("LucidOcean.MultiChain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Lucid Ocean")]
[assembly: AssemblyProduct("Lucid Ocean MultiChain Client")]
[assembly: AssemblyCopyright("Copyright © 2017, Lucid Ocean PTY (Ltd)")]
[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("f7c35562-fdd5-4124-86df-b8be94cf816d")]
// 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: AssemblyFileVersion("0.0.0.3")]
[assembly: AssemblyInformationalVersion("0.0.0.3")]
[assembly: AssemblyVersion("0.0.0.3")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("LucidOcean.MultiChain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Lucid Ocean")]
[assembly: AssemblyProduct("Lucid Ocean MultiChain Client")]
[assembly: AssemblyCopyright("Copyright © 2017, Lucid Ocean PTY (Ltd)")]
[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("f7c35562-fdd5-4124-86df-b8be94cf816d")]
// 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: AssemblyFileVersion("0.0.0.2")]
[assembly: AssemblyInformationalVersion("0.0.0.2")]
[assembly: AssemblyVersion("0.0.0.2")]
| mit | C# |
ea2b4a6207f32f35ce28162260e36076787edd29 | Reset the version number | Hallmanac/AzureCloudTable,Hallmanac/AzureCloudTable | src/AzureCloudTable.Api/Properties/AssemblyInfo.cs | src/AzureCloudTable.Api/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("AzureCloudTableContext.Api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AzureCloudTableContext.Api")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f65115d4-9115-4494-bb83-feb24c09961c")]
// 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.*")]
[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("AzureCloudTableContext.Api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AzureCloudTableContext.Api")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f65115d4-9115-4494-bb83-feb24c09961c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
| mit | C# |
2803b873321991ee508bde8d0f9dd90dad5a210d | Test git commit | UCSD-HCI/ise,UCSD-HCI/ise,UCSD-HCI/ise,UCSD-HCI/ise | everspaces/everspaces/Main.cs | everspaces/everspaces/Main.cs | using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;
using System.Net;
using System.Net.Sockets;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
using Evernote.EDAM.Type;
using Evernote.EDAM.UserStore;
using Evernote.EDAM.NoteStore;
using Evernote.EDAM.Error;
using Evernote.EDAM.Limits;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace everspaces
{
class MainClass
{
public static List<string> ids = new List<string>();
public static slink l = null;
public static void Main (string[] args)
{
//test
everspaces e = new everspaces();
e.createLinkCompleted += new createLinkHandler(getCreateLinkResult);
e.getLinkCompleted += new getLinkHandler(getLinkResult);
metadata coord;
coord.x1 = 0;
coord.x2 = 5;
coord.y1 = 0;
coord.y2 = 5;
slink link = new slink(coord);
link.setTitle("My first link!");
link.setComment("This is the coolest!");
List<String> tags = new List<String>();
tags.Add("ryan");
link.setTags(tags);
//List<String> files = new List<String>();
//files.Add("qrcode.jpg");
//link.setResources(files);
Console.WriteLine("Waiting for link...");
Thread.Sleep(5000);
IAsyncResult result;
e.createLink(link);
while(ids.Count == 0){}
e.getLink(ids[0]);
while(l == null){}
metadata m = l.getMetadata();
Console.WriteLine(m.x1);
Console.WriteLine(m.y1);
Console.WriteLine(m.x2);
Console.WriteLine(m.y2);
Console.WriteLine(l.getComment());
Console.WriteLine(l.getAppType());
Console.WriteLine(l.getUri());
Console.WriteLine("Waiting to open...");
Thread.Sleep(5000);
result = e.openLink(l.getNoteGuid());
result.AsyncWaitHandle.WaitOne();
}
private static void getCreateLinkResult(string data)
{
ids.Add(data);
}
private static void getLinkResult(slink link)
{
l = link;
}
}
}
| using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;
using System.Net;
using System.Net.Sockets;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
using Evernote.EDAM.Type;
using Evernote.EDAM.UserStore;
using Evernote.EDAM.NoteStore;
using Evernote.EDAM.Error;
using Evernote.EDAM.Limits;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace everspaces
{
class MainClass
{
public static List<string> ids = new List<string>();
public static slink l = null;
public static void Main (string[] args)
{
everspaces e = new everspaces();
e.createLinkCompleted += new createLinkHandler(getCreateLinkResult);
e.getLinkCompleted += new getLinkHandler(getLinkResult);
metadata coord;
coord.x1 = 0;
coord.x2 = 5;
coord.y1 = 0;
coord.y2 = 5;
slink link = new slink(coord);
link.setTitle("My first link!");
link.setComment("This is the coolest!");
List<String> tags = new List<String>();
tags.Add("ryan");
link.setTags(tags);
//List<String> files = new List<String>();
//files.Add("qrcode.jpg");
//link.setResources(files);
Console.WriteLine("Waiting for link...");
Thread.Sleep(5000);
IAsyncResult result;
e.createLink(link);
while(ids.Count == 0){}
e.getLink(ids[0]);
while(l == null){}
metadata m = l.getMetadata();
Console.WriteLine(m.x1);
Console.WriteLine(m.y1);
Console.WriteLine(m.x2);
Console.WriteLine(m.y2);
Console.WriteLine(l.getComment());
Console.WriteLine(l.getAppType());
Console.WriteLine(l.getUri());
Console.WriteLine("Waiting to open...");
Thread.Sleep(5000);
result = e.openLink(l.getNoteGuid());
result.AsyncWaitHandle.WaitOne();
}
private static void getCreateLinkResult(string data)
{
ids.Add(data);
}
private static void getLinkResult(slink link)
{
l = link;
}
}
}
| apache-2.0 | C# |
fe21d184e90f8f02928a74e4224ce0be3f135b02 | add validLineCount in sourceinfo of token (#646) | hellosnow/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,928PJY/docfx,superyyrrzz/docfx,LordZoltan/docfx,dotnet/docfx,928PJY/docfx,dotnet/docfx,LordZoltan/docfx,928PJY/docfx,LordZoltan/docfx,superyyrrzz/docfx,DuncanmaMSFT/docfx,LordZoltan/docfx,pascalberger/docfx,dotnet/docfx,hellosnow/docfx,pascalberger/docfx,superyyrrzz/docfx,hellosnow/docfx | src/Microsoft.DocAsCode.MarkdownLite/SourceInfo.cs | src/Microsoft.DocAsCode.MarkdownLite/SourceInfo.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
public struct SourceInfo
{
private SourceInfo(string markdown, string file, int lineNumber, int validLineCount)
{
Markdown = markdown;
File = file;
LineNumber = lineNumber;
ValidLineCount = validLineCount;
}
public string Markdown { get; }
public string File { get; }
public int LineNumber { get; }
public int ValidLineCount { get; }
public static SourceInfo Create(string markdown, string file, int lineNumber = 1)
{
return new SourceInfo(markdown, file, lineNumber, GetValidLineCount(markdown));
}
public SourceInfo Copy(string markdown, int lineOffset = 0)
{
return new SourceInfo(markdown, File, LineNumber + lineOffset, GetValidLineCount(markdown));
}
private static int GetValidLineCount(string markdown)
{
var indexOfLastChar = markdown.Length - 1;
var validLineCount = 0;
while (indexOfLastChar >= 0 && markdown[indexOfLastChar] == '\n')
indexOfLastChar--;
for (var i = indexOfLastChar - 1; i >= 0; i--)
{
if (markdown[i] == '\n')
validLineCount++;
}
return validLineCount;
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
public struct SourceInfo
{
private SourceInfo(string markdown, string file, int lineNumber)
{
Markdown = markdown;
File = file;
LineNumber = lineNumber;
}
public string Markdown { get; }
public string File { get; }
public int LineNumber { get; }
public static SourceInfo Create(string markdown, string file, int lineNumber = 1)
{
return new SourceInfo(markdown, file, lineNumber);
}
public SourceInfo Copy(string markdown, int lineOffset = 0)
{
return new SourceInfo(markdown, File, LineNumber + lineOffset);
}
}
}
| mit | C# |
b63c26fc4a2ce96d1637934951945cd110895979 | remove explizit saving project settings | Citavi/C6-Add-Ons-and-Online-Sources | src/SortReferencesByParentChild/Core/ProjectExt.cs | src/SortReferencesByParentChild/Core/ProjectExt.cs | using SwissAcademic.ApplicationInsights;
using SwissAcademic.Citavi;
using System;
namespace SwissAcademic.Addons.SortReferencesByParentChildAddon
{
internal static class ProjectExt
{
public static void AddComparerStatus(this Project project)
{
try
{
project.ProjectSettings[Addon.SettingsKey] = "true";
}
catch (Exception ignored)
{
Telemetry.Warning(ignored, string.Empty, ignored.Message, null);
}
}
public static void RemoveComparerStatus(this Project project)
{
try
{
project.ProjectSettings[Addon.SettingsKey] = "false";
}
catch (Exception ignored)
{
Telemetry.Warning(ignored, string.Empty, ignored.Message, null);
}
}
public static bool RestoreComparer(this Project project)
{
try
{
return bool.Parse(project.ProjectSettings[Addon.SettingsKey].ToString());
}
catch (Exception ignored)
{
Telemetry.Warning(ignored, string.Empty, ignored.Message, null);
}
return false;
}
}
}
| using SwissAcademic.ApplicationInsights;
using SwissAcademic.Citavi;
using System;
namespace SwissAcademic.Addons.SortReferencesByParentChildAddon
{
internal static class ProjectExt
{
public static void AddComparerStatus(this Project project)
{
try
{
project.ProjectSettings[Addon.SettingsKey] = "true";
project.ProjectSettings.Save(true);
}
catch (Exception ignored)
{
Telemetry.Warning(ignored, string.Empty, ignored.Message, null);
}
}
public static void RemoveComparerStatus(this Project project)
{
try
{
project.ProjectSettings[Addon.SettingsKey] = "false";
project.ProjectSettings.Save(true);
}
catch (Exception ignored)
{
Telemetry.Warning(ignored, string.Empty, ignored.Message, null);
}
}
public static bool RestoreComparer(this Project project)
{
try
{
return bool.Parse(project.ProjectSettings[Addon.SettingsKey].ToString());
}
catch (Exception ignored)
{
Telemetry.Warning(ignored, string.Empty, ignored.Message, null);
}
return false;
}
}
}
| mit | C# |
6fdced25dc7a38f312ea28c50b6f19484a958bb9 | Drop in a note for later. | darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,SparkPost/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,ZA1/csharp-sparkpost | src/SparkPost/RequestSenders/AsyncRequestSender.cs | src/SparkPost/RequestSenders/AsyncRequestSender.cs | using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SparkPost.RequestSenders
{
public class AsyncRequestSender : IRequestSender
{
private readonly IClient client;
public AsyncRequestSender(IClient client)
{
this.client = client;
}
public async virtual Task<Response> Send(Request request)
{
using (var httpClient = client.CustomSettings.CreateANewHttpClient())
{
httpClient.BaseAddress = new Uri(client.ApiHost);
// I don't think this is the right spot for this
//httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey);
if (client.SubaccountId != 0)
{
httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture));
}
var result = await GetTheResponse(request, httpClient);
return new Response
{
StatusCode = result.StatusCode,
ReasonPhrase = result.ReasonPhrase,
Content = await result.Content.ReadAsStringAsync()
};
}
}
protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient)
{
return await new RequestMethodFinder(httpClient)
.FindFor(request)
.Execute(request);
}
}
} | using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SparkPost.RequestSenders
{
public class AsyncRequestSender : IRequestSender
{
private readonly IClient client;
public AsyncRequestSender(IClient client)
{
this.client = client;
}
public async virtual Task<Response> Send(Request request)
{
using (var httpClient = client.CustomSettings.CreateANewHttpClient())
{
httpClient.BaseAddress = new Uri(client.ApiHost);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey);
if (client.SubaccountId != 0)
{
httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture));
}
var result = await GetTheResponse(request, httpClient);
return new Response
{
StatusCode = result.StatusCode,
ReasonPhrase = result.ReasonPhrase,
Content = await result.Content.ReadAsStringAsync()
};
}
}
protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient)
{
return await new RequestMethodFinder(httpClient)
.FindFor(request)
.Execute(request);
}
}
} | apache-2.0 | C# |
2b8a105ec5cab7296966efab2cc87fcc2d01347e | Fix osu!direct test fail | smoogipoo/osu,johnneijzen/osu,peppy/osu-new,peppy/osu,smoogipooo/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,2yangk23/osu | osu.Game/Online/API/Requests/SearchBeatmapSetsRequest.cs | osu.Game/Online/API/Requests/SearchBeatmapSetsRequest.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.ComponentModel;
using osu.Game.Overlays;
using osu.Game.Overlays.Direct;
using osu.Game.Rulesets;
namespace osu.Game.Online.API.Requests
{
public class SearchBeatmapSetsRequest : APIRequest<SearchBeatmapSetsResponse>
{
private readonly string query;
private readonly RulesetInfo ruleset;
private readonly BeatmapSearchCategory searchCategory;
private readonly DirectSortCriteria sortCriteria;
private readonly SortDirection direction;
private string directionString => direction == SortDirection.Descending ? @"desc" : @"asc";
public SearchBeatmapSetsRequest(string query, RulesetInfo ruleset, BeatmapSearchCategory searchCategory = BeatmapSearchCategory.Any, DirectSortCriteria sortCriteria = DirectSortCriteria.Ranked, SortDirection direction = SortDirection.Descending)
{
this.query = string.IsNullOrEmpty(query) ? string.Empty : System.Uri.EscapeDataString(query);
this.ruleset = ruleset;
this.searchCategory = searchCategory;
this.sortCriteria = sortCriteria;
this.direction = direction;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
protected override string Target => $@"beatmapsets/search?q={query}&m={ruleset.ID ?? 0}&s={searchCategory.ToString().ToLowerInvariant()}&sort={sortCriteria.ToString().ToLowerInvariant()}_{directionString}";
}
public enum BeatmapSearchCategory
{
Any,
[Description("Has Leaderboard")]
Leaderboard,
Ranked,
Qualified,
Loved,
Favourites,
[Description("Pending & WIP")]
Pending,
Graveyard,
[Description("My Maps")]
Mine,
}
}
| // 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.ComponentModel;
using osu.Game.Overlays;
using osu.Game.Overlays.Direct;
using osu.Game.Rulesets;
namespace osu.Game.Online.API.Requests
{
public class SearchBeatmapSetsRequest : APIRequest<SearchBeatmapSetsResponse>
{
private readonly string query;
private readonly RulesetInfo ruleset;
private readonly BeatmapSearchCategory searchCategory;
private readonly DirectSortCriteria sortCriteria;
private readonly SortDirection direction;
private string directionString => direction == SortDirection.Descending ? @"desc" : @"asc";
public SearchBeatmapSetsRequest(string query, RulesetInfo ruleset, BeatmapSearchCategory searchCategory = BeatmapSearchCategory.Any, DirectSortCriteria sortCriteria = DirectSortCriteria.Ranked, SortDirection direction = SortDirection.Descending)
{
this.query = System.Uri.EscapeDataString(query);
this.ruleset = ruleset;
this.searchCategory = searchCategory;
this.sortCriteria = sortCriteria;
this.direction = direction;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
protected override string Target => $@"beatmapsets/search?q={query}&m={ruleset.ID ?? 0}&s={searchCategory.ToString().ToLowerInvariant()}&sort={sortCriteria.ToString().ToLowerInvariant()}_{directionString}";
}
public enum BeatmapSearchCategory
{
Any,
[Description("Has Leaderboard")]
Leaderboard,
Ranked,
Qualified,
Loved,
Favourites,
[Description("Pending & WIP")]
Pending,
Graveyard,
[Description("My Maps")]
Mine,
}
}
| mit | C# |
52768e510c2a2decc54a9f23946107acbcb4b681 | 修改了 JsonSerializationWriter 类,为Json序列化后的对象属性名加上了双引号。 | MetSystem/Zongsoft.CoreLibrary,huoxudong125/Zongsoft.CoreLibrary,Zongsoft/Zongsoft.CoreLibrary | Runtime/Serialization/JsonSerializationWriter.cs | Runtime/Serialization/JsonSerializationWriter.cs | /*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2013 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Text;
namespace Zongsoft.Runtime.Serialization
{
public class JsonSerializationWriter : TextSerializationWriterBase
{
#region 构造函数
public JsonSerializationWriter()
{
}
#endregion
#region 写入方法
protected override void OnWrite(SerializationWriterContext context)
{
var writer = this.GetWriter(context);
if(writer == null)
throw new System.Runtime.Serialization.SerializationException("Can not obtain a text writer.");
if(context.Index > 0)
writer.WriteLine(",");
else
writer.WriteLine();
var indentText = this.GetIndentText(context.Depth);
writer.Write(indentText);
if(context.Member != null)
writer.Write("\"" + context.MemberName + "\" : ");
if(context.Value == null || context.IsCircularReference)
{
writer.Write("\"\"");
return;
}
var directedValue = string.Empty;
var isDirectedValue = this.GetDirectedValue(context.Value, out directedValue);
if(isDirectedValue)
{
writer.Write("\"" + directedValue + "\"");
}
else
{
if(context.IsCollection)
writer.Write(writer.NewLine + indentText + "[");
else
writer.Write("{");
}
context.Terminated = isDirectedValue;
}
#endregion
#region 重写方法
protected override void OnWrote(SerializationWriterContext context)
{
if(context.Terminated || context.IsCircularReference)
return;
var writer = this.GetWriter(context);
if(writer == null)
return;
if(context.IsCollection)
writer.Write(writer.NewLine + this.GetIndentText(context.Depth) + "]");
else
writer.Write(writer.NewLine + this.GetIndentText(context.Depth) + "}");
}
#endregion
}
}
| /*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2013 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Text;
namespace Zongsoft.Runtime.Serialization
{
public class JsonSerializationWriter : TextSerializationWriterBase
{
#region 构造函数
public JsonSerializationWriter()
{
}
#endregion
#region 写入方法
protected override void OnWrite(SerializationWriterContext context)
{
var writer = this.GetWriter(context);
if(writer == null)
throw new System.Runtime.Serialization.SerializationException("Can not obtain a text writer.");
if(context.Index > 0)
writer.WriteLine(",");
else
writer.WriteLine();
var indentText = this.GetIndentText(context.Depth);
writer.Write(indentText);
if(context.Member != null)
writer.Write(context.MemberName + " : ");
if(context.Value == null || context.IsCircularReference)
{
writer.Write("\"\"");
return;
}
var directedValue = string.Empty;
var isDirectedValue = this.GetDirectedValue(context.Value, out directedValue);
if(isDirectedValue)
{
writer.Write("\"" + directedValue + "\"");
}
else
{
if(context.IsCollection)
writer.Write(writer.NewLine + indentText + "[");
else
writer.Write("{");
}
context.Terminated = isDirectedValue;
}
#endregion
#region 重写方法
protected override void OnWrote(SerializationWriterContext context)
{
if(context.Terminated || context.IsCircularReference)
return;
var writer = this.GetWriter(context);
if(writer == null)
return;
if(context.IsCollection)
writer.Write(writer.NewLine + this.GetIndentText(context.Depth) + "]");
else
writer.Write(writer.NewLine + this.GetIndentText(context.Depth) + "}");
}
#endregion
}
}
| lgpl-2.1 | C# |
f393541e698c2fc88eea40916987669de4a7d553 | bump version | sumeshthomas/sendgrid-csharp,pandeysoni/sendgrid-csharp,FriskyLingo/sendgrid-csharp,brcaswell/sendgrid-csharp,smurfpandey/sendgrid-csharp-net40,sumeshthomas/sendgrid-csharp,FriskyLingo/sendgrid-csharp,brcaswell/sendgrid-csharp,kenlefeb/sendgrid-csharp,dubrovkinmaxim/sendgrid-csharp,smurfpandey/sendgrid-csharp-net40,dubrovkinmaxim/sendgrid-csharp,sendgrid/sendgrid-csharp,kenlefeb/sendgrid-csharp,pandeysoni/sendgrid-csharp,sendgrid/sendgrid-csharp,sendgrid/sendgrid-csharp | SendGrid/SendGridMail/Properties/AssemblyInfo.cs | SendGrid/SendGridMail/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("SendGridMail")]
[assembly: AssemblyDescription("A client library for interfacing with the SendGrid API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SendGrid")]
[assembly: AssemblyProduct("SendGridMail")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("193fa200-8430-4206-aacd-2d2bb2dfa6cf")]
[assembly: InternalsVisibleTo("Tests")]
[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2," +
"1310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b" +
"PublicKey=002400000480000094000000060200000024000052534" +
"3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d926665" +
"4753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb" +
"4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c486" +
"1eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| 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("SendGridMail")]
[assembly: AssemblyDescription("A client library for interfacing with the SendGrid API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SendGrid")]
[assembly: AssemblyProduct("SendGridMail")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("193fa200-8430-4206-aacd-2d2bb2dfa6cf")]
[assembly: InternalsVisibleTo("Tests")]
[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2," +
"1310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b" +
"PublicKey=002400000480000094000000060200000024000052534" +
"3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d926665" +
"4753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb" +
"4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c486" +
"1eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
b2eb1af10484e1d2cb65c124e99d7198b959e461 | remove post broadcast | LykkeCity/bitcoinservice,LykkeCity/bitcoinservice | src/LkeServices/Bitcoin/BitcoinBroadcastService.cs | src/LkeServices/Bitcoin/BitcoinBroadcastService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Core.Bitcoin;
using Core.Performance;
using Core.Providers;
using Core.Repositories.TransactionOutputs;
using Core.Settings;
using Core.TransactionMonitoring;
using NBitcoin;
namespace LkeServices.Bitcoin
{
public class BitcoinBroadcastService : IBitcoinBroadcastService
{
private readonly IBroadcastedOutputRepository _broadcastedOutputRepository;
private readonly IRpcBitcoinClient _rpcBitcoinClient;
private readonly ILykkeApiProvider _apiProvider;
private readonly BaseSettings _settings;
private readonly ITransactionMonitoringWriter _monitoringWriter;
public BitcoinBroadcastService(IBroadcastedOutputRepository broadcastedOutputRepository,
IRpcBitcoinClient rpcBitcoinClient, ILykkeApiProvider apiProvider, BaseSettings settings,
ITransactionMonitoringWriter monitoringWriter)
{
_broadcastedOutputRepository = broadcastedOutputRepository;
_rpcBitcoinClient = rpcBitcoinClient;
_apiProvider = apiProvider;
_settings = settings;
_monitoringWriter = monitoringWriter;
}
public async Task BroadcastTransaction(Guid transactionId, Transaction tx, IPerformanceMonitor monitor = null, bool useHandlers = true, Guid? notifyTxId = null)
{
var hash = tx.GetHash().ToString();
if (_settings.UseLykkeApi && useHandlers)
{
monitor?.Step("Send prebroadcast notification");
await _apiProvider.SendPreBroadcastNotification(new LykkeTransactionNotification(notifyTxId ?? transactionId, hash));
}
monitor?.Step("Broadcast transcation");
await _rpcBitcoinClient.BroadcastTransaction(tx, transactionId);
monitor?.Step("Set transaction hash and add to monitoring");
await Task.WhenAll(
_broadcastedOutputRepository.SetTransactionHash(transactionId, hash),
_monitoringWriter.AddToMonitoring(transactionId, tx.GetHash().ToString())
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Core.Bitcoin;
using Core.Performance;
using Core.Providers;
using Core.Repositories.TransactionOutputs;
using Core.Settings;
using Core.TransactionMonitoring;
using NBitcoin;
namespace LkeServices.Bitcoin
{
public class BitcoinBroadcastService : IBitcoinBroadcastService
{
private readonly IBroadcastedOutputRepository _broadcastedOutputRepository;
private readonly IRpcBitcoinClient _rpcBitcoinClient;
private readonly ILykkeApiProvider _apiProvider;
private readonly BaseSettings _settings;
private readonly ITransactionMonitoringWriter _monitoringWriter;
public BitcoinBroadcastService(IBroadcastedOutputRepository broadcastedOutputRepository,
IRpcBitcoinClient rpcBitcoinClient, ILykkeApiProvider apiProvider, BaseSettings settings,
ITransactionMonitoringWriter monitoringWriter)
{
_broadcastedOutputRepository = broadcastedOutputRepository;
_rpcBitcoinClient = rpcBitcoinClient;
_apiProvider = apiProvider;
_settings = settings;
_monitoringWriter = monitoringWriter;
}
public async Task BroadcastTransaction(Guid transactionId, Transaction tx, IPerformanceMonitor monitor = null, bool useHandlers = true, Guid? notifyTxId = null)
{
var hash = tx.GetHash().ToString();
if (_settings.UseLykkeApi && useHandlers)
{
monitor?.Step("Send prebroadcast notification");
await _apiProvider.SendPreBroadcastNotification(new LykkeTransactionNotification(notifyTxId ?? transactionId, hash));
}
monitor?.Step("Broadcast transcation");
await _rpcBitcoinClient.BroadcastTransaction(tx, transactionId);
monitor?.Step("Set transaction hash, postbroadcast and add to monitoring");
await Task.WhenAll(
_broadcastedOutputRepository.SetTransactionHash(transactionId, hash),
Task.Run(async () =>
{
if (_settings.UseLykkeApi && useHandlers)
{
await _apiProvider.SendPostBroadcastNotification(new LykkeTransactionNotification(notifyTxId ?? transactionId, hash));
}
}
),
_monitoringWriter.AddToMonitoring(transactionId, tx.GetHash().ToString())
);
}
}
}
| mit | C# |
e8d328d623f4820e247fc26011295597e6d21a7d | Update SkiaContainerImporter.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.Skia/Export/SkiaContainerImporter.cs | src/Draw2D.Skia/Export/SkiaContainerImporter.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Draw2D.ViewModels.Containers;
using Draw2D.ViewModels.Tools;
namespace Draw2D.Export
{
public class SkiaContainerImporter : IContainerImporter
{
internal static void ImportSvg(IToolContext context, string path, IContainerView containerView)
{
var xml = File.ReadAllText(path);
if (!string.IsNullOrEmpty(xml))
{
var picture = SkiaHelper.ToSKPicture(xml);
var image = SkiaHelper.ToSKImage(picture);
}
}
public void Import(IToolContext context, string path, IContainerView containerView)
{
var outputExtension = Path.GetExtension(path);
if (string.Compare(outputExtension, ".svg", StringComparison.OrdinalIgnoreCase) == 0)
{
ImportSvg(context, path, containerView);
}
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Draw2D.Presenters;
using Draw2D.ViewModels.Containers;
using Draw2D.ViewModels.Tools;
using SkiaSharp;
namespace Draw2D.Export
{
public class SkiaContainerImporter : IContainerImporter
{
internal static void ImportSvg(IToolContext context, string path, IContainerView containerView)
{
var svg = new SkiaSharp.Extended.Svg.SKSvg();
using (var stream = File.Open(path, FileMode.Open))
{
var picture = svg.Load(stream);
//var image = SKImage.FromPicture(picture, picture.CullRect.Size.ToSizeI());
}
}
public void Import(IToolContext context, string path, IContainerView containerView)
{
var outputExtension = Path.GetExtension(path);
if (string.Compare(outputExtension, ".svg", StringComparison.OrdinalIgnoreCase) == 0)
{
ImportSvg(context, path, containerView);
}
}
}
}
| mit | C# |
2ddd9bfe10130589960751bedb9ebd1820f72a2a | Tidy up | beyond-code-github/Superscribe | Superscribe.Demo.WebApiModules/HelloWorldModule.cs | Superscribe.Demo.WebApiModules/HelloWorldModule.cs | namespace Superscribe.Demo.WebApiModules
{
using Superscribe.Demo.WebApiModules.Services;
using Superscribe.Models;
using Superscribe.WebApi.Modules;
public class MessageWrapper
{
public string Message { get; set; }
}
public class HelloWorldModule : SuperscribeModule
{
public HelloWorldModule()
{
this.Get["/"] = o => new { Message = "Hello World" };
this.Get["Hello" / (ʃString)"Name"] = o =>
{
var helloService = o.Require<IHelloService>();
return new { Message = helloService.SayHello(o.Parameters.Name) };
};
this.Post["Save"] = o =>
{
var wrapper = o.Bind<MessageWrapper>();
return new { Message = "You entered - " + wrapper.Message };
};
}
}
} | namespace Superscribe.Demo.WebApiModules
{
using Superscribe.Demo.WebApiModules.Services;
using Superscribe.Models;
using Superscribe.WebApi.Modules;
public class MessageWrapper
{
public string Message { get; set; }
}
public class HelloWorldModule : SuperscribeModule
{
public HelloWorldModule()
{
this.Get["/"] = o => new { Message = "Hello World" };
this.Get["Hello" / (ʃString)"Name"] = o =>
{
var helloService = o.Require<IHelloService>();
return new { Message = helloService.SayHello(o.Parameters.Name) };
};
this.Post["Save"] = o =>
{
var wrapper = o.Bind<MessageWrapper>();
return new { Message = "You entered - " + wrapper.Message };
};
}
}
} | apache-2.0 | C# |
b364aa61b137e4e37744ebb0cbeac3908524f4ce | Implement GetSchedule functionality for Rooms | meutley/ISTS | src/Infrastructure/Repository/RoomRepository.cs | src/Infrastructure/Repository/RoomRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
using ISTS.Infrastructure.Model;
namespace ISTS.Infrastructure.Repository
{
public class RoomRepository : IRoomRepository
{
private readonly IstsContext _context;
public RoomRepository(
IstsContext context)
{
_context = context;
}
public Room Get(Guid id)
{
return null;
}
public RoomSession GetSession(Guid id)
{
return null;
}
public RoomSession CreateSession(Guid roomId, RoomSession entity)
{
return null;
}
public RoomSession RescheduleSession(Guid id, DateRange schedule)
{
return null;
}
public RoomSession StartSession(Guid id, DateTime time)
{
return null;
}
public RoomSession EndSession(Guid id, DateTime time)
{
return null;
}
public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range)
{
var sessions = _context.Sessions
.Where(s => s.RoomId == id)
.ToList();
var schedule = sessions
.Select(s => RoomSessionSchedule.Create(s.Id, s.Schedule));
return schedule;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
namespace ISTS.Infrastructure.Repository
{
public class RoomRepository : IRoomRepository
{
public Room Get(Guid id)
{
return null;
}
public RoomSession GetSession(Guid id)
{
return null;
}
public RoomSession CreateSession(Guid roomId, RoomSession entity)
{
return null;
}
public RoomSession RescheduleSession(Guid id, DateRange schedule)
{
return null;
}
public RoomSession StartSession(Guid id, DateTime time)
{
return null;
}
public RoomSession EndSession(Guid id, DateTime time)
{
return null;
}
public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range)
{
return Enumerable.Empty<RoomSessionSchedule>();
}
}
} | mit | C# |
535d3d136ec6a3bd6f6426eca3bc128d152b5361 | Comment out StreamReader. | CosmosOS/Cosmos,zarlo/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,Cyber4/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos,trivalik/Cosmos,tgiphil/Cosmos,tgiphil/Cosmos,Cyber4/Cosmos,tgiphil/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,MyvarHD/Cosmos,zarlo/Cosmos,fanoI/Cosmos,trivalik/Cosmos,fanoI/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,MyvarHD/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos,CosmosOS/Cosmos | source/Cosmos.System.Plugs/System/IO/StreamReaderImpl.cs | source/Cosmos.System.Plugs/System/IO/StreamReaderImpl.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.System.Plugs.System.IO
{
//[Plug(Target = typeof(global::System.IO.StreamReader))]
//public static class StreamReaderImpl
//{
// public static void CheckAsyncTaskInProgress(global::System.IO.StreamReader aThis)
// {
// // for now do nothing
// }
//}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.System.Plugs.System.IO
{
[Plug(Target = typeof(global::System.IO.StreamReader))]
public static class StreamReaderImpl
{
public static void CheckAsyncTaskInProgress(global::System.IO.StreamReader aThis)
{
// for now do nothing
}
}
}
| bsd-3-clause | C# |
2ce3ea318f865d43f37e22e3d39c4b1ca4061e30 | edit order credit marketplace | balanced/balanced-csharp | scenarios/snippets/order-credit-marketplace.cs | scenarios/snippets/order-credit-marketplace.cs | BankAccount marketplaceAccount = Marketplace.Mine.owner_customer.bank_accounts.First();
Dictionary<string, object> creditPayload = new Dictionary<string, object>();
creditPayload.Add("amount", 2000);
creditPayload.Add("description", "Credit from order escrow to marketplace bank account");
Credit credit = order.CreditTo(marketplaceAccount, creditPayload); | BankAccount bankAccount = Marketplace.Mine.owner_customer.bank_accounts.First();
Dictionary<string, object> payload = new Dictionary<string, object>();
payload.Add("amount", 2000);
payload.Add("description", "Credit from order escrow to marketplace bank account");
Credit credit = bankAccount.Credit(payload); | mit | C# |
5864182d85683b5cf947c0dba6fef9a41cb45e22 | replace table with list group | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/Views/Shared/_SpatialReference.cshtml | WebAPI.API/Views/Shared/_SpatialReference.cshtml | <p class="help-block">
The spatial reference for the output and input geometries.
<strong class="text-warning">The output and input spatial references must match.</strong>
Choose any of the <abbr title="Well-known Id">wkid</abbr>'s from the
<a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/geographic_coordinate_systems.pdf">Geographic Coordinate System wkid reference</a>
or <a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/projected_coordinate_systems.pdf">Projected Coordinate System wkid reference</a>.
<code>26912</code> is the default.
</p>
<div class="col-sm-offset-2 col-sm-8 list-group">
<div class="list-group-item">
<h4 class="list-group-item-heading">Popular wkid's</h4>
</div>
<div class="list-group-item">
Web Mercator
<span class="badge">3857</span>
</div>
<div class="list-group-item">
Latitude/Longitude (WGS84)
<span class="badge">4326</span>
</div>
</div> | <p class="help-block">
The spatial reference for the output and input geometries.
<strong class="text-warning">The output and input spatial references must match.</strong>
Choose any of the <abbr title="Well-known Id">wkid</abbr>'s from the
<a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/geographic_coordinate_systems.pdf">Geographic Coordinate System wkid reference</a>
or <a href="http://resources.arcgis.com/en/help/main/10.1/018z/pdf/projected_coordinate_systems.pdf">Projected Coordinate System wkid reference</a>.
<code>26912</code> is the default.
</p>
<span class="label label-info">Popular WKID's</span>
<table class="table table-condensed">
<thead>
<tr>
<th>System</th>
<th>wkid</th>
</tr>
</thead>
<tbody>
<tr>
<td>Web Mercator</td>
<td>3857</td>
</tr>
<tr>
<td>Latitude/Longitude (WGS84)</td>
<td>4326</td>
</tr>
</tbody>
</table>
| mit | C# |
48a7f88fa884bb2886c3e2c365d3b2bfcbb027f9 | update AssemblyVersion | gigya/KafkaNetClient | src/KafkaNetClient/Properties/AssemblyInfo.cs | src/KafkaNetClient/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("KafkaNetClient")]
[assembly: AssemblyDescription("Native C# client for Apache Kafka.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Gigya Inc")]
[assembly: AssemblyProduct("KafkaNetClient")]
[assembly: AssemblyCopyright("Copyright ©Gigya Inc 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: GuidAttribute("eb234ec0-d838-4abd-9224-479ca06f969d")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("KafkaNetClient")]
[assembly: AssemblyDescription("Native C# client for Apache Kafka.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Gigya Inc")]
[assembly: AssemblyProduct("KafkaNetClient")]
[assembly: AssemblyCopyright("Copyright ©Gigya Inc 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: GuidAttribute("eb234ec0-d838-4abd-9224-479ca06f969d")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
| apache-2.0 | C# |
6fa4404f4ca1ffc9de65d31bd5c4e38a8e0798a6 | Replace CotinueWith with async/await | jbogard/MediatR | src/MediatR/Wrappers/RequestHandlerWrapper.cs | src/MediatR/Wrappers/RequestHandlerWrapper.cs | namespace MediatR.Wrappers
{
using System;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
public abstract class RequestHandlerBase
{
public abstract Task<object?> Handle(object request, CancellationToken cancellationToken,
ServiceFactory serviceFactory);
protected static THandler GetHandler<THandler>(ServiceFactory factory)
{
THandler handler;
try
{
handler = factory.GetInstance<THandler>();
}
catch (Exception e)
{
throw new InvalidOperationException($"Error constructing handler for request of type {typeof(THandler)}. Register your handlers with the container. See the samples in GitHub for examples.", e);
}
if (handler == null)
{
throw new InvalidOperationException($"Handler was not found for request of type {typeof(THandler)}. Register your handlers with the container. See the samples in GitHub for examples.");
}
return handler;
}
}
public abstract class RequestHandlerWrapper<TResponse> : RequestHandlerBase
{
public abstract Task<TResponse> Handle(IRequest<TResponse> request, CancellationToken cancellationToken,
ServiceFactory serviceFactory);
}
public class RequestHandlerWrapperImpl<TRequest, TResponse> : RequestHandlerWrapper<TResponse>
where TRequest : IRequest<TResponse>
{
public override async Task<object?> Handle(object request, CancellationToken cancellationToken,
ServiceFactory serviceFactory) =>
await Handle((IRequest<TResponse>)request, cancellationToken, serviceFactory);
public override Task<TResponse> Handle(IRequest<TResponse> request, CancellationToken cancellationToken,
ServiceFactory serviceFactory)
{
Task<TResponse> Handler() => GetHandler<IRequestHandler<TRequest, TResponse>>(serviceFactory).Handle((TRequest) request, cancellationToken);
return serviceFactory
.GetInstances<IPipelineBehavior<TRequest, TResponse>>()
.Reverse()
.Aggregate((RequestHandlerDelegate<TResponse>) Handler, (next, pipeline) => () => pipeline.Handle((TRequest)request, cancellationToken, next))();
}
}
}
| namespace MediatR.Wrappers
{
using System;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
public abstract class RequestHandlerBase
{
public abstract Task<object?> Handle(object request, CancellationToken cancellationToken,
ServiceFactory serviceFactory);
protected static THandler GetHandler<THandler>(ServiceFactory factory)
{
THandler handler;
try
{
handler = factory.GetInstance<THandler>();
}
catch (Exception e)
{
throw new InvalidOperationException($"Error constructing handler for request of type {typeof(THandler)}. Register your handlers with the container. See the samples in GitHub for examples.", e);
}
if (handler == null)
{
throw new InvalidOperationException($"Handler was not found for request of type {typeof(THandler)}. Register your handlers with the container. See the samples in GitHub for examples.");
}
return handler;
}
}
public abstract class RequestHandlerWrapper<TResponse> : RequestHandlerBase
{
public abstract Task<TResponse> Handle(IRequest<TResponse> request, CancellationToken cancellationToken,
ServiceFactory serviceFactory);
}
public class RequestHandlerWrapperImpl<TRequest, TResponse> : RequestHandlerWrapper<TResponse>
where TRequest : IRequest<TResponse>
{
public override Task<object?> Handle(object request, CancellationToken cancellationToken,
ServiceFactory serviceFactory) =>
Handle((IRequest<TResponse>)request, cancellationToken, serviceFactory)
.ContinueWith(t =>
{
if (t.IsFaulted && t.Exception?.InnerException is not null)
{
ExceptionDispatchInfo.Capture(t.Exception.InnerException).Throw();
}
return (object?)t.Result;
}, cancellationToken);
public override Task<TResponse> Handle(IRequest<TResponse> request, CancellationToken cancellationToken,
ServiceFactory serviceFactory)
{
Task<TResponse> Handler() => GetHandler<IRequestHandler<TRequest, TResponse>>(serviceFactory).Handle((TRequest) request, cancellationToken);
return serviceFactory
.GetInstances<IPipelineBehavior<TRequest, TResponse>>()
.Reverse()
.Aggregate((RequestHandlerDelegate<TResponse>) Handler, (next, pipeline) => () => pipeline.Handle((TRequest)request, cancellationToken, next))();
}
}
}
| apache-2.0 | C# |
6866d74d2125950924918b492c8423dbd6ff7387 | Fix warning CS0078. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | src/MitternachtBot/Common/ModerationPoints.cs | src/MitternachtBot/Common/ModerationPoints.cs | using Mitternacht.Database.Models;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Mitternacht.Common {
public class ModerationPoints : IModerationPoints {
public long PointsHard { get; set; }
public long PointsMedium { get; set; }
public long PointsLight { get; set; }
public ModerationPoints(long hard, long medium, long light) {
PointsHard = hard;
PointsMedium = medium;
PointsLight = light;
}
public override string ToString()
=> PointsHard == 0 && PointsMedium == 0 && PointsLight == 0 ? "0L" : $"{(PointsHard != 0 ? $"{PointsHard}H" : "")}{(PointsMedium != 0 ? $"{PointsMedium}M" : "")}{(PointsLight != 0 ? $"{PointsLight}L" : "")}";
public static ModerationPoints operator +(ModerationPoints a, IModerationPoints b)
=> new ModerationPoints(a.PointsHard + b.PointsHard, a.PointsMedium + b.PointsMedium, a.PointsLight + b.PointsLight);
public static ModerationPoints FromList(IEnumerable<IModerationPoints> moderationPoints) {
var hard = 0L;
var medium = 0L;
var light = 0L;
foreach(var mp in moderationPoints) {
hard += mp.PointsHard;
medium += mp.PointsMedium;
light += mp.PointsLight;
}
return new ModerationPoints(hard, medium, light);
}
public static ModerationPoints FromString(string moderationPointsString) {
var match = Regex.Match(moderationPointsString.Trim(), "\\A(?:(?<hard>(\\+|-)?\\d+)(?:H|S))?(?:(?<medium>(\\+|-)?\\d+)M)?(?:(?<light>(\\+|-)?\\d+)L)?\\z", RegexOptions.IgnoreCase);
if(!string.IsNullOrWhiteSpace(moderationPointsString) && match != null && match.Success){
if(!long.TryParse(match.Groups["hard" ].Value, out var hard))
hard = 0;
if(!long.TryParse(match.Groups["medium"].Value, out var medium))
medium = 0;
if(!long.TryParse(match.Groups["light" ].Value, out var light))
light = 0;
return new ModerationPoints(hard, medium, light);
} else {
throw new ArgumentException($"'{moderationPointsString}' is not a valid moderation points string.", nameof(moderationPointsString));
}
}
public static explicit operator ModerationPoints(Warning warning)
=> new ModerationPoints(warning.PointsHard, warning.PointsMedium, warning.PointsLight);
}
}
| using Mitternacht.Database.Models;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Mitternacht.Common {
public class ModerationPoints : IModerationPoints {
public long PointsHard { get; set; }
public long PointsMedium { get; set; }
public long PointsLight { get; set; }
public ModerationPoints(long hard, long medium, long light) {
PointsHard = hard;
PointsMedium = medium;
PointsLight = light;
}
public override string ToString()
=> PointsHard == 0 && PointsMedium == 0 && PointsLight == 0 ? "0L" : $"{(PointsHard != 0 ? $"{PointsHard}H" : "")}{(PointsMedium != 0 ? $"{PointsMedium}M" : "")}{(PointsLight != 0 ? $"{PointsLight}L" : "")}";
public static ModerationPoints operator +(ModerationPoints a, IModerationPoints b)
=> new ModerationPoints(a.PointsHard + b.PointsHard, a.PointsMedium + b.PointsMedium, a.PointsLight + b.PointsLight);
public static ModerationPoints FromList(IEnumerable<IModerationPoints> moderationPoints) {
var hard = 0l;
var medium = 0l;
var light = 0l;
foreach(var mp in moderationPoints) {
hard += mp.PointsHard;
medium += mp.PointsMedium;
light += mp.PointsLight;
}
return new ModerationPoints(hard, medium, light);
}
public static ModerationPoints FromString(string moderationPointsString) {
var match = Regex.Match(moderationPointsString.Trim(), "\\A(?:(?<hard>(\\+|-)?\\d+)(?:H|S))?(?:(?<medium>(\\+|-)?\\d+)M)?(?:(?<light>(\\+|-)?\\d+)L)?\\z", RegexOptions.IgnoreCase);
if(!string.IsNullOrWhiteSpace(moderationPointsString) && match != null && match.Success){
if(!long.TryParse(match.Groups["hard" ].Value, out var hard))
hard = 0;
if(!long.TryParse(match.Groups["medium"].Value, out var medium))
medium = 0;
if(!long.TryParse(match.Groups["light" ].Value, out var light))
light = 0;
return new ModerationPoints(hard, medium, light);
} else {
throw new ArgumentException($"'{moderationPointsString}' is not a valid moderation points string.", nameof(moderationPointsString));
}
}
public static explicit operator ModerationPoints(Warning warning)
=> new ModerationPoints(warning.PointsHard, warning.PointsMedium, warning.PointsLight);
}
}
| mit | C# |
c2afd43b151b1591f704dded53e4840c39cd0e64 | Add a watcher test for SubFileSystem for good measure | xoofx/zio | src/Zio.Tests/FileSystems/TestSubFileSystem.cs | src/Zio.Tests/FileSystems/TestSubFileSystem.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using Xunit;
using Zio.FileSystems;
namespace Zio.Tests.FileSystems
{
public class TestSubFileSystem : TestFileSystemBase
{
[Fact]
public void TestBasic()
{
var fs = new PhysicalFileSystem();
var path = fs.ConvertPathFromInternal(SystemPath);
// Create a filesystem / on the current folder of this assembly
var subfs = new SubFileSystem(fs, path);
// This test is basically testing the two methods (ConvertPathToDelegate and ConvertPathFromDelegate) in SubFileSystem
var files = subfs.EnumeratePaths("/").Select(info => info.GetName()).ToList();
var expectedFiles = fs.EnumeratePaths(path).Select(info => info.GetName()).ToList();
Assert.True(files.Count > 0);
Assert.Equal(expectedFiles, files);
// Check that SubFileSystem is actually checking that the directory exists in the delegate filesystem
Assert.Throws<DirectoryNotFoundException>(() => new SubFileSystem(fs, path / "does_not_exist"));
Assert.Throws<InvalidOperationException>(() => subfs.ConvertPathFromInternal(@"C:\"));
// TODO: We could add another test just to make sure that files can be created...etc. But the test above should already cover the code provided in SubFileSystem
}
[Fact]
public void TestGetOrCreateFileSystem()
{
var fs = new MemoryFileSystem();
const string subFolder = "/sub";
var subFileSystem = fs.GetOrCreateSubFileSystem(subFolder);
Assert.True(fs.DirectoryExists(subFolder));
subFileSystem.WriteAllText("/test.txt", "yo");
var text = fs.ReadAllText(subFolder + "/test.txt");
Assert.Equal("yo", text);
}
[Fact]
public void TestWatcher()
{
var fs = GetCommonMemoryFileSystem();
var subFs = fs.GetOrCreateSubFileSystem("/a/b");
var watcher = subFs.Watch("/");
var gotChange = false;
watcher.Created += (sender, args) =>
{
if (args.FullPath == "/watched.txt")
{
gotChange = true;
}
};
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
fs.WriteAllText("/a/b/watched.txt", "test");
System.Threading.Thread.Sleep(100);
Assert.True(gotChange);
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using Xunit;
using Zio.FileSystems;
namespace Zio.Tests.FileSystems
{
public class TestSubFileSystem : TestFileSystemBase
{
[Fact]
public void TestBasic()
{
var fs = new PhysicalFileSystem();
var path = fs.ConvertPathFromInternal(SystemPath);
// Create a filesystem / on the current folder of this assembly
var subfs = new SubFileSystem(fs, path);
// This test is basically testing the two methods (ConvertPathToDelegate and ConvertPathFromDelegate) in SubFileSystem
var files = subfs.EnumeratePaths("/").Select(info => info.GetName()).ToList();
var expectedFiles = fs.EnumeratePaths(path).Select(info => info.GetName()).ToList();
Assert.True(files.Count > 0);
Assert.Equal(expectedFiles, files);
// Check that SubFileSystem is actually checking that the directory exists in the delegate filesystem
Assert.Throws<DirectoryNotFoundException>(() => new SubFileSystem(fs, path / "does_not_exist"));
Assert.Throws<InvalidOperationException>(() => subfs.ConvertPathFromInternal(@"C:\"));
// TODO: We could add another test just to make sure that files can be created...etc. But the test above should already cover the code provided in SubFileSystem
}
[Fact]
public void TestGetOrCreateFileSystem()
{
var fs = new MemoryFileSystem();
const string subFolder = "/sub";
var subFileSystem = fs.GetOrCreateSubFileSystem(subFolder);
Assert.True(fs.DirectoryExists(subFolder));
subFileSystem.WriteAllText("/test.txt", "yo");
var text = fs.ReadAllText(subFolder + "/test.txt");
Assert.Equal("yo", text);
}
}
} | bsd-2-clause | C# |
fa0f636024c8fbfcd014212455d6855cd07710f0 | Update some test assembly paths | rileywhite/Cilador | src/Cilador/Fody.Tests/Common/TestContent.cs | src/Cilador/Fody.Tests/Common/TestContent.cs | /***************************************************************************/
// Copyright 2013-2018 Riley White
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Cilador.Fody.Tests.Common
{
internal static class TestContent
{
public static BindingFlags BindingFlagsForWeavedMembers =
BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static string GetTestSolutionDirectory()
{
return Path.GetFullPath(@"..\..\..\");
}
private static readonly string TestProjectDirectoryRelativeToExecutingAssemblyFormat = @"..\..\..\{0}";
private static readonly string TestAssemblyPathRelativeToExecutingAssemblyFormat =
TestProjectDirectoryRelativeToExecutingAssemblyFormat + @"\bin\{1}\Cilador.{0}.dll";
public static string GetTestPath(string assemblyFilename)
{
var targetPathFormat = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(new Uri(typeof(TestContent).Assembly.CodeBase).LocalPath),
string.Format(TestAssemblyPathRelativeToExecutingAssemblyFormat, assemblyFilename.Substring(8), "{0}")));
#if (DEBUG)
return string.Format(targetPathFormat, @"Debug\netstandard2.0");
#else
return string.Format(targetPathFormat, @"Release\netstandard2.0");
#endif
}
public static string GetDirectory(string assemblyFilename)
{
return Path.GetDirectoryName(GetTestPath(assemblyFilename));
}
}
}
| /***************************************************************************/
// Copyright 2013-2018 Riley White
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Cilador.Fody.Tests.Common
{
internal static class TestContent
{
public static BindingFlags BindingFlagsForWeavedMembers =
BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public static string GetTestSolutionDirectory()
{
return Path.GetFullPath(@"..\..\..\");
}
private static readonly string TestProjectDirectoryRelativeToExecutingAssemblyFormat = @"..\..\..\{0}";
private static readonly string TestAssemblyPathRelativeToExecutingAssemblyFormat =
TestProjectDirectoryRelativeToExecutingAssemblyFormat + @"\bin\{1}\{0}.dll";
public static string GetTestPath(string assemblyFilename)
{
var targetPathFormat = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(new Uri(typeof(TestContent).Assembly.CodeBase).LocalPath),
string.Format(TestAssemblyPathRelativeToExecutingAssemblyFormat, assemblyFilename, "{0}")));
#if (DEBUG)
return string.Format(targetPathFormat, "Debug");
#else
return string.Format(targetPathFormat, "Release");
#endif
}
public static string GetDirectory(string assemblyFilename)
{
return Path.GetDirectoryName(GetTestPath(assemblyFilename));
}
}
}
| apache-2.0 | C# |
79782633f093404f64f5a08e724231cd054d8e85 | Update registry | ektrah/nsec | tests/Registry.cs | tests/Registry.cs | using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests
{
internal static class Registry
{
#region Algorithms By Base Class
public static readonly TheoryData<Type> AeadAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> AuthenticationAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> HashAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeyAgreementAlgorithms = new TheoryData<Type>
{
typeof(X25519),
};
public static readonly TheoryData<Type> KeyDerivationAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> PasswordHashAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> SignatureAlgorithms = new TheoryData<Type>
{
typeof(Ed25519),
};
#endregion
#region Algorithms By Key Type
public static readonly TheoryData<Type> AsymmetricAlgorithms = new TheoryData<Type>
{
typeof(X25519),
typeof(Ed25519),
};
public static readonly TheoryData<Type> SymmetricAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeylessAlgorithms = new TheoryData<Type>
{
};
#endregion
#region Key Blob Formats
public static readonly TheoryData<Type, KeyBlobFormat> PublicKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
{ typeof(X25519), KeyBlobFormat.RawPublicKey },
{ typeof(Ed25519), KeyBlobFormat.RawPublicKey },
};
public static readonly TheoryData<Type, KeyBlobFormat> PrivateKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
{ typeof(X25519), KeyBlobFormat.RawPrivateKey },
{ typeof(Ed25519), KeyBlobFormat.RawPrivateKey },
};
public static readonly TheoryData<Type, KeyBlobFormat> SymmetricKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
#endregion
}
}
| using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests
{
internal static class Registry
{
#region Algorithms By Base Class
public static readonly TheoryData<Type> AeadAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> AuthenticationAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> HashAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeyAgreementAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeyDerivationAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> PasswordHashAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> SignatureAlgorithms = new TheoryData<Type>
{
};
#endregion
#region Algorithms By Key Type
public static readonly TheoryData<Type> AsymmetricAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> SymmetricAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeylessAlgorithms = new TheoryData<Type>
{
};
#endregion
#region Key Blob Formats
public static readonly TheoryData<Type, KeyBlobFormat> PublicKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
public static readonly TheoryData<Type, KeyBlobFormat> PrivateKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
public static readonly TheoryData<Type, KeyBlobFormat> SymmetricKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
#endregion
}
}
| mit | C# |
4e2a88a69835592028361c7acee51da0a85c4ce1 | Fix FxCop violation from HttpResponseException changes | LianwMS/WebApi,scz2011/WebApi,lungisam/WebApi,scz2011/WebApi,lewischeng-ms/WebApi,LianwMS/WebApi,lungisam/WebApi,yonglehou/WebApi,congysu/WebApi,congysu/WebApi,abkmr/WebApi,lewischeng-ms/WebApi,chimpinano/WebApi,abkmr/WebApi,yonglehou/WebApi,chimpinano/WebApi | src/System.Web.Http/HttpResponseException.cs | src/System.Web.Http/HttpResponseException.cs | // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Web.Http.Properties;
namespace System.Web.Http
{
/// <summary>
/// An exception that allows for a given <see cref="HttpResponseMessage"/>
/// to be returned to the client.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "This type is not meant to be serialized")]
[SuppressMessage("Microsoft.Usage", "CA2240:Implement ISerializable correctly", Justification = "This type has no serializable state")]
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "HttpResponseException is not a real exception and is just an easy way to return HttpResponseMessage")]
public class HttpResponseException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpResponseException"/> class.
/// </summary>
/// <param name="statusCode">The status code of the response.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Instance is disposed elsewhere")]
public HttpResponseException(HttpStatusCode statusCode)
: this(new HttpResponseMessage(statusCode))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpResponseException"/> class.
/// </summary>
/// <param name="response">The response message.</param>
public HttpResponseException(HttpResponseMessage response)
: base(SRResources.HttpResponseExceptionMessage)
{
if (response == null)
{
throw Error.ArgumentNull("response");
}
Response = response;
}
/// <summary>
/// Gets the <see cref="HttpResponseMessage"/> to return to the client.
/// </summary>
public HttpResponseMessage Response { get; private set; }
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Web.Http.Properties;
namespace System.Web.Http
{
/// <summary>
/// An exception that allows for a given <see cref="HttpResponseMessage"/>
/// to be returned to the client.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "This type is not meant to be serialized")]
[SuppressMessage("Microsoft.Usage", "CA2240:Implement ISerializable correctly", Justification = "This type has no serializable state")]
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "HttpResponseException is not a real exception and is just an easy way to return HttpResponseMessage")]
public class HttpResponseException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpResponseException"/> class.
/// </summary>
/// <param name="statusCode">The status code of the response.</param>
public HttpResponseException(HttpStatusCode statusCode)
: this(new HttpResponseMessage(statusCode))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpResponseException"/> class.
/// </summary>
/// <param name="response">The response message.</param>
public HttpResponseException(HttpResponseMessage response)
: base(SRResources.HttpResponseExceptionMessage)
{
if (response == null)
{
throw Error.ArgumentNull("response");
}
Response = response;
}
/// <summary>
/// Gets the <see cref="HttpResponseMessage"/> to return to the client.
/// </summary>
public HttpResponseMessage Response { get; private set; }
}
}
| mit | C# |
89a18e4aac47644e61373862ed3492530a80a948 | remove nl and add comment for -1 and +1 | ZLima12/osu,peppy/osu,smoogipooo/osu,ppy/osu,johnneijzen/osu,peppy/osu,naoey/osu,DrabWeb/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,NeoAdonis/osu,DrabWeb/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,naoey/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,2yangk23/osu,2yangk23/osu | osu.Game.Rulesets.Osu/Mods/OsuModArrange.cs | osu.Game.Rulesets.Osu/Mods/OsuModArrange.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 System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModArrange : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Arrange";
public override string ShortenedName => "Arrange";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.Fun;
public override string Description => "Everything rotates. EVERYTHING.";
public override double ScoreMultiplier => 1;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable => drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState);
}
private float theta;
private void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
var hitObject = (OsuHitObject) drawable.HitObject;
// repeat points get their position data from the slider.
if (hitObject is RepeatPoint)
return;
Vector2 originalPosition = drawable.Position;
const float appear_distance = 250;
//the - 1 and + 1 prevents the hit explosion to appear in the wrong position.
double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1;
double moveDuration = hitObject.TimePreempt + 1;
using (drawable.BeginAbsoluteSequence(appearTime, true))
{
drawable
.MoveToOffset(new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appear_distance)
.MoveTo(originalPosition, moveDuration, Easing.InOutSine);
}
// That way slider ticks come all from the same direction.
if (hitObject is HitCircle || hitObject is Slider)
theta += 0.4f;
}
}
}
| // 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 System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModArrange : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Arrange";
public override string ShortenedName => "Arrange";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.Fun;
public override string Description => "Everything rotates. EVERYTHING.";
public override double ScoreMultiplier => 1;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable => drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState);
}
private float theta;
private void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
var hitObject = (OsuHitObject) drawable.HitObject;
// repeat points get their position data from the slider.
if (hitObject is RepeatPoint)
return;
Vector2 originalPosition = drawable.Position;
const float appear_distance = 250;
double appearTime = hitObject.StartTime - hitObject.TimePreempt - 1;
double moveDuration = hitObject.TimePreempt + 1;
using (drawable.BeginAbsoluteSequence(appearTime, true))
{
drawable
.MoveToOffset(new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appear_distance)
.MoveTo(originalPosition, moveDuration, Easing.InOutSine);
}
// That way slider ticks come all from the same direction.
if (hitObject is HitCircle || hitObject is Slider)
theta += 0.4f;
}
}
}
| mit | C# |
2af3e59fcbd146fc1cb7dacc3b1695740cef53e2 | Increase version | cap9/EEPhysics,Tunous/EEPhysics | EEPhysics/Properties/AssemblyInfo.cs | EEPhysics/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("EEPhysics")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EEPhysics")]
[assembly: AssemblyCopyright("MIT License")]
[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("80820906-c3b5-43f6-9eac-97906f07f2f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.4.0")]
[assembly: AssemblyFileVersion("1.1.4.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("EEPhysics")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EEPhysics")]
[assembly: AssemblyCopyright("MIT License")]
[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("80820906-c3b5-43f6-9eac-97906f07f2f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.3.0")]
[assembly: AssemblyFileVersion("1.1.3.0")]
| mit | C# |
df05a31213a8ae67249c2272d73c559e64da4741 | Update code | sakapon/Samples-2013 | EFSample/DirectoryConsole/Program.cs | EFSample/DirectoryConsole/Program.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace DirectoryConsole
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DirectoryDbInitializer());
using (var db = new DirectoryDb())
{
var files = db.Entries
.OfType<File>()
.Include(f => f.Parent)
.ToArray();
var dir1 = db.Entries
.OfType<Folder>()
.Where(f => f.Name == "Dir 1")
.Include(f => f.Subentries)
.Single();
foreach (var item in dir1.Subentries)
{
Console.WriteLine(item.Name);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace DirectoryConsole
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DirectoryDbInitializer());
GetData();
}
static void GetData()
{
using (var db = new DirectoryDb())
{
var files = db.Entries
.OfType<File>()
.Include(f => f.Parent)
.ToArray();
var dir1 = db.Entries
.OfType<Folder>()
.Where(f => f.Name == "Dir 1")
.Include(f => f.Subentries)
.Single();
foreach (var item in dir1.Subentries)
{
Console.WriteLine(item.Name);
}
}
}
}
}
| mit | C# |
749a0dd8779b4d075ecd7a84769718c0d28e1f7e | Add invalid message + aria tags to login | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Views/Account/Login.cshtml | src/SFA.DAS.EmployerUsers.Web/Views/Account/Login.cshtml | @model bool
@{
var invalidAttributes = Model ? "aria-invalid=\"true\" aria-labeledby=\"invalidMessage\"" : "";
}
<div class="grid-row">
<div class="column-half">
<h1 class="heading-large">Sign in</h1>
@if (Model)
{
<div class="error" style="margin-bottom: 10px;" id="invalidMessage">
<p class="error-message">Invalid Email address / Password</p>
</div>
}
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label" for="email-address">Email address</label>
<input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text"
autofocus="autofocus" aria-required="true" @invalidAttributes>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control form-control-3-4" id="password" name="Password" type="password"
aria-required="true" @invalidAttributes>
<p>
<a href="#">I can't access my account</a>
</p>
</div>
<div class="form-group">
<button type="submit" class="button">Sign in</button>
</div>
</form>
</div>
<div class="column-half">
<h1 class="heading-large">New to this service?</h1>
<p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p>
</div>
</div> | <div class="grid-row">
<div class="column-half">
<h1 class="heading-large">Sign in</h1>
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label" for="email-address">Email address</label>
<input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text">
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control form-control-3-4" id="password" name="Password" type="password">
<p>
<a href="#">I can't access my account</a>
</p>
</div>
<div class="form-group">
<button type="submit" class="button">Sign in</button>
</div>
</form>
</div>
<div class="column-half">
<h1 class="heading-large">New to this service?</h1>
<p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p>
</div>
</div> | mit | C# |
061dc64bcc00bd7289555d0d0c790bac7e7b0614 | fix - number in JSON are Int64 | jdevillard/JmesPath.Net | src/jmespath.net/Functions/ToNumberFunction.cs | src/jmespath.net/Functions/ToNumberFunction.cs | using System;
using System.Globalization;
using DevLab.JmesPath.Utils;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Functions
{
public class ToNumberFunction : JmesPathFunction
{
public ToNumberFunction()
: base("to_number", 1)
{
}
public override JToken Execute(params JmesPathFunctionArgument[] args)
{
System.Diagnostics.Debug.Assert(args.Length == 1);
System.Diagnostics.Debug.Assert(args[0].IsToken);
var argument = args[0];
var token = argument.Token;
switch (token.GetTokenType())
{
case "number":
return token;
case "string":
{
var value = token.Value<string>();
Int64 i = 0;
double d = 0;
if (Int64.TryParse(value, out i))
return new JValue(i);
if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
return new JValue(d);
return JTokens.Null;
}
default:
return JTokens.Null;
}
}
}
} | using System;
using System.Globalization;
using DevLab.JmesPath.Utils;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Functions
{
public class ToNumberFunction : JmesPathFunction
{
public ToNumberFunction()
: base("to_number", 1)
{
}
public override JToken Execute(params JmesPathFunctionArgument[] args)
{
System.Diagnostics.Debug.Assert(args.Length == 1);
System.Diagnostics.Debug.Assert(args[0].IsToken);
var argument = args[0];
var token = argument.Token;
switch (token.GetTokenType())
{
case "number":
return token;
case "string":
{
var value = token.Value<string>();
int i = 0;
double d = 0;
if (int.TryParse(value, out i))
return new JValue(i);
if (double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
return new JValue(d);
return JTokens.Null;
}
default:
return JTokens.Null;
}
}
}
} | apache-2.0 | C# |
dcfe9e39a17d3739942e4f619404d6ba9c618942 | Improve debug string representation of MacroDefinition. | inordertotest/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,mono/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mono/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,mono/CppSharp,inordertotest/CppSharp,mono/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,u255436/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,mono/CppSharp,Samana/CppSharp,SonyaSa/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,mono/CppSharp,u255436/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,mydogisbox/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,Samana/CppSharp | src/AST/Preprocessor.cs | src/AST/Preprocessor.cs | namespace CppSharp.AST
{
public enum MacroLocation
{
Unknown,
ClassHead,
ClassBody,
FunctionHead,
FunctionParameters,
FunctionBody,
};
/// <summary>
/// Base class that describes a preprocessed entity, which may
/// be a preprocessor directive or macro expansion.
/// </summary>
public abstract class PreprocessedEntity : Declaration
{
public MacroLocation MacroLocation = MacroLocation.Unknown;
}
/// <summary>
/// Represents a C preprocessor macro expansion.
/// </summary>
public class MacroExpansion : PreprocessedEntity
{
// Contains the macro expansion text.
public string Text;
public MacroDefinition Definition;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
//return visitor.VisitMacroExpansion(this);
return default(T);
}
public override string ToString()
{
return Text;
}
}
/// <summary>
/// Represents a C preprocessor macro definition.
/// </summary>
public class MacroDefinition : PreprocessedEntity
{
// Contains the macro definition text.
public string Expression;
// Backing enumeration if one was generated.
public Enumeration Enumeration;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
return visitor.VisitMacroDefinition(this);
}
public override string ToString()
{
return string.Format("{0} = {1}", Name, Expression);
}
}
}
| namespace CppSharp.AST
{
public enum MacroLocation
{
Unknown,
ClassHead,
ClassBody,
FunctionHead,
FunctionParameters,
FunctionBody,
};
/// <summary>
/// Base class that describes a preprocessed entity, which may
/// be a preprocessor directive or macro expansion.
/// </summary>
public abstract class PreprocessedEntity : Declaration
{
public MacroLocation MacroLocation = MacroLocation.Unknown;
}
/// <summary>
/// Represents a C preprocessor macro expansion.
/// </summary>
public class MacroExpansion : PreprocessedEntity
{
// Contains the macro expansion text.
public string Text;
public MacroDefinition Definition;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
//return visitor.VisitMacroExpansion(this);
return default(T);
}
public override string ToString()
{
return Text;
}
}
/// <summary>
/// Represents a C preprocessor macro definition.
/// </summary>
public class MacroDefinition : PreprocessedEntity
{
// Contains the macro definition text.
public string Expression;
// Backing enumeration if one was generated.
public Enumeration Enumeration;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
return visitor.VisitMacroDefinition(this);
}
public override string ToString()
{
return Expression;
}
}
}
| mit | C# |
38592adb0daf9658c112c1245b36c5e407fd7e1f | Fix the definition of Cps<TResult, T> for Silverlight | linerlock/parseq | Parseq/Cps.cs | Parseq/Cps.cs | /*
* Parseq - a monadic parser combinator library for C#
*
* Copyright (c) 2012 - 2013 WATANABE TAKAHISA <x.linerlock@gmail.com> All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
namespace Parseq
{
#if SILVERLIGHT
public delegate TResult Cps<TResult, T>(Func<T, TResult> func);
#else
public delegate TResult Cps<TResult, out T>(Func<T, TResult> func);
#endif
}
| /*
* Parseq - a monadic parser combinator library for C#
*
* Copyright (c) 2012 - 2013 WATANABE TAKAHISA <x.linerlock@gmail.com> All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System;
namespace Parseq
{
public delegate TResult Cps<TResult, out T>(Func<T, TResult> func);
}
| mit | C# |
274a32e6475dbd2339a0d083e875eb5802bc681b | add menu logoff option | OlegKleyman/AlphaDev,OlegKleyman/AlphaDev,OlegKleyman/AlphaDev | web/AlphaDev.Web/Views/Shared/Partial/_Menu.cshtml | web/AlphaDev.Web/Views/Shared/Partial/_Menu.cshtml | <div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-area="" asp-controller="Default" asp-action="Index" class="navbar-brand">AlphaDev</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a asp-area="" asp-controller="Posts" asp-action="Index" asp-route-id="">Posts</a>
</li>
<li>
<a asp-area="" asp-controller="Info" asp-action="About">About</a>
</li>
<li>
<a asp-area="" asp-controller="Info" asp-action="Contact">Contact</a>
</li>
<display value="@User.Identity.IsAuthenticated">
<li>
<a asp-area="" asp-controller="Posts" asp-action="Create">Create Post</a>
</li>
</display>
</ul>
<display value="@User.Identity.IsAuthenticated">
<form asp-controller="Account" asp-action="Logout" method="post" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Logout</button>
</li>
</ul>
</form>
</display>
</div> | <div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-area="" asp-controller="Default" asp-action="Index" class="navbar-brand">AlphaDev</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a asp-area="" asp-controller="Posts" asp-action="Index" asp-route-id="">Posts</a>
</li>
<li>
<a asp-area="" asp-controller="Info" asp-action="About">About</a>
</li>
<li>
<a asp-area="" asp-controller="Info" asp-action="Contact">Contact</a>
</li>
<display value="@User.Identity.IsAuthenticated">
<li>
<a asp-area="" asp-controller="Posts" asp-action="Create">Create Post</a>
</li>
</display>
</ul>
</div> | unlicense | C# |
76362f36189e9ef61ba7425b8cb1d5001ad708fb | Disable test on MacOS. | dlemstra/Magick.NET,dlemstra/Magick.NET | tests/Magick.NET.Tests/Shared/Settings/MagickSettingsTests/TheFontProperty.cs | tests/Magick.NET.Tests/Shared/Settings/MagickSettingsTests/TheFontProperty.cs | // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickSettingsTests
{
public class TheFontProperty
{
[Fact]
public void ShouldSetTheFontWhenReadingImage()
{
using (var image = new MagickImage())
{
Assert.Null(image.Settings.Font);
image.Settings.Font = "Courier New";
image.Settings.FontPointsize = 40;
image.Read("pango:Test");
// Different result on MacOS
if (image.Width != 40)
{
Assert.Equal(128, image.Width);
Assert.Contains(image.Height, new[] { 58, 62 });
ColorAssert.Equal(MagickColors.Black, image, 26, 22);
}
}
}
}
}
}
| // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickSettingsTests
{
public class TheFontProperty
{
[Fact]
public void ShouldSetTheFontWhenReadingImage()
{
using (var image = new MagickImage())
{
Assert.Null(image.Settings.Font);
image.Settings.Font = "Courier New";
image.Settings.FontPointsize = 40;
image.Read("pango:Test");
Assert.Equal(128, image.Width);
Assert.Contains(image.Height, new[] { 58, 62 });
ColorAssert.Equal(MagickColors.Black, image, 26, 22);
}
}
}
}
}
| apache-2.0 | C# |
311b53957d75e0da1a0827ddfc572c795629078c | Bump to 1.9.2 | phoenixwebgroup/DotNetMongoMigrations,phoenixwebgroup/DotNetMongoMigrations | src/MongoMigrations/Properties/AssemblyInfo.cs | src/MongoMigrations/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MongoMigrations")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoMigrations")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("5eb1cfc3-0160-4c1b-9209-12e8251e686c")]
[assembly: AssemblyVersion("1.9.2.0")]
[assembly: AssemblyFileVersion("1.9.2.0")] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("MongoMigrations")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoMigrations")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("5eb1cfc3-0160-4c1b-9209-12e8251e686c")]
[assembly: AssemblyVersion("1.8.3.0")]
[assembly: AssemblyFileVersion("1.8.3.0")] | mit | C# |
9c30351e474e8a1fe315bccd520b150e78914af2 | Add GetLogger method to Logging. | eternnoir/NLogging | src/NLogging/Logging.cs | src/NLogging/Logging.cs | namespace NLogging
{
using System;
using System.Collections.Generic;
/// <summary>
/// A Logging class.
/// </summary>
public class Logging
{
/// <summary>
/// Singleton
/// </summary>
private static volatile Logging instance;
/// <summary>
/// For thread safe.
/// </summary>
private static object syncRoot = new object();
private Dictionary<string, Logger> loggerDictionary;
private Logging()
{
this.loggerDictionary = new Dictionary<string, Logger>();
}
public static Logging Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Logging();
}
}
return instance;
}
}
public Logger GetLogger(string loggerName)
{
lock (syncRoot)
{
if (!this.loggerDictionary.ContainsKey(loggerName))
{
this.loggerDictionary.Add(loggerName, new Logger(loggerName));
}
return this.loggerDictionary[loggerName];
}
}
}
} | using System;
namespace NLogging
{
public class Logging
{
private static volatile Logging instance;
private static object syncRoot = new Object();
private Logging() {}
public static Logging Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Logging();
}
}
return instance;
}
}
}
}
| mit | C# |
ae4cf0abfc1312e7c3c9513e3ddd8d4b43ce6b4d | Add more unit test filestorage | masterdidoo/LiteDB,falahati/LiteDB,89sos98/LiteDB,RytisLT/LiteDB,prepare/LiteDB,RytisLT/LiteDB,89sos98/LiteDB,prepare/LiteDB,prepare/LiteDB,falahati/LiteDB,Skysper/LiteDB,prepare/LiteDB,Xicy/LiteDB,masterdidoo/LiteDB,mbdavid/LiteDB,icelty/LiteDB | LiteDB.Tests/Crud/FileStorageTest.cs | LiteDB.Tests/Crud/FileStorageTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Linq;
using System.Text;
namespace LiteDB.Tests
{
[TestClass]
public class FileStorage_Test
{
[TestMethod]
public void FileStorage_InsertDelete()
{
// create a dump file
File.WriteAllText("Core.dll", "FileCoreContent");
using (var db = new LiteDatabase(new MemoryStream()))
{
// upload
db.FileStorage.Upload("Core.dll", "Core.dll");
// exits
var exists = db.FileStorage.Exists("Core.dll");
Assert.AreEqual(true, exists);
// find
var files = db.FileStorage.Find("Core");
Assert.AreEqual(1, files.Count());
Assert.AreEqual("Core.dll", files.First().Id);
// find by id
var core = db.FileStorage.FindById("Core.dll");
Assert.IsNotNull(core);
Assert.AreEqual("Core.dll", core.Id);
// download
var mem = new MemoryStream();
db.FileStorage.Download("Core.dll", mem);
var content = Encoding.UTF8.GetString(mem.ToArray());
Assert.AreEqual("FileCoreContent", content);
// delete
var deleted = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(true, deleted);
// not found deleted
var deleted2 = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(false, deleted2);
}
File.Delete("Core.dll");
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace LiteDB.Tests
{
[TestClass]
public class FileStorage_Test
{
[TestMethod]
public void FileStorage_InsertDelete()
{
// create a dump file
File.WriteAllText("Core.dll", "FileCoreContent");
using (var db = new LiteDatabase(new MemoryStream()))
{
db.FileStorage.Upload("Core.dll", "Core.dll");
var exists = db.FileStorage.Exists("Core.dll");
Assert.AreEqual(true, exists);
var deleted = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(true, deleted);
var deleted2 = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(false, deleted2);
}
File.Delete("Core.dll");
}
}
} | mit | C# |
9b9cf1f9c0674133d23def1bca9fa5b35617c352 | remove unused code | icehowler/ApiScanner,icehowler/ApiScanner,icehowler/ApiScanner,icehowler/ApiScanner | ApiScanner.Jobs/Startup.cs | ApiScanner.Jobs/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiScanner.DataAccess;
using ApiScanner.DataAccess.Repositories;
using ApiScanner.Entities.Enums;
using ApiScanner.Jobs.Managers;
using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ApiScanner.Jobs
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// 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)
{
// Configure DataBase contexts
CoreContext.ConnectionString = Configuration.GetConnectionString("DataAccessPostgreSqlProvider");
services.AddDbContext<CoreContext>();
services.AddTransient<IApiRepository, ApiRepository>();
services.AddTransient<IApiLogRepository, ApiLogRepository>();
services.AddHangfire(c => c.UseMemoryStorage());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
app.UseHangfireDashboard("/hangfire");
app.UseHangfireServer();
RecurringJob.AddOrUpdate<HourlyApisJob>("HourlyApis", x => x.ExecuteJobAsync(ApiInterval.Hourly), Cron.Hourly);
RecurringJob.AddOrUpdate<HourlyApisJob>("DailyApis", x => x.ExecuteJobAsync(ApiInterval.Daily), Cron.Daily);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("ApiScanner jobs. Navigate to /hangfire for dashboard.");
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiScanner.DataAccess;
using ApiScanner.DataAccess.Repositories;
using ApiScanner.Entities.Enums;
using ApiScanner.Jobs.Managers;
using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ApiScanner.Jobs
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// 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)
{
// Configure DataBase contexts
CoreContext.ConnectionString = Configuration.GetConnectionString("DataAccessPostgreSqlProvider");
services.AddDbContext<CoreContext>();
services.AddTransient<IApiRepository, ApiRepository>();
services.AddTransient<IApiLogRepository, ApiLogRepository>();
services.AddHangfire(c => c.UseMemoryStorage());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
//GlobalConfiguration.Configuration.UseActivator(new HangfireActivator(serviceProvider));
app.UseHangfireDashboard("/hangfire");
app.UseHangfireServer();
RecurringJob.AddOrUpdate<HourlyApisJob>("HourlyApis", x => x.ExecuteJobAsync(ApiInterval.Hourly), Cron.Hourly);
RecurringJob.AddOrUpdate<HourlyApisJob>("DailyApis", x => x.ExecuteJobAsync(ApiInterval.Daily), Cron.Daily);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("ApiScanner jobs. Navigate to /hangfire for dashboard.");
});
}
}
}
| mit | C# |
6716f02efe702e363d9aaf191a6c16e6050fc8ac | Add json serializer test on sub satoshi feeRate | NicolasDorier/NBitcoin,MetacoSA/NBitcoin,MetacoSA/NBitcoin | NBitcoin.Tests/JsonConverterTests.cs | NBitcoin.Tests/JsonConverterTests.cs | using NBitcoin.JsonConverters;
using NBitcoin.OpenAsset;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace NBitcoin.Tests
{
public class JsonConverterTests
{
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanSerializeInJson()
{
Key k = new Key();
CanSerializeInJsonCore(DateTimeOffset.UtcNow);
CanSerializeInJsonCore(new byte[] { 1, 2, 3 });
CanSerializeInJsonCore(k);
CanSerializeInJsonCore(Money.Coins(5.0m));
CanSerializeInJsonCore(k.PubKey.GetAddress(Network.Main));
CanSerializeInJsonCore(new KeyPath("1/2"));
CanSerializeInJsonCore(Network.Main);
CanSerializeInJsonCore(new uint256(RandomUtils.GetBytes(32)));
CanSerializeInJsonCore(new uint160(RandomUtils.GetBytes(20)));
CanSerializeInJsonCore(new AssetId(k.PubKey));
CanSerializeInJsonCore(k.PubKey.ScriptPubKey);
CanSerializeInJsonCore(new Key().PubKey.WitHash.GetAddress(Network.Main));
CanSerializeInJsonCore(new Key().PubKey.WitHash.ScriptPubKey.GetWitScriptAddress(Network.Main));
var sig = k.Sign(new uint256(RandomUtils.GetBytes(32)));
CanSerializeInJsonCore(sig);
CanSerializeInJsonCore(new TransactionSignature(sig, SigHash.All));
CanSerializeInJsonCore(k.PubKey.Hash);
CanSerializeInJsonCore(k.PubKey.ScriptPubKey.Hash);
CanSerializeInJsonCore(k.PubKey.WitHash);
CanSerializeInJsonCore(k);
CanSerializeInJsonCore(k.PubKey);
CanSerializeInJsonCore(new WitScript(new Script(Op.GetPushOp(sig.ToDER()), Op.GetPushOp(sig.ToDER()))));
CanSerializeInJsonCore(new LockTime(1));
CanSerializeInJsonCore(new LockTime(130), out var str);
Assert.Equal("130", str);
CanSerializeInJsonCore(new LockTime(DateTime.UtcNow));
CanSerializeInJsonCore(new FeeRate(Money.Satoshis(1), 1000));
CanSerializeInJsonCore(new FeeRate(Money.Satoshis(1000), 1000));
CanSerializeInJsonCore(new FeeRate(0.5m));
}
private T CanSerializeInJsonCore<T>(T value)
{
var str = Serializer.ToString(value);
var obj2 = Serializer.ToObject<T>(str);
Assert.Equal(str, Serializer.ToString(obj2));
return obj2;
}
private T CanSerializeInJsonCore<T>(T value, out string str)
{
str = Serializer.ToString(value);
var obj2 = Serializer.ToObject<T>(str);
Assert.Equal(str, Serializer.ToString(obj2));
return obj2;
}
}
}
| using NBitcoin.JsonConverters;
using NBitcoin.OpenAsset;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace NBitcoin.Tests
{
public class JsonConverterTests
{
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanSerializeInJson()
{
Key k = new Key();
CanSerializeInJsonCore(DateTimeOffset.UtcNow);
CanSerializeInJsonCore(new byte[] { 1, 2, 3 });
CanSerializeInJsonCore(k);
CanSerializeInJsonCore(Money.Coins(5.0m));
CanSerializeInJsonCore(k.PubKey.GetAddress(Network.Main));
CanSerializeInJsonCore(new KeyPath("1/2"));
CanSerializeInJsonCore(Network.Main);
CanSerializeInJsonCore(new uint256(RandomUtils.GetBytes(32)));
CanSerializeInJsonCore(new uint160(RandomUtils.GetBytes(20)));
CanSerializeInJsonCore(new AssetId(k.PubKey));
CanSerializeInJsonCore(k.PubKey.ScriptPubKey);
CanSerializeInJsonCore(new Key().PubKey.WitHash.GetAddress(Network.Main));
CanSerializeInJsonCore(new Key().PubKey.WitHash.ScriptPubKey.GetWitScriptAddress(Network.Main));
var sig = k.Sign(new uint256(RandomUtils.GetBytes(32)));
CanSerializeInJsonCore(sig);
CanSerializeInJsonCore(new TransactionSignature(sig, SigHash.All));
CanSerializeInJsonCore(k.PubKey.Hash);
CanSerializeInJsonCore(k.PubKey.ScriptPubKey.Hash);
CanSerializeInJsonCore(k.PubKey.WitHash);
CanSerializeInJsonCore(k);
CanSerializeInJsonCore(k.PubKey);
CanSerializeInJsonCore(new WitScript(new Script(Op.GetPushOp(sig.ToDER()), Op.GetPushOp(sig.ToDER()))));
CanSerializeInJsonCore(new LockTime(1));
CanSerializeInJsonCore(new LockTime(130), out var str);
Assert.Equal("130", str);
CanSerializeInJsonCore(new LockTime(DateTime.UtcNow));
CanSerializeInJsonCore(new FeeRate(Money.Satoshis(1), 1000));
CanSerializeInJsonCore(new FeeRate(Money.Satoshis(1000), 1000));
}
private T CanSerializeInJsonCore<T>(T value)
{
var str = Serializer.ToString(value);
var obj2 = Serializer.ToObject<T>(str);
Assert.Equal(str, Serializer.ToString(obj2));
return obj2;
}
private T CanSerializeInJsonCore<T>(T value, out string str)
{
str = Serializer.ToString(value);
var obj2 = Serializer.ToObject<T>(str);
Assert.Equal(str, Serializer.ToString(obj2));
return obj2;
}
}
}
| mit | C# |
8dd97a36a3b725774477aa087ed0660b83955c2b | Update Viktor.cs | FireBuddy/adevade | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
. var End = new vector3();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
. var End = sender.GetWaypoints().Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| mit | C# |
97da228179c72a6a3414b82abb246b0207db3f8d | Make it easier to pass an array of properties | MCGPPeters/Eru,MCGPPeters/Eru | src/Eru/Validation/Validation.cs | src/Eru/Validation/Validation.cs | namespace Eru.Validation
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class Validation
{
private static Either<TCauseIdentifier[], TRight> Assert<TRight, TCauseIdentifier>(TRight source,
params Property<TCauseIdentifier, TRight>[] properties)
{
var propertiesThatDoNotHold = properties
.Where(rule => !rule.Holds(source))
.Select(rule => rule.Identifier)
.ToArray();
return propertiesThatDoNotHold.Any()
? Either<TCauseIdentifier[], TRight>.Create(propertiesThatDoNotHold)
: Either<TCauseIdentifier[], TRight>.Create(source);
}
public static Either<TCauseIdentifier[], TRight> Check<TRight, TCauseIdentifier>(
this Either<TCauseIdentifier[], TRight> source,
params Property<TCauseIdentifier, TRight>[] properties)
{
return source.Bind(right => Assert(right, properties));
}
public static Either<TCauseIdentifier[], TRight> Check<TRight, TCauseIdentifier>(this TRight source,
params Property<TCauseIdentifier, TRight>[] properties)
{
return Check(source.Return<TCauseIdentifier[], TRight>(), properties);
}
public static Either<string[], TRight> Check<TRight>(this TRight source,
string cause,
params Predicate<TRight>[] rules)
{
return Check(source.Return<string[], TRight>(),
rules.Select(predicate => new Property<string, TRight>(cause, predicate)).ToArray());
}
public static Either<string[], TRight> Check<TRight>(this Either<string[], TRight> source,
string cause,
params Predicate<TRight>[] rules)
{
return Check(source, rules.Select(predicate => new Property<string, TRight>(cause, predicate)).ToArray());
}
}
} | namespace Eru.Validation
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class Validation
{
private static Either<TCauseIdentifier[], TRight> Assert<TRight, TCauseIdentifier>(TRight source,
IEnumerable<Property<TCauseIdentifier, TRight>> properties)
{
var propertiesThatDoNotHold = properties
.Where(rule => !rule.Holds(source))
.Select(rule => rule.Identifier)
.ToArray();
return propertiesThatDoNotHold.Any()
? Either<TCauseIdentifier[], TRight>.Create(propertiesThatDoNotHold)
: Either<TCauseIdentifier[], TRight>.Create(source);
}
public static Either<TCauseIdentifier[], TRight> Check<TRight, TCauseIdentifier>(
this Either<TCauseIdentifier[], TRight> source,
IEnumerable<Property<TCauseIdentifier, TRight>> properties)
{
return source.Bind(right => Assert(right, properties));
}
public static Either<TCauseIdentifier[], TRight> Check<TRight, TCauseIdentifier>(this TRight source,
IEnumerable<Property<TCauseIdentifier, TRight>> properties)
{
return Check(source.Return<TCauseIdentifier[], TRight>(), properties);
}
public static Either<string[], TRight> Check<TRight>(this TRight source,
string cause,
params Predicate<TRight>[] rules)
{
return Check(source.Return<string[], TRight>(),
rules.Select(predicate => new Property<string, TRight>(cause, predicate)));
}
public static Either<string[], TRight> Check<TRight>(this Either<string[], TRight> source,
string cause,
params Predicate<TRight>[] rules)
{
return Check(source, rules.Select(predicate => new Property<string, TRight>(cause, predicate)));
}
}
} | mit | C# |
cc28cc0e08aa1c216f2d641529bb242793533199 | Support for two argument execute | cybergen/bri-lib | Assets/BriLib/Scripts/Extension/StaticExtensions.cs | Assets/BriLib/Scripts/Extension/StaticExtensions.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace BriLib
{
public static class StaticExtensions
{
public static void ForEach(this IEnumerable list, Action<object> action)
{
for (var enumerator = list.GetEnumerator(); enumerator.MoveNext();)
{
action.Execute(enumerator.Current);
}
}
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
for (var enumerator = list.GetEnumerator(); enumerator.MoveNext();)
{
action.Execute(enumerator.Current);
}
}
public static void Execute(this Action action)
{
if (action != null) { action(); }
}
public static void Execute<T>(this Action<T> action, T obj)
{
if (action != null) { action(obj); }
}
public static void Execute<T, K>(this Action<T, K> action, T objOne, K objTwo)
{
if (action != null) { action(objOne, objTwo); }
}
public static void Execute<T, K, L>(this Action<T, K, L> action, T objOne, K objTwo, L objThree)
{
if (action != null) { action(objOne, objTwo, objThree); }
}
public static void Execute<T, K, L, M>(this Action<T, K, L, M> action, T objOne, K objTwo, L objThree, M objFour)
{
if (action != null) { action(objOne, objTwo, objThree, objFour); }
}
public static float Sq(this float value)
{
return value * value;
}
public static double Sq(this double value)
{
return value * value;
}
public static float Sqrt(this float value)
{
return (float)Math.Sqrt(value);
}
public static double Sqrt(this double value)
{
return Math.Sqrt(value);
}
public static float MapRange(this float currValue, float fromStart, float toStart, float fromEnd, float toEnd)
{
return (currValue - fromStart) / (toStart - fromStart) * (toEnd - fromEnd) + fromEnd;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
namespace BriLib
{
public static class StaticExtensions
{
public static void ForEach(this IEnumerable list, Action<object> action)
{
for (var enumerator = list.GetEnumerator(); enumerator.MoveNext();)
{
action.Execute(enumerator.Current);
}
}
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
for (var enumerator = list.GetEnumerator(); enumerator.MoveNext();)
{
action.Execute(enumerator.Current);
}
}
public static void Execute(this Action action)
{
if (action != null) { action(); }
}
public static void Execute<T>(this Action<T> action, T obj)
{
if (action != null) { action(obj); }
}
public static void Execute<T, K, L>(this Action<T, K, L> action, T objOne, K objTwo, L objThree)
{
if (action != null) { action(objOne, objTwo, objThree); }
}
public static void Execute<T, K, L, M>(this Action<T, K, L, M> action, T objOne, K objTwo, L objThree, M objFour)
{
if (action != null) { action(objOne, objTwo, objThree, objFour); }
}
public static float Sq(this float value)
{
return value * value;
}
public static double Sq(this double value)
{
return value * value;
}
public static float Sqrt(this float value)
{
return (float)Math.Sqrt(value);
}
public static double Sqrt(this double value)
{
return Math.Sqrt(value);
}
public static float MapRange(this float currValue, float fromStart, float toStart, float fromEnd, float toEnd)
{
return (currValue - fromStart) / (toStart - fromStart) * (toEnd - fromEnd) + fromEnd;
}
}
}
| mit | C# |
121ec680955e4f54f27bb78c1afeeefe4f76efed | Add edit box for eval status | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Evaluations/Edit.cshtml | Battery-Commander.Web/Views/Evaluations/Edit.cshtml | @model Evaluation
@using (Html.BeginForm("Save", "Evaluations", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Status)
@Html.DropDownListFor(model => model.Status, Html.GetEnumSelectList<EvaluationStatus>())
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Ratee)
@Html.DropDownListFor(model => model.RateeId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")
@Html.ActionLink("Add", "New", "Soldiers")
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Rater)
@Html.DropDownListFor(model => model.RaterId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")
@Html.ActionLink("Add", "New", "Soldiers")
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.SeniorRater)
@Html.DropDownListFor(model => model.SeniorRaterId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")
@Html.ActionLink("Add", "New", "Soldiers")
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.EvaluationId)
@Html.EditorFor(model => model.EvaluationId)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.StartDate)
@Html.EditorFor(model => model.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.ThruDate)
@Html.EditorFor(model => model.ThruDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Type)
@Html.DropDownListFor(model => model.Type, Html.GetEnumSelectList<EvaluationType>())
</div>
<button type="submit">Save</button>
} | @model Evaluation
@using (Html.BeginForm("Save", "Evaluations", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Ratee)
@Html.DropDownListFor(model => model.RateeId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")
@Html.ActionLink("Add", "New", "Soldiers")
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Rater)
@Html.DropDownListFor(model => model.RaterId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")
@Html.ActionLink("Add", "New", "Soldiers")
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.SeniorRater)
@Html.DropDownListFor(model => model.SeniorRaterId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --")
@Html.ActionLink("Add", "New", "Soldiers")
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.EvaluationId)
@Html.EditorFor(model => model.EvaluationId)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.StartDate)
@Html.EditorFor(model => model.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.ThruDate)
@Html.EditorFor(model => model.ThruDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Type)
@Html.DropDownListFor(model => model.Type, Html.GetEnumSelectList<EvaluationType>())
</div>
<button type="submit">Save</button>
} | mit | C# |
34af213c83b740d14689d2ba0a181fea6ad57681 | merge and remove ExecuteFirstCommand method | li-rongcheng/CoreCmd | CoreCmd/CommandExecution/AssemblyCommandExecutor.cs | CoreCmd/CommandExecution/AssemblyCommandExecutor.cs | using CoreCmd.CommandLoading;
using CoreCmd.Help;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace CoreCmd.CommandExecution
{
public interface IAssemblyCommandExecutor
{
void Execute(string[] args);
}
public class AssemblyCommandExecutor : IAssemblyCommandExecutor
{
public List<Assembly> additionalAssemblies = new List<Assembly>();
public void SetAdditionalSearchAssembly(Assembly assembly)
{
this.additionalAssemblies.Add(assembly);
}
public AssemblyCommandExecutor() { }
public AssemblyCommandExecutor(params Type[] types)
{
if (types != null)
{
foreach(var type in types)
this.SetAdditionalSearchAssembly(Assembly.GetAssembly(type));
}
}
public void Execute(string[] args)
{
ICommandClassLoader _loader = new CommandClassLoader();
ICommandExecutorCreate _commandFinder = new CommandExecutorCreator();
try
{
var allClassTypes = _loader.LoadAllCommandClasses(additionalAssemblies);
if (args.Length > 0)
{
var singleCommandExecutor = _commandFinder.GetSingleCommandExecutor(allClassTypes, args);
if (singleCommandExecutor != null)
singleCommandExecutor.Execute();
}
else
PrintHelpMessage(allClassTypes);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintHelpMessage(IEnumerable<Type> allClassTypes)
{
IHelpInfoService _helpSvc = new HelpInfoService();
Console.WriteLine("Subcommand is missing, please specify subcommands:");
foreach (var cmd in allClassTypes) // print all available commands
_helpSvc.PrintClassHelp(cmd);
}
}
}
| using CoreCmd.CommandLoading;
using CoreCmd.Help;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace CoreCmd.CommandExecution
{
public interface IAssemblyCommandExecutor
{
void Execute(string[] args);
}
public class AssemblyCommandExecutor : IAssemblyCommandExecutor
{
public List<Assembly> additionalAssemblies = new List<Assembly>();
public void SetAdditionalSearchAssembly(Assembly assembly)
{
this.additionalAssemblies.Add(assembly);
}
public AssemblyCommandExecutor() { }
public AssemblyCommandExecutor(params Type[] types)
{
if (types != null)
{
foreach(var type in types)
this.SetAdditionalSearchAssembly(Assembly.GetAssembly(type));
}
}
public void Execute(string[] args)
{
try
{
ICommandClassLoader _loader = new CommandClassLoader();
var allClassTypes = _loader.LoadAllCommandClasses(additionalAssemblies);
if (args.Length > 0)
ExecuteFirstCommand(allClassTypes, args);
else
PrintHelpMessage(allClassTypes);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void ExecuteFirstCommand(IEnumerable<Type> allClassTypes, string[] args)
{
ICommandExecutorCreate _commandFinder = new CommandExecutorCreator();
var singleCommandExecutor = _commandFinder.GetSingleCommandExecutor(allClassTypes, args);
if (singleCommandExecutor != null)
singleCommandExecutor.Execute();
}
private void PrintHelpMessage(IEnumerable<Type> allClassTypes)
{
IHelpInfoService _helpSvc = new HelpInfoService();
Console.WriteLine("Subcommand is missing, please specify subcommands:");
foreach (var cmd in allClassTypes) // print all available commands
_helpSvc.PrintClassHelp(cmd);
}
}
}
| mit | C# |
eb7012c83503761a4a7b38bda0d6843fa3f16c96 | update version number | spring-projects/spring-net,kvr000/spring-net,yonglehou/spring-net,spring-projects/spring-net,likesea/spring-net,kvr000/spring-net,djechelon/spring-net,yonglehou/spring-net,dreamofei/spring-net,likesea/spring-net,yonglehou/spring-net,likesea/spring-net,spring-projects/spring-net,zi1jing/spring-net,zi1jing/spring-net,dreamofei/spring-net,kvr000/spring-net,djechelon/spring-net | src/Spring/CommonAssemblyInfo.cs | src/Spring/CommonAssemblyInfo.cs | using System;
using System.Reflection;
[assembly: CLSCompliant(false)]
//
// 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.
//
#if !NET_2_0
[assembly: AssemblyConfiguration("net-1.1.win32; Release")]
#else
[assembly: AssemblyConfiguration("net-2.0.win32; Release")]
#endif
[assembly: AssemblyCompany("http://www.springframework.net")]
[assembly: AssemblyProduct("Spring.NET Framework 1.2.0")]
[assembly: AssemblyCopyright("Copyright 2002-2008 Spring.NET Framework Team.")]
[assembly: AssemblyTrademark("Apache License, Version 2.0")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// .NET Framework Version (RR)
// Revision = "1" for builds with VS.NET, nant build is # of days since 'project.year'
// property
//
//
// This is to support side-by-side deployment of .NET 1.1 and .NET 2.0 versions of the assembly.
#if !NET_2_0
[assembly: AssemblyVersion("1.2.0.11001")]
#else
[assembly: AssemblyVersion("1.2.0.20001")]
#endif
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
#if STRONG
[assembly: AssemblyDelaySign(false)]
#if !NET_2_0
[assembly: AssemblyKeyFile("Spring.Net.snk")]
#endif
#endif
| using System;
using System.Reflection;
[assembly: CLSCompliant(false)]
//
// 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.
//
#if !NET_2_0
[assembly: AssemblyConfiguration("net-1.1.win32; Release")]
#else
[assembly: AssemblyConfiguration("net-2.0.win32; Release")]
#endif
[assembly: AssemblyCompany("http://www.springframework.net")]
[assembly: AssemblyProduct("Spring.NET Framework 1.2.0 RC1")]
[assembly: AssemblyCopyright("Copyright 2002-2007 Spring.NET Framework Team.")]
[assembly: AssemblyTrademark("Apache License, Version 2.0")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// .NET Framework Version (RR)
// Revision = "1" for builds with VS.NET, nant build is # of days since 'project.year'
// property
//
//
// This is to support side-by-side deployment of .NET 1.1 and .NET 2.0 versions of the assembly.
#if !NET_2_0
[assembly: AssemblyVersion("1.2.0.11001")]
#else
[assembly: AssemblyVersion("1.2.0.20001")]
#endif
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
#if STRONG
[assembly: AssemblyDelaySign(false)]
#if !NET_2_0
[assembly: AssemblyKeyFile("Spring.Net.snk")]
#endif
#endif
| apache-2.0 | C# |
ad43ead69b700a8a6e9c2588944aae56ab183bab | Fix copy paste naming error | kali786516/kudu,juoni/kudu,kenegozi/kudu,YOTOV-LIMITED/kudu,chrisrpatterson/kudu,mauricionr/kudu,dev-enthusiast/kudu,barnyp/kudu,kenegozi/kudu,projectkudu/kudu,dev-enthusiast/kudu,juvchan/kudu,barnyp/kudu,shibayan/kudu,chrisrpatterson/kudu,dev-enthusiast/kudu,puneet-gupta/kudu,projectkudu/kudu,barnyp/kudu,puneet-gupta/kudu,juoni/kudu,uQr/kudu,kali786516/kudu,MavenRain/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,juoni/kudu,shrimpy/kudu,duncansmart/kudu,shibayan/kudu,sitereactor/kudu,shibayan/kudu,projectkudu/kudu,chrisrpatterson/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,juoni/kudu,badescuga/kudu,bbauya/kudu,badescuga/kudu,shrimpy/kudu,duncansmart/kudu,MavenRain/kudu,kali786516/kudu,barnyp/kudu,sitereactor/kudu,chrisrpatterson/kudu,oliver-feng/kudu,uQr/kudu,EricSten-MSFT/kudu,uQr/kudu,duncansmart/kudu,badescuga/kudu,shrimpy/kudu,oliver-feng/kudu,oliver-feng/kudu,bbauya/kudu,puneet-gupta/kudu,sitereactor/kudu,shrimpy/kudu,puneet-gupta/kudu,duncansmart/kudu,kenegozi/kudu,YOTOV-LIMITED/kudu,sitereactor/kudu,MavenRain/kudu,mauricionr/kudu,juvchan/kudu,EricSten-MSFT/kudu,dev-enthusiast/kudu,mauricionr/kudu,juvchan/kudu,projectkudu/kudu,sitereactor/kudu,shibayan/kudu,shibayan/kudu,kenegozi/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,projectkudu/kudu,puneet-gupta/kudu,juvchan/kudu,MavenRain/kudu,juvchan/kudu,EricSten-MSFT/kudu,bbauya/kudu,kali786516/kudu,mauricionr/kudu,uQr/kudu,oliver-feng/kudu,bbauya/kudu | Kudu.Core.Test/Deployment/PythonSiteEnablerTests.cs | Kudu.Core.Test/Deployment/PythonSiteEnablerTests.cs | using System;
using System.IO.Abstractions;
using Kudu.Core.Infrastructure;
using Moq;
using Xunit;
using Xunit.Extensions;
namespace Kudu.Core.Deployment.Generator.Test
{
public class PythonSiteEnablerTests
{
[Theory]
[InlineData(true, new string[] { "requirements.txt" })]
[InlineData(true, new string[] { "requirements.txt", "default.asp" })]
[InlineData(true, new string[] { "requirements.txt", "site.aspx" })]
[InlineData(false, new string[0])]
[InlineData(false, new string[] { "index.php" })]
[InlineData(false, new string[] { "site.aspx" })]
[InlineData(false, new string[] { "site.aspx", "index2.aspx" })]
[InlineData(false, new string[] { "server.js" })]
[InlineData(false, new string[] { "app.js" })]
[InlineData(false, new string[] { "package.json" })]
public void TestLooksLikePython(bool looksLikePythonExpectedResult, string[] existingFiles)
{
Console.WriteLine("Testing: {0}", String.Join(", ", existingFiles));
var fileMock = new Mock<FileBase>();
var fileSystemMock = new Mock<IFileSystem>();
foreach (var existingFile in existingFiles)
{
fileMock.Setup(f => f.Exists("site\\" + existingFile)).Returns(true);
}
fileSystemMock.Setup(f => f.File).Returns(fileMock.Object);
FileSystemHelpers.Instance = fileSystemMock.Object;
bool looksLikePythonResult = PythonSiteEnabler.LooksLikePython("site");
Assert.Equal(looksLikePythonExpectedResult, looksLikePythonResult);
}
}
}
| using System;
using System.IO.Abstractions;
using Kudu.Core.Infrastructure;
using Moq;
using Xunit;
using Xunit.Extensions;
namespace Kudu.Core.Deployment.Generator.Test
{
public class PythonSiteEnablerTests
{
[Theory]
[InlineData(true, new string[] { "requirements.txt" })]
[InlineData(true, new string[] { "requirements.txt", "default.asp" })]
[InlineData(true, new string[] { "requirements.txt", "site.aspx" })]
[InlineData(false, new string[0])]
[InlineData(false, new string[] { "index.php" })]
[InlineData(false, new string[] { "site.aspx" })]
[InlineData(false, new string[] { "site.aspx", "index2.aspx" })]
[InlineData(false, new string[] { "server.js" })]
[InlineData(false, new string[] { "app.js" })]
[InlineData(false, new string[] { "package.json" })]
public void TestLooksLikePython(bool looksLikePythonExpectedResult, string[] existingFiles)
{
Console.WriteLine("Testing: {0}", String.Join(", ", existingFiles));
var fileMock = new Mock<FileBase>();
var fileSystemMock = new Mock<IFileSystem>();
foreach (var existingFile in existingFiles)
{
fileMock.Setup(f => f.Exists("site\\" + existingFile)).Returns(true);
}
fileSystemMock.Setup(f => f.File).Returns(fileMock.Object);
FileSystemHelpers.Instance = fileSystemMock.Object;
bool looksLikeNodeResult = PythonSiteEnabler.LooksLikePython("site");
Assert.Equal(looksLikePythonExpectedResult, looksLikeNodeResult);
}
}
}
| apache-2.0 | C# |
f71697720eca4111e3d829c27b6117fbb05b9084 | Update prerelease version to v1.0.0. Resolves #17 | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Properties/AssemblyInfo.cs | Source/Lib/TraktApiSharp/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("TraktApiSharp.PreNextVersion.Tests")]
[assembly: InternalsVisibleTo("TraktApiSharp.Tests")]
[assembly: AssemblyTitle("TraktApiSharp")]
[assembly: AssemblyDescription(".NET wrapper library for the Trakt.tv API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Fröhling")]
[assembly: AssemblyProduct("TraktApiSharp")]
[assembly: AssemblyCopyright("Copyright © 2016 - 2017 Henrik Fröhling")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("TraktApiSharp.PreNextVersion.Tests")]
[assembly: InternalsVisibleTo("TraktApiSharp.Tests")]
[assembly: AssemblyTitle("TraktApiSharp")]
[assembly: AssemblyDescription(".NET wrapper library for the Trakt.tv API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Fröhling")]
[assembly: AssemblyProduct("TraktApiSharp")]
[assembly: AssemblyCopyright("Copyright © 2016 - 2017 Henrik Fröhling")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
| mit | C# |
c642d0d878f802d22b943bd0b2015576482a34ee | Remove unused variable. | NguyenMatthieu/f-spot,dkoeb/f-spot,mans0954/f-spot,dkoeb/f-spot,Yetangitu/f-spot,mono/f-spot,GNOME/f-spot,dkoeb/f-spot,Sanva/f-spot,mans0954/f-spot,mono/f-spot,dkoeb/f-spot,Sanva/f-spot,Yetangitu/f-spot,GNOME/f-spot,NguyenMatthieu/f-spot,mono/f-spot,GNOME/f-spot,Yetangitu/f-spot,mono/f-spot,Yetangitu/f-spot,mans0954/f-spot,nathansamson/F-Spot-Album-Exporter,NguyenMatthieu/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,mans0954/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,GNOME/f-spot,Sanva/f-spot,dkoeb/f-spot,Sanva/f-spot,dkoeb/f-spot,GNOME/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot,Sanva/f-spot,nathansamson/F-Spot-Album-Exporter,mono/f-spot | extensions/Editors/ResizeEditor/ResizeEditor.cs | extensions/Editors/ResizeEditor/ResizeEditor.cs | /*
* ResizeEditor.cs
*
* Author(s)
* Stephane Delcroix (stephane@delcroix.org)
*
* This is free software. See COPYING for details.
*/
using System;
using FSpot;
using FSpot.Editors;
using Gtk;
using Gdk;
using Mono.Unix;
namespace FSpot.Addins.Editors {
class ResizeEditor : Editor {
SpinButton size;
public ResizeEditor () : base (Catalog.GetString ("Resize"), null) {
CanHandleMultiple = false;
HasSettings = true;
}
protected override Pixbuf Process (Pixbuf input, Cms.Profile input_profile)
{
Pixbuf output = (Pixbuf) input.Clone ();
double ratio = (double)size.Value / Math.Max (output.Width, output.Height);
return output.ScaleSimple ((int)(output.Width * ratio), (int)(output.Height * ratio), InterpType.Bilinear);
}
public override Widget ConfigurationWidget ()
{
int max;
using (ImageFile img = ImageFile.Create (State.Items[0].DefaultVersionUri))
using (Pixbuf p = img.Load ())
max = Math.Max (p.Width, p.Height);
size = new SpinButton (128, max, 10);
size.Value = max;
return size;
}
}
}
| /*
* ResizeEditor.cs
*
* Author(s)
* Stephane Delcroix (stephane@delcroix.org)
*
* This is free software. See COPYING for details.
*/
using System;
using FSpot;
using FSpot.Editors;
using Gtk;
using Gdk;
using Mono.Unix;
namespace FSpot.Addins.Editors {
class ResizeEditor : Editor {
double ratio;
SpinButton size;
public ResizeEditor () : base (Catalog.GetString ("Resize"), null) {
CanHandleMultiple = false;
HasSettings = true;
}
protected override Pixbuf Process (Pixbuf input, Cms.Profile input_profile)
{
Pixbuf output = (Pixbuf) input.Clone ();
double ratio = (double)size.Value / Math.Max (output.Width, output.Height);
return output.ScaleSimple ((int)(output.Width * ratio), (int)(output.Height * ratio), InterpType.Bilinear);
}
public override Widget ConfigurationWidget ()
{
int max;
using (ImageFile img = ImageFile.Create (State.Items[0].DefaultVersionUri))
using (Pixbuf p = img.Load ())
max = Math.Max (p.Width, p.Height);
size = new SpinButton (128, max, 10);
size.Value = max;
return size;
}
}
}
| mit | C# |
5affc52afec5f84b1c5d8999675d21cfa17688d2 | Update CompositeStringLocalizer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Localization/CompositeStringLocalizer.cs | TIKSN.Core/Localization/CompositeStringLocalizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Localization;
namespace TIKSN.Localization
{
public class CompositeStringLocalizer : IStringLocalizer
{
public CompositeStringLocalizer(IEnumerable<IStringLocalizer> localizers) => this.Localizers = localizers;
protected CompositeStringLocalizer()
{
}
public virtual IEnumerable<IStringLocalizer> Localizers { get; }
public LocalizedString this[string name] => this.GetLocalizedString(l => l[name]);
public LocalizedString this[string name, params object[] arguments] =>
this.GetLocalizedString(l => l[name, arguments]);
public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
{
var localizedStrings = new List<LocalizedString>();
foreach (var localizer in this.Localizers)
{
localizedStrings.AddRange(localizer.GetAllStrings(includeParentCultures));
}
return localizedStrings;
}
private LocalizedString GetLocalizedString(Func<IStringLocalizer, LocalizedString> singleLocalizer)
{
var localizedStrings = this.Localizers.Select(localizer => singleLocalizer(localizer)).ToArray();
var localizableStrings = localizedStrings.Where(item => !item.ResourceNotFound && item.Name != item.Value)
.ToArray();
if (localizableStrings.Length > 0)
{
return localizableStrings.First();
}
return localizedStrings.First();
}
}
}
| using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace TIKSN.Localization
{
public class CompositeStringLocalizer : IStringLocalizer
{
public CompositeStringLocalizer(IEnumerable<IStringLocalizer> localizers)
{
Localizers = localizers;
}
protected CompositeStringLocalizer()
{
}
public virtual IEnumerable<IStringLocalizer> Localizers { get; }
public LocalizedString this[string name]
{
get
{
return GetLocalizedString(l => l[name]);
}
}
public LocalizedString this[string name, params object[] arguments]
{
get
{
return GetLocalizedString(l => l[name, arguments]);
}
}
public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
{
var localizedStrings = new List<LocalizedString>();
foreach (var localizer in Localizers)
{
localizedStrings.AddRange(localizer.GetAllStrings(includeParentCultures));
}
return localizedStrings;
}
private LocalizedString GetLocalizedString(Func<IStringLocalizer, LocalizedString> singleLocalizer)
{
var localizedStrings = Localizers.Select(localizer => singleLocalizer(localizer)).ToArray();
var localizableStrings = localizedStrings.Where(item => !item.ResourceNotFound && item.Name != item.Value).ToArray();
if (localizableStrings.Length > 0)
return localizableStrings.First();
return localizedStrings.First();
}
}
} | mit | C# |
716fe06ddde19b19c0c85250bd7dc587cff4480e | Fix inverted assert condition. | peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk | wrappers/dotnet/indy-sdk-dotnet/Utils/PendingCommands.cs | wrappers/dotnet/indy-sdk-dotnet/Utils/PendingCommands.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Utils
{
/// <summary>
/// Holder for pending commands.
/// </summary>
internal static class PendingCommands
{
/// <summary>
/// The next command handle to use.
/// </summary>
private static int _nextCommandHandle = 0;
/// <summary>
/// Gets the next command handle.
/// </summary>
/// <returns>The next command handle.</returns>
public static int GetNextCommandHandle()
{
return Interlocked.Increment(ref _nextCommandHandle);
}
/// <summary>
/// Gets the map of command handles and their task completion sources.
/// </summary>
private static IDictionary<int, object> _taskCompletionSources = new ConcurrentDictionary<int, object>();
/// <summary>
/// Adds a new TaskCompletionSource to track.
/// </summary>
/// <typeparam name="T">The type of the TaskCompletionSource result.</typeparam>
/// <param name="taskCompletionSource">The TaskCompletionSource to track.</param>
/// <returns>The command handle to use for tracking the task completion source.</returns>
public static int Add<T>(TaskCompletionSource<T> taskCompletionSource)
{
Debug.Assert(taskCompletionSource != null, "A task completion source is required.");
var commandHandle = GetNextCommandHandle();
_taskCompletionSources.Add(commandHandle, taskCompletionSource);
return commandHandle;
}
/// <summary>
/// Gets and removes a TaskCompletionResult from tracking.
/// </summary>
/// <typeparam name="T">The type of the TaskCompletionResult that was tracked.</typeparam>
/// <param name="commandHandle">The command handle used for tracking the TaskCompletionResult.</param>
/// <returns>The TaskCompletionResult associated with the command handle.</returns>
public static TaskCompletionSource<T> Remove<T>(int commandHandle)
{
Debug.Assert(_taskCompletionSources.ContainsKey(commandHandle), string.Format("No task completion source is currently registered for the command with the handle '{0}'.", commandHandle));
var taskCompletionSource = _taskCompletionSources[commandHandle];
_taskCompletionSources.Remove(commandHandle);
var result = taskCompletionSource as TaskCompletionSource<T>;
Debug.Assert(result != null, string.Format("No task completion source of the specified type is registered for the command with the handle '{0}'.", commandHandle));
return result;
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Utils
{
/// <summary>
/// Holder for pending commands.
/// </summary>
internal static class PendingCommands
{
/// <summary>
/// The next command handle to use.
/// </summary>
private static int _nextCommandHandle = 0;
/// <summary>
/// Gets the next command handle.
/// </summary>
/// <returns>The next command handle.</returns>
public static int GetNextCommandHandle()
{
return Interlocked.Increment(ref _nextCommandHandle);
}
/// <summary>
/// Gets the map of command handles and their task completion sources.
/// </summary>
private static IDictionary<int, object> _taskCompletionSources = new ConcurrentDictionary<int, object>();
/// <summary>
/// Adds a new TaskCompletionSource to track.
/// </summary>
/// <typeparam name="T">The type of the TaskCompletionSource result.</typeparam>
/// <param name="taskCompletionSource">The TaskCompletionSource to track.</param>
/// <returns>The command handle to use for tracking the task completion source.</returns>
public static int Add<T>(TaskCompletionSource<T> taskCompletionSource)
{
Debug.Assert(taskCompletionSource == null, "A task completion source is required.");
var commandHandle = GetNextCommandHandle();
_taskCompletionSources.Add(commandHandle, taskCompletionSource);
return commandHandle;
}
/// <summary>
/// Gets and removes a TaskCompletionResult from tracking.
/// </summary>
/// <typeparam name="T">The type of the TaskCompletionResult that was tracked.</typeparam>
/// <param name="commandHandle">The command handle used for tracking the TaskCompletionResult.</param>
/// <returns>The TaskCompletionResult associated with the command handle.</returns>
public static TaskCompletionSource<T> Remove<T>(int commandHandle)
{
Debug.Assert(_taskCompletionSources.ContainsKey(commandHandle), string.Format("No task completion source is currently registered for the command with the handle '{0}'.", commandHandle));
var taskCompletionSource = _taskCompletionSources[commandHandle];
_taskCompletionSources.Remove(commandHandle);
var result = taskCompletionSource as TaskCompletionSource<T>;
Debug.Assert(result != null, string.Format("No task completion source of the specified type is registered for the command with the handle '{0}'.", commandHandle));
return result;
}
}
}
| apache-2.0 | C# |
f5f27a9a418bf1aa4c884c6b122dae89f782ac0a | Fix method name change | hrzafer/nuve | nuve/Stemming/StatisticalStemmer.cs | nuve/Stemming/StatisticalStemmer.cs | using System.Collections.Generic;
using Nuve.Lang;
using Nuve.Morphologic.Structure;
using Nuve.NGrams;
namespace Nuve.Stemming
{
internal class StatisticalStemmer : IStemmer
{
private readonly WordAnalyzer analyzer;
private readonly NGramModel model;
public StatisticalStemmer(NGramModel model, WordAnalyzer analyzer)
{
this.model = model;
this.analyzer = analyzer;
}
public string GetStem(string word)
{
IList<Word> solutions = analyzer.Analyze(word);
if (solutions.Count == 0)
{
return word;
}
if (solutions.Count == 1)
{
return solutions[0].GetStem().GetSurface();
}
double max = double.NegativeInfinity;
int maxIndex = 0;
for (int i = 0; i < solutions.Count; i++)
{
double p = model.GetSentenceProbability(solutions[i].MorphemeSequence);
//Console.WriteLine(solutions[i] + "\t" + p);
if (p > max)
{
max = p;
maxIndex = i;
}
}
return solutions[maxIndex].GetStem().GetSurface();
}
}
} | using System.Collections.Generic;
using Nuve.Lang;
using Nuve.Morphologic.Structure;
using Nuve.NGrams;
namespace Nuve.Stemming
{
internal class StatisticalStemmer : IStemmer
{
private readonly WordAnalyzer analyzer;
private readonly NGramModel model;
public StatisticalStemmer(NGramModel model, WordAnalyzer analyzer)
{
this.model = model;
this.analyzer = analyzer;
}
public string GetStem(string word)
{
IList<Word> solutions = analyzer.Analyze(word);
if (solutions.Count == 0)
{
return word;
}
if (solutions.Count == 1)
{
return solutions[0].GetStem().GetSurface();
}
double max = double.NegativeInfinity;
int maxIndex = 0;
for (int i = 0; i < solutions.Count; i++)
{
double p = model.GetSentenceProbability(solutions[i].GetSequenceIds());
//Console.WriteLine(solutions[i] + "\t" + p);
if (p > max)
{
max = p;
maxIndex = i;
}
}
return solutions[maxIndex].GetStem().GetSurface();
}
}
} | mit | C# |
2d65d191e59e826c748a3f888e732ccc0baa0aed | rename variable | yasokada/unity-151117-linemonitor-UI | Assets/SettingSend.cs | Assets/SettingSend.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text.RegularExpressions; // for Regex
// for UDP send
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class SettingSend : MonoBehaviour {
public const string kCommandIpAddressPrefix = "192.168.10.";
public const string kDefaultCommandPort = "7000";
public const string kDefaultComBaud = "9600";
public InputField IF_ipadr;
public InputField IF_port;
public InputField IF_combaud;
public bool s_udp_initialized = false;
UdpClient s_udp_client;
void Start () {
IF_ipadr.text = kCommandIpAddressPrefix;
IF_port.text = kDefaultCommandPort;
IF_combaud.text = kDefaultComBaud;
}
void UDP_init() {
s_udp_client = new UdpClient ();
s_udp_client.Client.ReceiveTimeout = 300; // msec
s_udp_client.Client.Blocking = false;
}
void UDP_send(string ipadr, string portStr, string text) {
int portInt = int.Parse(new Regex("[0-9]+").Match(portStr).Value); // from string to integer
byte[] data = System.Text.Encoding.ASCII.GetBytes(text); // from string to byte[]
s_udp_client.Send (data, data.Length, ipadr, portInt);
}
public void SendButtonClick() {
if (s_udp_initialized == false) {
s_udp_initialized = true;
UDP_init ();
}
}
}
// client.Send (data, data.Length, ipadr, port);
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text.RegularExpressions; // for Regex
// for UDP send
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class SettingSend : MonoBehaviour {
public const string kCommandIpAddressPrefix = "192.168.10.";
public const string kDefaultCommandPort = "7000";
public const string kDefaultComBaud = "9600";
public InputField IF_ipadr;
public InputField IF_port;
public InputField IF_combaud;
public bool s_udp_isNotInit = true; // TODO: 1> rename to positive variable
UdpClient s_udp_client;
void Start () {
IF_ipadr.text = kCommandIpAddressPrefix;
IF_port.text = kDefaultCommandPort;
IF_combaud.text = kDefaultComBaud;
}
void UDP_init() {
s_udp_client = new UdpClient ();
s_udp_client.Client.ReceiveTimeout = 300; // msec
s_udp_client.Client.Blocking = false;
}
void UDP_send(string ipadr, string portStr, string text) {
int portInt = int.Parse(new Regex("[0-9]+").Match(portStr).Value); // from string to integer
byte[] data = System.Text.Encoding.ASCII.GetBytes(text); // from string to byte[]
s_udp_client.Send (data, data.Length, ipadr, portInt);
}
public void SendButtonClick() {
Debug.Log ("SendButton");
if (s_udp_isNotInit == true) {
s_udp_isNotInit = false;
UDP_init ();
}
}
}
// client.Send (data, data.Length, ipadr, port);
| mit | C# |
2daa77f80c3583dd5c0dcbe0ce6c485177d478bd | make it clear what our default web test runner is | pseale/monopoly-dotnet,pseale/monopoly-dotnet | src/MonopolyTests/Infrastructure/SeleniumHelper.cs | src/MonopolyTests/Infrastructure/SeleniumHelper.cs | using Coypu;
using Coypu.Drivers;
namespace MonopolyTests.Infrastructure
{
public static class SeleniumHelper
{
private static BrowserSession _browserSession;
public static BrowserSession BrowserSession
{
get
{
if (_browserSession == null)
Start();
return _browserSession;
}
}
public static void Start()
{
//_browserSession = new BrowserSession(new SessionConfiguration() { Port = IisExpressInstance.Port, Browser = Browser.Firefox});
_browserSession = new BrowserSession(new SessionConfiguration() { Port = IisExpressInstance.Port, Browser = Browser.Chrome});
}
public static void Stop()
{
if (_browserSession == null) return;
_browserSession.Dispose();
}
}
} | using Coypu;
using Coypu.Drivers;
namespace MonopolyTests.Infrastructure
{
public static class SeleniumHelper
{
private static BrowserSession _browserSession;
public static BrowserSession BrowserSession
{
get
{
if (_browserSession == null)
Start();
return _browserSession;
}
}
public static void Start()
{
//_browserSession = new BrowserSession(new SessionConfiguration() { Port = IisExpressInstance.Port});
_browserSession = new BrowserSession(new SessionConfiguration() { Port = IisExpressInstance.Port, Browser = Browser.Chrome});
}
public static void Stop()
{
if (_browserSession == null) return;
_browserSession.Dispose();
}
}
} | mit | C# |
6832af7196b6f87925f4aea65e7a8a6aef72242e | Fix serialization of the zoneemphasis | OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core | Core/OfficeDevPnP.Core/Pages/ClientSideSectionEmphasis.cs | Core/OfficeDevPnP.Core/Pages/ClientSideSectionEmphasis.cs | using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Pages
{
public class ClientSideSectionEmphasis
{
[JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)]
public int ZoneEmphasis
{
get
{
if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result))
{
return result;
}
return 0;
}
set { ZoneEmphasisString = value.ToString(); }
}
[JsonIgnore]
public string ZoneEmphasisString { get; set; }
}
}
| using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Pages
{
public class ClientSideSectionEmphasis
{
[JsonIgnore]
public int ZoneEmphasis
{
get
{
if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result))
{
return result;
}
return 0;
}
set { ZoneEmphasisString = value.ToString(); }
}
[JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)]
public string ZoneEmphasisString { get; set; }
}
}
| mit | C# |
e04379dd1d09ef3590deb6da4479ba10298e6578 | Add SpnLookupTime property back to SpnEndpointIdentity | hongdai/wcf,zhenlan/wcf,ericstj/wcf,KKhurin/wcf,iamjasonp/wcf,iamjasonp/wcf,mconnew/wcf,StephenBonikowsky/wcf,mconnew/wcf,imcarolwang/wcf,shmao/wcf,mconnew/wcf,dotnet/wcf,MattGal/wcf,shmao/wcf,imcarolwang/wcf,imcarolwang/wcf,ElJerry/wcf,ericstj/wcf,StephenBonikowsky/wcf,zhenlan/wcf,MattGal/wcf,KKhurin/wcf,ElJerry/wcf,dotnet/wcf,khdang/wcf,khdang/wcf,hongdai/wcf,dotnet/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/SpnEndpointIdentity.cs | src/System.Private.ServiceModel/src/System/ServiceModel/SpnEndpointIdentity.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.IdentityModel.Claims;
using System.Runtime;
using System.Security.Principal;
namespace System.ServiceModel
{
public class SpnEndpointIdentity : EndpointIdentity
{
public SpnEndpointIdentity(string spnName)
{
if (spnName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName");
base.Initialize(Claim.CreateSpnClaim(spnName));
}
public SpnEndpointIdentity(Claim identity)
{
if (identity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
if (!identity.ClaimType.Equals(ClaimTypes.Spn))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn));
base.Initialize(identity);
}
public static TimeSpan SpnLookupTime {get;set;}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IdentityModel.Claims;
using System.Runtime;
using System.Security.Principal;
namespace System.ServiceModel
{
public class SpnEndpointIdentity : EndpointIdentity
{
public SpnEndpointIdentity(string spnName)
{
if (spnName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spnName");
base.Initialize(Claim.CreateSpnClaim(spnName));
}
public SpnEndpointIdentity(Claim identity)
{
if (identity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
if (!identity.ClaimType.Equals(ClaimTypes.Spn))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.UnrecognizedClaimTypeForIdentity, identity.ClaimType, ClaimTypes.Spn));
base.Initialize(identity);
}
}
}
| mit | C# |
4fdb8f43689e454755e5891d4d3fb7fe19a088c0 | Remove unnecessary base call on default ctor | editor-tools/octokit.net,editor-tools/octokit.net,Sarmad93/octokit.net,octokit-net-test-org/octokit.net,gabrielweyer/octokit.net,TattsGroup/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,alfhenrik/octokit.net,ivandrofly/octokit.net,M-Zuber/octokit.net,shiftkey/octokit.net,ivandrofly/octokit.net,dampir/octokit.net,adamralph/octokit.net,rlugojr/octokit.net,chunkychode/octokit.net,TattsGroup/octokit.net,eriawan/octokit.net,gdziadkiewicz/octokit.net,SmithAndr/octokit.net,chunkychode/octokit.net,octokit-net-test-org/octokit.net,shiftkey-tester/octokit.net,hahmed/octokit.net,thedillonb/octokit.net,thedillonb/octokit.net,shana/octokit.net,SmithAndr/octokit.net,alfhenrik/octokit.net,khellang/octokit.net,shiftkey/octokit.net,shana/octokit.net,SamTheDev/octokit.net,eriawan/octokit.net,devkhan/octokit.net,dampir/octokit.net,rlugojr/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,devkhan/octokit.net,shiftkey-tester/octokit.net,gabrielweyer/octokit.net,octokit/octokit.net,khellang/octokit.net,hahmed/octokit.net,octokit/octokit.net,Sarmad93/octokit.net,SamTheDev/octokit.net,M-Zuber/octokit.net,gdziadkiewicz/octokit.net | Octokit/Exceptions/InvalidGitignoreTemplateException.cs | Octokit/Exceptions/InvalidGitignoreTemplateException.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// Represents a HTTP 403 - Forbidden response returned from the API.
/// </summary>
#if !NETFX_CORE
[Serializable]
#endif
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors",
Justification = "These exceptions are specific to the GitHub API and not general purpose exceptions")]
public class InvalidGitIgnoreTemplateException : ApiValidationException
{
/// <summary>
/// Constructs an instance of ApiValidationException
/// </summary>
public InvalidGitIgnoreTemplateException()
{ }
/// <summary>
/// Constructs an instance of ApiValidationException
/// </summary>
/// <param name="innerException">The inner validation exception.</param>
public InvalidGitIgnoreTemplateException(ApiValidationException innerException)
: base(innerException)
{ }
public override string Message
{
get
{
return "The Gitignore template provided is not valid.";
}
}
#if !NETFX_CORE
/// <summary>
/// Constructs an instance of InvalidGitignoreTemplateException
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> that holds the
/// serialized object data about the exception being thrown.
/// </param>
/// <param name="context">
/// The <see cref="StreamingContext"/> that contains
/// contextual information about the source or destination.
/// </param>
protected InvalidGitIgnoreTemplateException(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endif
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// Represents a HTTP 403 - Forbidden response returned from the API.
/// </summary>
#if !NETFX_CORE
[Serializable]
#endif
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors",
Justification = "These exceptions are specific to the GitHub API and not general purpose exceptions")]
public class InvalidGitIgnoreTemplateException : ApiValidationException
{
/// <summary>
/// Constructs an instance of ApiValidationException
/// </summary>
public InvalidGitIgnoreTemplateException()
: base()
{ }
/// <summary>
/// Constructs an instance of ApiValidationException
/// </summary>
/// <param name="innerException">The inner validation exception.</param>
public InvalidGitIgnoreTemplateException(ApiValidationException innerException)
: base(innerException)
{ }
public override string Message
{
get
{
return "The Gitignore template provided is not valid.";
}
}
#if !NETFX_CORE
/// <summary>
/// Constructs an instance of InvalidGitignoreTemplateException
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> that holds the
/// serialized object data about the exception being thrown.
/// </param>
/// <param name="context">
/// The <see cref="StreamingContext"/> that contains
/// contextual information about the source or destination.
/// </param>
protected InvalidGitIgnoreTemplateException(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endif
}
} | mit | C# |
8cd91031bab253b7d10650cd20ecdadd43600963 | Add using statement. | mthamil/EFDocumentationGenerator | extension/Tests.Unit/Support/TemporaryFileTests.cs | extension/Tests.Unit/Support/TemporaryFileTests.cs | using System;
using System.IO;
using Xunit;
namespace Tests.Unit.Support
{
public class TemporaryFileTests
{
[Fact]
public void Test_File()
{
// Arrange.
using (var temp = new TemporaryFile())
{
// Act.
var file = temp.File;
// Assert.
Assert.NotNull(file);
Assert.Equal(Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar), file.DirectoryName.TrimEnd(Path.DirectorySeparatorChar));
}
}
[Fact]
public void Test_Touch()
{
// Arrange.
using (var temp = new TemporaryFile())
{
// Act.
var returned = temp.Touch();
// Assert.
Assert.True(temp.File.Exists);
Assert.Same(temp, returned);
}
}
[Fact]
public void Test_WithContent()
{
// Act.
using (var temp = new TemporaryFile("stuff"))
{
// Assert.
Assert.True(temp.File.Exists);
Assert.Equal("stuff", File.ReadAllText(temp.File.FullName));
}
}
[Fact]
public void Test_Dispose()
{
// Arrange.
var temp = new TemporaryFile().Touch();
// Act.
temp.Dispose();
temp.File.Refresh();
// Assert.
Assert.False(temp.File.Exists);
}
[Fact]
public void Test_Destructor()
{
// Act.
FileInfo file = GetTempFile();
GC.Collect();
GC.WaitForPendingFinalizers();
file.Refresh();
// Assert.
Assert.False(file.Exists);
}
private static FileInfo GetTempFile()
{
var temp = new TemporaryFile().Touch();
return temp.File;
}
}
} | using System;
using System.IO;
using Xunit;
namespace Tests.Unit.Support
{
public class TemporaryFileTests
{
[Fact]
public void Test_File()
{
// Arrange.
var temp = new TemporaryFile();
// Act.
var file = temp.File;
// Assert.
Assert.NotNull(file);
Assert.Equal(Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar), file.DirectoryName.TrimEnd(Path.DirectorySeparatorChar));
}
[Fact]
public void Test_Touch()
{
// Arrange.
using (var temp = new TemporaryFile())
{
// Act.
var returned = temp.Touch();
// Assert.
Assert.True(temp.File.Exists);
Assert.Same(temp, returned);
}
}
[Fact]
public void Test_WithContent()
{
// Act.
using (var temp = new TemporaryFile("stuff"))
{
// Assert.
Assert.True(temp.File.Exists);
Assert.Equal("stuff", File.ReadAllText(temp.File.FullName));
}
}
[Fact]
public void Test_Dispose()
{
// Arrange.
var temp = new TemporaryFile().Touch();
// Act.
temp.Dispose();
temp.File.Refresh();
// Assert.
Assert.False(temp.File.Exists);
}
[Fact]
public void Test_Destructor()
{
// Act.
FileInfo file = GetTempFile();
GC.Collect();
GC.WaitForPendingFinalizers();
file.Refresh();
// Assert.
Assert.False(file.Exists);
}
private static FileInfo GetTempFile()
{
var temp = new TemporaryFile().Touch();
return temp.File;
}
}
} | apache-2.0 | C# |
f5d415b3a1d203103de70596cc33580f8534b1b3 | bump version | modulexcite/Anotar,mstyura/Anotar,Fody/Anotar,distantcam/Anotar | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("2.17.0")]
[assembly: AssemblyFileVersion("2.17.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("2.16.4")]
[assembly: AssemblyFileVersion("2.16.4")]
| mit | C# |
2073662a02b77453fa886aa4f04af28547ea666e | fix info | Fody/Scalpel | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Scalpel")]
[assembly: AssemblyProduct("Scalpel")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Fielder")]
[assembly: AssemblyProduct("Fielder")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
| mit | C# |
56938a4211919c0557484efb6ed65da620273ab8 | Change version to 1.5.1 | RazorGenerator/RazorGenerator,RazorGenerator/RazorGenerator,wizzardmr42/RazorGenerator | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.5.1")]
[assembly: AssemblyProduct("RazorGenerator")]
[assembly: AssemblyCompany("RazorGenerator contributors")]
| using System.Reflection;
[assembly: AssemblyVersion("1.5.0")]
[assembly: AssemblyProduct("RazorGenerator")]
[assembly: AssemblyCompany("RazorGenerator contributors")]
| apache-2.0 | C# |
1d72e49186f7e69b0b0c9466dd28540c9f55be49 | Verify Credentials works. | dance2die/MyAnimeListSharp | Project.MyAnimeList/Project.MyAnimeList.Demo/Program.cs | Project.MyAnimeList/Project.MyAnimeList.Demo/Program.cs | using System;
using System.IO;
using System.Net;
namespace Project.MyAnimeList.Demo
{
public class Program
{
public static void Main(string[] args)
{
ICredentialContext credential = new CredentialContext();
TestCredentials(credential);
}
private static void TestCredentials(ICredentialContext credential)
{
HttpWebRequest request = CreateCredentialWebRequest(credential);
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
//Read the content.
string responseFromServer = reader.ReadToEnd();
}
}
private static HttpWebRequest CreateCredentialWebRequest(ICredentialContext credential)
{
RequestParameters requestParameters = new VerifyCredentialsRequestParameters(credential);
return CreateWebRequest(requestParameters);
}
private static HttpWebRequest CreateWebRequest(RequestParameters requestParameters)
{
HttpWebRequest result = WebRequest.Create(requestParameters.RequestUri) as HttpWebRequest;
if (result == null)
throw new InvalidOperationException("Could not create web request");
result.ContentType = "application/x-www-form-urlencoded";
// credit
// https://github.com/DeadlyEmbrace/MyAnimeListAPI/blob/master/MyAnimeListAPI/MyAnimeListAPI/Credentials.cs
result.Method = requestParameters.HttpMethod;
result.UseDefaultCredentials = false;
result.Credentials = new NetworkCredential(
requestParameters.Credential.UserName, requestParameters.Credential.Password);
// credit
// https://github.com/LHCGreg/mal-api/blob/f6c82c95d139807a1d6259200ec7622384328bc3/MalApi/MyAnimeListApi.cs
result.AutomaticDecompression = DecompressionMethods.GZip;
return result;
}
}
public class VerifyCredentialsRequestParameters : RequestParameters
{
public override string RequestUri { get; set; } = "http://myanimelist.net/api/account/verify_credentials.xml";
public override string HttpMethod { get; set; } = "GET";
public VerifyCredentialsRequestParameters(ICredentialContext credential)
: base(credential)
{
Credential = credential;
}
}
public abstract class RequestParameters
{
public ICredentialContext Credential { get; set; }
protected RequestParameters(ICredentialContext credential)
{
Credential = credential;
}
public abstract string RequestUri { get; set; }
public abstract string HttpMethod { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project.MyAnimeList.Demo
{
public class Program
{
public static void Main(string[] args)
{
}
}
}
| mit | C# |
edf5a996a9da81d7471a3fccd1fb06bcccfe5bb6 | Add test which checks for duplicate user agent | YOTOV-LIMITED/rackspace-net-sdk,YOTOV-LIMITED/rackspace-net-sdk,rackspace/rackspace-net-sdk,hdansou/rackspace-net-sdk,hdansou/rackspace-net-sdk,rackspace/rackspace-net-sdk,rackspace/Rackspace.NET,rackspace/Rackspace.NET | test/Rackspace.UnitTests/RackspaceNetTests.cs | test/Rackspace.UnitTests/RackspaceNetTests.cs | using System;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using Flurl.Http;
using Rackspace.Testing;
using Xunit;
namespace Rackspace
{
public class RackspaceNetTests : IDisposable
{
public RackspaceNetTests()
{
RackspaceNet.ResetDefaults();
}
public void Dispose()
{
RackspaceNet.ResetDefaults();
}
[Fact]
public void ResetDefaults_ResetsFlurlConfiguration()
{
RackspaceNet.Configure();
Assert.NotNull(FlurlHttp.Configuration.BeforeCall);
RackspaceNet.ResetDefaults();
Assert.Null(FlurlHttp.Configuration.BeforeCall);
}
[Fact]
public async void UserAgentTest()
{
using (var httpTest = new HttpTest())
{
RackspaceNet.Configure();
await "http://api.com".GetAsync();
var userAgent = httpTest.CallLog[0].Request.Headers.UserAgent.ToString();
Assert.Contains("rackspace.net", userAgent);
Assert.Contains("openstack.net", userAgent);
}
}
[Fact]
public async void UserAgentOnlyListedOnceTest()
{
using (var httpTest = new HttpTest())
{
RackspaceNet.Configure();
RackspaceNet.Configure();
await "http://api.com".GetAsync();
var userAgent = httpTest.CallLog[0].Request.Headers.UserAgent.ToString();
var matches = new Regex("rackspace").Matches(userAgent);
Assert.Equal(1, matches.Count);
}
}
[Fact]
public async void UserAgentWithApplicationSuffixTest()
{
using (var httpTest = new HttpTest())
{
RackspaceNet.Configure(configure: options => options.UserAgents.Add(new ProductInfoHeaderValue("(unit-tests)")));
await "http://api.com".GetAsync();
var userAgent = httpTest.CallLog[0].Request.Headers.UserAgent.ToString();
Assert.Contains("rackspace.net", userAgent);
Assert.Contains("unit-tests", userAgent);
}
}
}
}
| using System;
using System.Net.Http.Headers;
using Flurl.Http;
using Rackspace.Testing;
using Xunit;
namespace Rackspace
{
public class RackspaceNetTests : IDisposable
{
public RackspaceNetTests()
{
RackspaceNet.ResetDefaults();
}
public void Dispose()
{
RackspaceNet.ResetDefaults();
}
[Fact]
public void ResetDefaults_ResetsFlurlConfiguration()
{
RackspaceNet.Configure();
Assert.NotNull(FlurlHttp.Configuration.BeforeCall);
RackspaceNet.ResetDefaults();
Assert.Null(FlurlHttp.Configuration.BeforeCall);
}
[Fact]
public async void UserAgentTest()
{
using (var httpTest = new HttpTest())
{
RackspaceNet.Configure();
await "http://api.com".GetAsync();
var userAgent = httpTest.CallLog[0].Request.Headers.UserAgent.ToString();
Assert.Contains("rackspace.net", userAgent);
Assert.Contains("openstack.net", userAgent);
}
}
[Fact]
public async void UserAgentWithApplicationSuffixTest()
{
using (var httpTest = new HttpTest())
{
RackspaceNet.Configure(configure: options => options.UserAgents.Add(new ProductInfoHeaderValue("(unit-tests)")));
await "http://api.com".GetAsync();
var userAgent = httpTest.CallLog[0].Request.Headers.UserAgent.ToString();
Assert.Contains("rackspace.net", userAgent);
Assert.Contains("unit-tests", userAgent);
}
}
}
}
| apache-2.0 | C# |
b1f523e787bfc8fbdceca96080d86d07209dff5c | Address CodeFactor. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/ViewModels/Validation/Validator.cs | WalletWasabi.Gui/ViewModels/Validation/Validator.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.ViewModels.Validation
{
public static class Validator
{
public static IEnumerable<(string, MethodInfo)> PropertiesWithValidation(object instance)
{
foreach (PropertyInfo pInfo in ReflectionHelper.GetPropertyInfos(instance))
{
var vma = ReflectionHelper.GetAttribute<ValidateMethodAttribute>(pInfo);
if (vma is null) continue;
var mInfo = ReflectionHelper.GetMethodInfo<ErrorDescriptors>(instance, vma.MethodName);
yield return (pInfo.Name, mInfo);
}
}
public static ErrorDescriptors ValidateAllProperties(ViewModelBase viewModelBase,
List<(string propertyName, MethodInfo mInfo)> validationMethodCache)
{
if (validationMethodCache is null) return ErrorDescriptors.Empty;
ErrorDescriptors result = null;
foreach (var validationCache in validationMethodCache)
{
var invokeRes = (ErrorDescriptors)validationCache.mInfo.Invoke(viewModelBase, null);
if (result is null) result = new ErrorDescriptors();
result.AddRange(invokeRes);
}
return result ?? ErrorDescriptors.Empty;
}
public static ErrorDescriptors ValidateProperty(ViewModelBase viewModelBase,
string propertyName,
List<(string propertyName, MethodInfo mInfo)> validationMethodCache)
{
if (validationMethodCache is null) return ErrorDescriptors.Empty;
ErrorDescriptors result = null;
foreach (var validationCache in validationMethodCache)
{
if (validationCache.propertyName != propertyName) continue;
var invokeRes = (ErrorDescriptors)validationCache.mInfo.Invoke(viewModelBase, null);
if (result is null) result = new ErrorDescriptors();
result.AddRange(invokeRes);
}
return result ?? ErrorDescriptors.Empty;
}
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.ViewModels.Validation
{
public static class Validator
{
public static IEnumerable<(string, MethodInfo)> PropertiesWithValidation(object instance)
{
foreach (PropertyInfo pInfo in ReflectionHelper.GetPropertyInfos(instance))
{
var vma = ReflectionHelper.GetAttribute<ValidateMethodAttribute>(pInfo);
if (vma is null) continue;
var mInfo = ReflectionHelper.GetMethodInfo<ErrorDescriptors>(instance, vma.MethodName);
yield return (pInfo.Name, mInfo);
}
}
public static ErrorDescriptors ValidateAllProperties(ViewModelBase viewModelBase,
List<(string propertyName, MethodInfo mInfo)> validationMethodCache)
{
if (validationMethodCache is null) return ErrorDescriptors.Empty;
ErrorDescriptors result = null;
foreach (var validationCache in validationMethodCache)
{
var invokeRes = (ErrorDescriptors)validationCache.mInfo.Invoke(viewModelBase, null);
if (result is null) result = new ErrorDescriptors();
result.AddRange(invokeRes);
}
return result ?? ErrorDescriptors.Empty;
}
public static ErrorDescriptors ValidateProperty(ViewModelBase viewModelBase,
string propertyName,
List<(string propertyName, MethodInfo mInfo)> validationMethodCache)
{
if (validationMethodCache is null) return ErrorDescriptors.Empty;
ErrorDescriptors result = null;
foreach (var validationCache in validationMethodCache)
{
if (validationCache.propertyName != propertyName) continue;
var invokeRes = (ErrorDescriptors)validationCache.mInfo.Invoke(viewModelBase, null);
if (result is null) result = new ErrorDescriptors();
result.AddRange(invokeRes);
}
return result ?? ErrorDescriptors.Empty;
}
}
} | mit | C# |
53e024bccd199d2219f8fef292e97159a4e32c1b | Test af assigntment controller | Bargsteen/ADL,Bargsteen/ADL,Bargsteen/ADL | WebCode/test/ADL.Tests/AssignmentControllerTests.cs | WebCode/test/ADL.Tests/AssignmentControllerTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using ADL.controllers;
using Moq;
namespace ADL.Tests
{
class AssignmentControllerTests
{
[Fact]
public void Can_List_Assignments()
{
// Arrange
Mock<IAssignmentRepository> mock = new Mock<IAssignmentRepository>();
mock.Assignments.Returns(Assignment[3] = new Assignment { Headline = "A1", Headline = "A2", Headline = "A3" });
/* {
new Assignment() = { Headline = "A1"};
new Assignment() = { Headline = "A2"};
new Assignment() = { Headline = "A3"};
}
*/
AssignmentController controller = new AssignmentController(mock.Object());
// Act
Assignment[] result = (controller.List() as ViewModel).ToArray();
// Assert
Assert.Equal(result.Length, 3);
Assert.True(result[0].Headline == "A1");
Assert.True(result[1].Headline == "A2");
Assert.True(result[2].Headline == "A3");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using ADL.controllers;
using Moq;
namespace ADL.Tests
{
class AssignmentControllerTests
{
[Fact]
public void Can_List_Assignments()
{
// Arrange
Mock<IAssignmentRepository> mock = new Mock<IAssignmentRepository>();
mock.Assignments.Returns(new Assignment[] =
{
new Assignment = { Headline = "A1"};
new Assignment = { Headline = "A2"};
new Assignment = { Headline = "A3"};
}
AssignmentController controller = new AssignmentController(mock.Object());
// Act
Assignment[] result = (controller.List() as ViewModel).ToArray();
// Assert
Assert.Equal(result.Length, 3);
Assert.True(result[0].Headline == "A1");
Assert.True(result[1].Headline == "A2");
Assert.True(result[2].Headline == "A3");
}
}
} | apache-2.0 | C# |
2da8f73a056e13f249f47de1dd0640f5374f5cca | Print more info if the message times out while waiting | MrLeebo/unitystation,MrLeebo/unitystation,fomalsd/unitystation,fomalsd/unitystation,MrLeebo/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,MrLeebo/unitystation,fomalsd/unitystation,fomalsd/unitystation,Lancemaker/unitystation,Necromunger/unitystation,krille90/unitystation,Lancemaker/unitystation,Necromunger/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Messages/GameMessageBase.cs | UnityProject/Assets/Scripts/Messages/GameMessageBase.cs | using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public abstract class GameMessageBase : MessageBase
{
public GameObject NetworkObject;
public GameObject[] NetworkObjects;
protected IEnumerator WaitFor(NetworkInstanceId id)
{
int tries = 0;
while ((NetworkObject = ClientScene.FindLocalObject(id)) == null)
{
if (tries++ > 10)
{
Debug.LogWarning($"{this} could not find object with id {id}");
yield break;
}
yield return YieldHelper.EndOfFrame;
}
}
protected IEnumerator WaitFor(params NetworkInstanceId[] ids)
{
NetworkObjects = new GameObject[ids.Length];
while (!AllLoaded(ids))
{
yield return YieldHelper.EndOfFrame;
}
}
private bool AllLoaded(NetworkInstanceId[] ids)
{
for (int i = 0; i < ids.Length; i++)
{
GameObject obj = ClientScene.FindLocalObject(ids[i]);
if (obj == null)
{
return false;
}
NetworkObjects[i] = obj;
}
return true;
}
}
| using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public abstract class GameMessageBase : MessageBase
{
public GameObject NetworkObject;
public GameObject[] NetworkObjects;
protected IEnumerator WaitFor(NetworkInstanceId id)
{
int tries = 0;
while ((NetworkObject = ClientScene.FindLocalObject(id)) == null)
{
if (tries++ > 10)
{
Debug.LogWarning("GameMessageBase could not find object with id " + id);
yield break;
}
yield return YieldHelper.EndOfFrame;
}
}
protected IEnumerator WaitFor(params NetworkInstanceId[] ids)
{
NetworkObjects = new GameObject[ids.Length];
while (!AllLoaded(ids))
{
yield return YieldHelper.EndOfFrame;
}
}
private bool AllLoaded(NetworkInstanceId[] ids)
{
for (int i = 0; i < ids.Length; i++)
{
GameObject obj = ClientScene.FindLocalObject(ids[i]);
if (obj == null)
{
return false;
}
NetworkObjects[i] = obj;
}
return true;
}
} | agpl-3.0 | C# |
4ce3b07ba1fa4ef07a6d6f910050e134d56c6bf0 | Add http path under http.uri tag | criteo/zipkin4net,criteo/zipkin4net | zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs | zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.uri", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
} | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
if (!extractor.TryExtract(context.Request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, context.Request.Method))
{
await TraceHelper.TracedActionAsync(next());
}
});
}
}
} | apache-2.0 | C# |
dc8fae7d8fa18f545f9dfb055dad58409a4dcaca | Refactor Divide Doubles operation to use GetValues and CloneWithValues | ajlopez/TensorSharp | Src/TensorSharp/Operations/DivideDoubleDoubleOperation.cs | Src/TensorSharp/Operations/DivideDoubleDoubleOperation.cs | namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
double[] values1 = tensor1.GetValues();
int l = values1.Length;
double value2 = tensor2.GetValue();
double[] newvalues = new double[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] / value2;
return tensor1.CloneWithNewValues(newvalues);
}
}
}
| namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
Tensor<double> result = new Tensor<double>();
result.SetValue(tensor1.GetValue() / tensor2.GetValue());
return result;
}
}
}
| mit | C# |
6a08332ff9cd87c4edad5509b1a8d89ca5e995c9 | Fix CI issues | default0/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,default0/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework | osu.Framework/Configuration/BindableNumberWithPrecision.cs | osu.Framework/Configuration/BindableNumberWithPrecision.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Configuration
{
public abstract class BindableNumberWithPrecision<T> : BindableNumber<T>
where T : struct
{
/// <summary>
/// An event which is raised when <see cref="Precision"/> has changed (or manually via <see cref="TriggerPrecisionChange"/>).
/// </summary>
public event Action<T> PrecisionChanged;
private T precision;
/// <summary>
/// The precision up to which the value of this bindable should be rounded.
/// </summary>
public T Precision
{
get => precision;
set
{
if (precision.Equals(value))
return;
precision = value;
TriggerPrecisionChange();
}
}
protected BindableNumberWithPrecision(T value = default(T))
: base(value)
{
precision = DefaultPrecision;
}
public override void TriggerChange()
{
base.TriggerChange();
TriggerPrecisionChange(false);
}
protected void TriggerPrecisionChange(bool propagateToBindings = true)
{
PrecisionChanged?.Invoke(MinValue);
if (!propagateToBindings)
return;
Bindings?.ForEachAlive(b =>
{
if (b is BindableNumberWithPrecision<T> other)
other.Precision = Precision;
});
}
protected abstract T DefaultPrecision { get; }
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Configuration
{
public abstract class BindableNumberWithPrecision<T> : BindableNumber<T>
where T : struct
{
/// <summary>
/// An event which is raised when <see cref="Precision"/> has changed (or manually via <see cref="TriggerPrecisionChange"/>).
/// </summary>
public event Action<T> PrecisionChanged;
private T precision;
/// <summary>
/// The precision up to which the value of this bindable should be rounded.
/// </summary>
public T Precision
{
get => precision;
set
{
if (precision.Equals(value))
return;
precision = value;
TriggerPrecisionChange();
}
}
protected BindableNumberWithPrecision(T value = default(T))
: base(value)
{
precision = DefaultPrecision;
}
public override void TriggerChange()
{
base.TriggerChange();
TriggerPrecisionChange(false);
}
protected void TriggerPrecisionChange(bool propagateToBindings = true)
{
PrecisionChanged?.Invoke(MinValue);
if (!propagateToBindings)
return;
Bindings?.ForEachAlive(b =>
{
if (b is BindableNumberWithPrecision<T> other)
other.Precision = Precision;
});
}
protected abstract T DefaultPrecision { get; }
}
}
| mit | C# |
48ea14bc311d857287a737a6df193262100b3fa5 | Simplify dispose method in Cursor class | k94ll13nn3/Strinken | src/Strinken/Engine/Cursor.cs | src/Strinken/Engine/Cursor.cs | // stylecop.header
using System;
using System.IO;
namespace Strinken.Engine
{
/// <summary>
/// Cursor used to read a string.
/// </summary>
internal sealed class Cursor : IDisposable
{
/// <summary>
/// The reader used to read the string.
/// </summary>
private readonly StringReader reader;
/// <summary>
/// Initializes a new instance of the <see cref="Cursor"/> class.
/// </summary>
/// <param name="input">The string to read.</param>
public Cursor(string input)
{
this.reader = new StringReader(input);
this.Position = -1;
this.Value = '\0';
}
/// <summary>
/// Gets the current position of the cursor.
/// </summary>
public int Position { get; private set; }
/// <summary>
/// Gets the current value of the cursor.
/// </summary>
public int Value { get; private set; }
/// <summary>
/// Gets the current value of the cursor as a <see cref="char"/>.
/// </summary>
public char CharValue => (char)this.Value;
/// <inheritdoc/>
public void Dispose()
{
this.reader?.Dispose();
}
/// <summary>
/// Indicates if the cursor as reached the end.
/// </summary>
/// <returns>A value indicating whether the cursor as reached the end.</returns>
public bool HasEnded() => this.Position != -1 && this.Value == -1;
/// <summary>
/// Moves the cursor.
/// </summary>
public void Next()
{
this.Value = this.reader.Read();
this.Position++;
}
}
} | // stylecop.header
using System;
using System.IO;
namespace Strinken.Engine
{
/// <summary>
/// Cursor used to read a string.
/// </summary>
internal class Cursor : IDisposable
{
/// <summary>
/// The reader used to read the string.
/// </summary>
private readonly StringReader reader;
/// <summary>
/// A value indicating whether the <see cref="Dispose()"/> method has already been called.
/// </summary>
private bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="Cursor"/> class.
/// </summary>
/// <param name="input">The string to read.</param>
public Cursor(string input)
{
this.reader = new StringReader(input);
this.Position = -1;
this.Value = '\0';
}
/// <summary>
/// Gets the current position of the cursor.
/// </summary>
public int Position { get; private set; }
/// <summary>
/// Gets the current value of the cursor.
/// </summary>
public int Value { get; private set; }
/// <summary>
/// Gets the current value of the cursor as a <see cref="char"/>.
/// </summary>
public char CharValue => (char)this.Value;
/// <inheritdoc/>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Indicates if the cursor as reached the end.
/// </summary>
/// <returns>A value indicating whether the cursor as reached the end.</returns>
public bool HasEnded() => this.Position != -1 && this.Value == -1;
/// <summary>
/// Moves the cursor.
/// </summary>
public void Next()
{
this.Value = this.reader.Read();
this.Position++;
}
/// <summary>
/// Implementation of the dispose method.
/// </summary>
/// <param name="disposing">A value indicating whether managed resources should be disposed.</param>
protected virtual void Dispose(bool disposing)
{
if (this.disposed)
{
return;
}
if (disposing)
{
this.reader?.Dispose();
}
this.disposed = true;
}
}
} | mit | C# |
5f11084aedc4a6896f50d0e5a32ca7cf8540e653 | Refactor ProfileItemContainer to not use sounds | UselessToucan/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu-new,johnneijzen/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu | osu.Game/Overlays/Profile/Sections/ProfileItemContainer.cs | osu.Game/Overlays/Profile/Sections/ProfileItemContainer.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.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osuTK.Graphics;
namespace osu.Game.Overlays.Profile.Sections
{
public class ProfileItemContainer : Container
{
private const int hover_duration = 200;
protected override Container<Drawable> Content => content;
private Color4 idleColour;
private Color4 hoverColour;
private readonly Box background;
private readonly Container content;
public ProfileItemContainer()
{
RelativeSizeAxes = Axes.Both;
Masking = true;
CornerRadius = 6;
AddRangeInternal(new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
},
content = new Container
{
RelativeSizeAxes = Axes.Both,
}
});
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
background.Colour = idleColour = colours.GreySeafoam;
hoverColour = colours.GreySeafoamLight;
}
protected override bool OnHover(HoverEvent e)
{
background.FadeColour(hoverColour, hover_duration, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
base.OnHoverLost(e);
background.FadeColour(idleColour, hover_duration, Easing.OutQuint);
}
}
}
| // 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.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using System.Collections.Generic;
namespace osu.Game.Overlays.Profile.Sections
{
public class ProfileItemContainer : OsuHoverContainer
{
protected override IEnumerable<Drawable> EffectTargets => new[] { background };
protected override Container<Drawable> Content => content;
private readonly Box background;
private readonly Container content;
public ProfileItemContainer()
{
RelativeSizeAxes = Axes.Both;
Enabled.Value = true; //manually enabled, because we have no action
Masking = true;
CornerRadius = 6;
base.Content.AddRange(new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
},
content = new Container
{
RelativeSizeAxes = Axes.Both,
}
});
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
IdleColour = colours.GreySeafoam;
HoverColour = colours.GreySeafoamLight;
}
}
}
| mit | C# |
4c69286e90aa04dee0e1b2f9921f96c47b8470d8 | Revert "Fix: make cookie valid cross sessions. (#85)" | gyrosworkshop/Wukong,gyrosworkshop/Wukong | Wukong/Controllers/AuthController.cs | Wukong/Controllers/AuthController.cs | using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties { RedirectUri = redirectUri });
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
} | using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Wukong.Models;
namespace Wukong.Controllers
{
[Route("oauth")]
public class AuthController : Controller
{
[HttpGet("all")]
public IEnumerable<OAuthMethod> AllSchemes()
{
return
new List<OAuthMethod>{ new OAuthMethod()
{
Scheme = "Microsoft",
DisplayName = "Microsoft",
Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}"
}};
}
[HttpGet("go/{any}")]
public async Task SignIn(string any, string redirectUri = "/")
{
await HttpContext.ChallengeAsync(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties {
RedirectUri = redirectUri,
IsPersistent = true
});
}
[HttpGet("signout")]
public SignOutResult SignOut(string redirectUrl = "/")
{
return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
} | mit | C# |
06163b631985eb36b06118b578379739b09843a8 | Update internal calls to use API v1.2 | loicteixeira/gj-unity-api | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.1.3";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "https://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1_1"; // `1_1` actually targets the API version `1.2`..
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION;
public const string API_USERS_AUTH = "/users/auth";
public const string API_USERS_FETCH = "/users";
public const string API_SESSIONS_OPEN = "/sessions/open";
public const string API_SESSIONS_PING = "/sessions/ping";
public const string API_SESSIONS_CLOSE = "/sessions/close";
public const string API_SCORES_ADD = "/scores/add";
public const string API_SCORES_FETCH = "/scores";
public const string API_SCORES_TABLES_FETCH = "/scores/tables";
public const string API_TROPHIES_ADD = "/trophies/add-achieved";
public const string API_TROPHIES_FETCH = "/trophies";
public const string API_DATASTORE_SET = "/data-store/set";
public const string API_DATASTORE_UPDATE = "/data-store/update";
public const string API_DATASTORE_FETCH = "/data-store";
public const string API_DATASTORE_REMOVE = "/data-store/remove";
public const string API_DATASTORE_KEYS_FETCH = "/data-store/get-keys";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.1.3";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "https://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION;
public const string API_USERS_AUTH = "/users/auth";
public const string API_USERS_FETCH = "/users";
public const string API_SESSIONS_OPEN = "/sessions/open";
public const string API_SESSIONS_PING = "/sessions/ping";
public const string API_SESSIONS_CLOSE = "/sessions/close";
public const string API_SCORES_ADD = "/scores/add";
public const string API_SCORES_FETCH = "/scores";
public const string API_SCORES_TABLES_FETCH = "/scores/tables";
public const string API_TROPHIES_ADD = "/trophies/add-achieved";
public const string API_TROPHIES_FETCH = "/trophies";
public const string API_DATASTORE_SET = "/data-store/set";
public const string API_DATASTORE_UPDATE = "/data-store/update";
public const string API_DATASTORE_FETCH = "/data-store";
public const string API_DATASTORE_REMOVE = "/data-store/remove";
public const string API_DATASTORE_KEYS_FETCH = "/data-store/get-keys";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| mit | C# |
8972d622a83ac864edadc1009bb01c5eb8c7e322 | Add missing newline | Tom94/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,default0/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ZLima12/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,default0/osu-framework,peppy/osu-framework,EVAST9919/osu-framework | osu.Framework/Allocation/RecursiveLoadException.cs | osu.Framework/Allocation/RecursiveLoadException.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Linq;
using System.Reflection;
using System.Text;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Allocation
{
/// <summary>
/// The exception that is re-thrown by <see cref="DependencyContainer"/> when a loader invocation fails.
/// This exception type builds a readablestacktrace message since loader invocations tend to be long recursive reflection calls.
/// </summary>
public class RecursiveLoadException : Exception
{
/// <summary>
/// Types that are ignored for the custom stack traces. The initializers for these typically invoke
/// initializers in user code where the problem actually lies.
/// </summary>
private static readonly Type[] blacklist =
{
typeof(Container),
typeof(Container<>),
typeof(CompositeDrawable)
};
private readonly StringBuilder traceBuilder;
public RecursiveLoadException(Exception inner, MethodInfo loaderMethod)
: base(string.Empty, (inner as RecursiveLoadException)?.InnerException ?? inner)
{
traceBuilder = inner is RecursiveLoadException recursiveException ? recursiveException.traceBuilder : new StringBuilder();
if (!blacklist.Contains(loaderMethod.DeclaringType))
traceBuilder.AppendLine($" at {loaderMethod.DeclaringType}.{loaderMethod.Name} ()");
}
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendLine(InnerException?.ToString() ?? string.Empty);
builder.AppendLine(traceBuilder.ToString());
return builder.ToString();
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Linq;
using System.Reflection;
using System.Text;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Allocation
{
/// <summary>
/// The exception that is re-thrown by <see cref="DependencyContainer"/> when a loader invocation fails.
/// This exception type builds a readablestacktrace message since loader invocations tend to be long recursive reflection calls.
/// </summary>
public class RecursiveLoadException : Exception
{
/// <summary>
/// Types that are ignored for the custom stack traces. The initializers for these typically invoke
/// initializers in user code where the problem actually lies.
/// </summary>
private static readonly Type[] blacklist =
{
typeof(Container),
typeof(Container<>),
typeof(CompositeDrawable)
};
private readonly StringBuilder traceBuilder;
public RecursiveLoadException(Exception inner, MethodInfo loaderMethod)
: base(string.Empty, (inner as RecursiveLoadException)?.InnerException ?? inner)
{
traceBuilder = inner is RecursiveLoadException recursiveException ? recursiveException.traceBuilder : new StringBuilder();
if (!blacklist.Contains(loaderMethod.DeclaringType))
traceBuilder.AppendLine($" at {loaderMethod.DeclaringType}.{loaderMethod.Name} ()");
}
public override string ToString()
{
var builder = new StringBuilder();
builder.Append(InnerException?.ToString() ?? string.Empty);
builder.AppendLine(traceBuilder.ToString());
return builder.ToString();
}
}
}
| mit | C# |
6257add234ef4e7bca7b4fb97dd7cd38daee67b4 | Update INanoEngine interface | SirNanoCat/nano-tile-engine | Nano/Engine/INanoEngine.cs | Nano/Engine/INanoEngine.cs | namespace Nano.Engine
{
public interface INanoEngine
{
TileEngineType TileEngineType { get; }
int TileHeight { get; }
int TileWidth { get; }
}
}
| using System;
namespace Nano.Engine
{
public interface INanoEngine
{
int TileHeight { get; }
int TileWidth { get; }
}
}
| mit | C# |
823e2079dd1d06bbf666a5187b4faefbc5cda46c | Add IRequestTarget.Cast instead of BoundActorTarget.* | SaladLab/Akka.Interfaced,SaladbowlCreative/Akka.Interfaced,SaladLab/Akka.Interfaced,SaladbowlCreative/Akka.Interfaced | core/Akka.Interfaced-Base/InterfacedActorRefExtensions.cs | core/Akka.Interfaced-Base/InterfacedActorRefExtensions.cs | namespace Akka.Interfaced
{
public static class InterfacedActorRefExtensions
{
// Cast (not type-safe)
public static TRef Cast<TRef>(this InterfacedActorRef actorRef)
where TRef : InterfacedActorRef, new()
{
if (actorRef == null)
return null;
return new TRef()
{
Target = actorRef.Target,
RequestWaiter = actorRef.RequestWaiter,
Timeout = actorRef.Timeout
};
}
// Wrap target into TRef (not type-safe)
public static TRef Cast<TRef>(this IRequestTarget target)
where TRef : InterfacedActorRef, new()
{
if (target == null)
return null;
return new TRef()
{
Target = target,
RequestWaiter = target.DefaultRequestWaiter
};
}
}
}
| namespace Akka.Interfaced
{
public static class InterfacedActorRefExtensions
{
// Cast (not type-safe)
public static TRef Cast<TRef>(this InterfacedActorRef actorRef)
where TRef : InterfacedActorRef, new()
{
if (actorRef == null)
return null;
return new TRef()
{
Target = actorRef.Target,
RequestWaiter = actorRef.RequestWaiter,
Timeout = actorRef.Timeout
};
}
// Wrap target into TRef (not type-safe)
public static TRef Cast<TRef>(this BoundActorTarget target)
where TRef : InterfacedActorRef, new()
{
if (target == null)
return null;
return new TRef()
{
Target = target,
RequestWaiter = target.DefaultRequestWaiter
};
}
}
}
| mit | C# |
29c5759c22431f586bcc1aba1b731a1b2a4b830b | Support for nullable types in DataTableContructor | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/components/DataTableConstructor.cs | R7.University/components/DataTableConstructor.cs | //
// DataTableConstructor.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// 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.
// based on:
// http://www.c-sharpcorner.com/UploadFile/1a81c5/list-to-datatable-converter-using-C-Sharp/
// http://stackoverflow.com/questions/701223/net-convert-generic-collection-to-datatable
using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;
namespace R7.University
{
public static class DataTableConstructor
{
public static DataTable FromIEnumerable<T> (IEnumerable<T> items)
{
var dataTable = new DataTable (typeof (T).Name);
// get all the properties
var props = typeof (T).GetProperties (BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
dataTable.Columns.Add (prop.Name, Nullable.GetUnderlyingType (
prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in items)
{
var values = new object [props.Length];
for (var i = 0; i < props.Length; i++)
{
// inserting property values to datatable rows
values [i] = props [i].GetValue (item, null) ?? DBNull.Value;
}
dataTable.Rows.Add (values);
}
return dataTable;
}
}
}
| //
// DataTableConstructor.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2015
//
// 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.
// based on:
// http://www.c-sharpcorner.com/UploadFile/1a81c5/list-to-datatable-converter-using-C-Sharp/
using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;
namespace R7.University
{
public static class DataTableConstructor
{
public static DataTable FromIEnumerable<T> (IEnumerable<T> items)
{
var dataTable = new DataTable (typeof (T).Name);
// get all the properties
var props = typeof (T).GetProperties (BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
dataTable.Columns.Add (prop.Name, prop.PropertyType);
foreach (T item in items)
{
var values = new object [props.Length];
for (var i = 0; i < props.Length; i++)
{
// inserting property values to datatable rows
values [i] = props [i].GetValue (item, null);
}
dataTable.Rows.Add (values);
}
return dataTable;
}
}
}
| agpl-3.0 | C# |
8de4a2af69640e7572421f480e24e3dd84a49e92 | make lastAccess value valid ISO 8601 | automatonic/http-archive-net | src/HttpArchive.Tests/AfterRequestShould.cs | src/HttpArchive.Tests/AfterRequestShould.cs | using System.Text.Json;
using Xunit;
using FluentAssertions;
using System;
namespace HttpArchive
{
/// <summary>
/// Unit tests for the AfterRequest object
/// </summary>
public class AfterRequestShould
{
[Fact]
public void DeserializeSchemaExample()
{
var json =
@"{
""expires"": ""2009-04-16T15:50:36"",
""lastAccess"": ""2009-02-16T15:50:34"",
""eTag"": """",
""hitCount"": 0,
""comment"": """"
}";
var deserialized = JsonSerializer.Deserialize<AfterRequest>(json);
deserialized.Should().NotBeNull();
deserialized.Expires.Should().Be(DateTimeOffset.Parse("2009-04-16T15:50:36"));
deserialized.LastAccess.Should().Be(DateTimeOffset.Parse("2009-02-16T15:50:34"));
deserialized.Etag.Should().Be("");
deserialized.HitCount.Should().Be(0);
deserialized.Comment.Should().Be("");
}
[Fact]
public void RoundtripDefault()
{
var deserialized = JsonSerializer.Deserialize<AfterRequest>(
JsonSerializer.Serialize(new AfterRequest()));
deserialized.Expires.Should().BeNull();
deserialized.LastAccess.Should().Be(DateTimeOffset.MinValue);
deserialized.Etag.Should().Be("");
deserialized.HitCount.Should().Be(0);
deserialized.Comment.Should().BeNull();
}
}
}
| using System.Text.Json;
using Xunit;
using FluentAssertions;
using System;
namespace HttpArchive
{
/// <summary>
/// Unit tests for the AfterRequest object
/// </summary>
public class AfterRequestShould
{
[Fact]
public void DeserializeSchemaExample()
{
var json =
@"{
""expires"": ""2009-04-16T15:50:36"",
""lastAccess"": ""2009-16-02T15:50:34"",
""eTag"": """",
""hitCount"": 0,
""comment"": """"
}";
var deserialized = JsonSerializer.Deserialize<AfterRequest>(json);
deserialized.Should().NotBeNull();
deserialized.Expires.Should().Be(DateTimeOffset.Parse("2009-04-16T15:50:36"));
deserialized.LastAccess.Should().Be(DateTimeOffset.Parse("2009-16-02T15:50:34"));
deserialized.Etag.Should().Be("");
deserialized.HitCount.Should().Be(0);
deserialized.Comment.Should().Be("");
}
[Fact]
public void RoundtripDefault()
{
var deserialized = JsonSerializer.Deserialize<AfterRequest>(
JsonSerializer.Serialize(new AfterRequest()));
deserialized.Expires.Should().BeNull();
deserialized.LastAccess.Should().Be(DateTimeOffset.MinValue);
deserialized.Etag.Should().Be("");
deserialized.HitCount.Should().Be(0);
deserialized.Comment.Should().BeNull();
}
}
}
| mit | C# |
869d186b12ce21dc0eb74ee05e5f9837d60242df | Fix VideoTextureUpload inheriting ArrayPoolTextureUpload for no reason | ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | osu.Framework/Graphics/Video/VideoTextureUpload.cs | osu.Framework/Graphics/Video/VideoTextureUpload.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Textures;
using osuTK.Graphics.ES30;
using FFmpeg.AutoGen;
using osu.Framework.Graphics.Primitives;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Video
{
public unsafe class VideoTextureUpload : ITextureUpload
{
public AVFrame* Frame;
private readonly FFmpegFuncs.AvFrameFreeDelegate freeFrame;
public ReadOnlySpan<Rgba32> Data => ReadOnlySpan<Rgba32>.Empty;
public int Level => 0;
public RectangleI Bounds { get; set; }
public PixelFormat Format => PixelFormat.Red;
/// <summary>
/// Sets the frame cotaining the data to be uploaded
/// </summary>
/// <param name="frame">The libav frame to upload.</param>
/// <param name="free">A function to free the frame on disposal.</param>
public VideoTextureUpload(AVFrame* frame, FFmpegFuncs.AvFrameFreeDelegate free)
{
Frame = frame;
freeFrame = free;
}
#region IDisposable Support
public void Dispose()
{
fixed (AVFrame** ptr = &Frame)
freeFrame(ptr);
}
#endregion
}
}
| // 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.Textures;
using osuTK.Graphics.ES30;
using FFmpeg.AutoGen;
namespace osu.Framework.Graphics.Video
{
public unsafe class VideoTextureUpload : ArrayPoolTextureUpload
{
public AVFrame* Frame;
private readonly FFmpegFuncs.AvFrameFreeDelegate freeFrame;
public override PixelFormat Format => PixelFormat.Red;
/// <summary>
/// Sets the frame cotaining the data to be uploaded
/// </summary>
/// <param name="frame">The libav frame to upload.</param>
/// <param name="free">A function to free the frame on disposal.</param>
public VideoTextureUpload(AVFrame* frame, FFmpegFuncs.AvFrameFreeDelegate free)
: base(0, 0)
{
Frame = frame;
freeFrame = free;
}
#region IDisposable Support
protected override void Dispose(bool disposing)
{
fixed (AVFrame** ptr = &Frame)
freeFrame(ptr);
base.Dispose(disposing);
}
#endregion
}
}
| mit | C# |
f0850c42e536178aceeb17a965c9b4e56aea0560 | fix typo | ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu | osu.Game.Rulesets.Mania/ManiaSettingsSubsection.cs | osu.Game.Rulesets.Mania/ManiaSettingsSubsection.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Mania.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania
{
public class ManiaSettingsSubsection : RulesetSettingsSubsection
{
protected override LocalisableString Header => "osu!mania";
public ManiaSettingsSubsection(ManiaRuleset ruleset)
: base(ruleset)
{
}
[BackgroundDependencyLoader]
private void load()
{
var config = (ManiaRulesetConfigManager)Config;
Children = new Drawable[]
{
new SettingsEnumDropdown<ManiaScrollingDirection>
{
LabelText = "Scrolling direction",
Current = config.GetBindable<ManiaScrollingDirection>(ManiaRulesetSetting.ScrollDirection)
},
new SettingsSlider<double, ManiaScrollSlider>
{
LabelText = "Scroll speed",
Current = config.GetBindable<double>(ManiaRulesetSetting.ScrollTime),
KeyboardStep = 5
},
new SettingsCheckbox
{
LabelText = "Timing-based note colouring",
Current = config.GetBindable<bool>(ManiaRulesetSetting.TimingBasedNoteColouring),
}
};
}
private class ManiaScrollSlider : OsuSliderBar<double>
{
public override LocalisableString TooltipText => $"{(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / Current.Value)} ({Current.Value}ms)";
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Mania.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania
{
public class ManiaSettingsSubsection : RulesetSettingsSubsection
{
protected override LocalisableString Header => "osu!mania";
public ManiaSettingsSubsection(ManiaRuleset ruleset)
: base(ruleset)
{
}
[BackgroundDependencyLoader]
private void load()
{
var config = (ManiaRulesetConfigManager)Config;
Children = new Drawable[]
{
new SettingsEnumDropdown<ManiaScrollingDirection>
{
LabelText = "Scrolling direction",
Current = config.GetBindable<ManiaScrollingDirection>(ManiaRulesetSetting.ScrollDirection)
},
new SettingsSlider<double, ManiaScorllSlider>
{
LabelText = "Scroll speed",
Current = config.GetBindable<double>(ManiaRulesetSetting.ScrollTime),
KeyboardStep = 5
},
new SettingsCheckbox
{
LabelText = "Timing-based note colouring",
Current = config.GetBindable<bool>(ManiaRulesetSetting.TimingBasedNoteColouring),
}
};
}
private class ManiaScorllSlider : OsuSliderBar<double>
{
public override LocalisableString TooltipText => $"{(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / Current.Value)} ({Current.Value}ms)";
}
}
}
| mit | C# |
4c00d31a2c1849d89b5b8191eaf9982909f27889 | Revert "version bump" | Kerbas-ad-astra/KSP_Contract_Window,DMagic1/KSP_Contract_Window | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KSPP_Contracts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KSPP_Contracts")]
[assembly: AssemblyCopyright("Copyright © 2014 DMagic")]
[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("f18527dd-a54e-4711-9dcd-c73a221ebb2d")]
[assembly: AssemblyVersion("1.0.1.1")]
[assembly: AssemblyFileVersion("1.0.1.1")]
[assembly: AssemblyInformationalVersion("v1.1")]
[assembly: KSPAssembly("Contracts_Window", 1, 1)]
| 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("KSPP_Contracts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KSPP_Contracts")]
[assembly: AssemblyCopyright("Copyright © 2014 DMagic")]
[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("f18527dd-a54e-4711-9dcd-c73a221ebb2d")]
[assembly: AssemblyVersion("1.0.1.2")]
[assembly: AssemblyFileVersion("1.0.1.2")]
[assembly: AssemblyInformationalVersion("v1.2")]
[assembly: KSPAssembly("Contracts_Window", 1, 2)]
| mit | C# |
996f10bfe024f86ef3df6b52d642a753060c2188 | Update version | Mataniko/IV-Play | Properties/Assemblyinfo.cs | Properties/Assemblyinfo.cs | #region
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IV/Play")]
[assembly: AssemblyCopyright("© 2019 John L. Hardy IV / Matan Bareket")]
[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("d8a332a5-9ccd-4fef-8660-00e53c990711")]
// 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.8.3.0")]
[assembly: AssemblyFileVersion("1.8.3.0")]
[assembly: AssemblyTitleAttribute("IV/Play")]
| #region
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IV/Play")]
[assembly: AssemblyCopyright("© 2019 John L. Hardy IV / Matan Bareket")]
[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("d8a332a5-9ccd-4fef-8660-00e53c990711")]
// 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.8.2.1")]
[assembly: AssemblyFileVersion("1.8.2.1")]
[assembly: AssemblyTitleAttribute("IV/Play")]
| mit | C# |
f0353f14f2fa8bfcc16ae3b1e0f4c924cf6c72ae | add ClearQueue | NDark/ndinfrastructure,NDark/ndinfrastructure | Unity/NGUIUtil/NGUIMessageQueueControllerBase.cs | Unity/NGUIUtil/NGUIMessageQueueControllerBase.cs | /**
MIT License
Copyright (c) 2017 - 2020 NDark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NGUIMessageQueueControllerBase : MonoBehaviour
{
public void ClearQueue()
{
m_MessageQueue.Clear();
}
public virtual string CurrentText
{
get{ return string.Empty;}
set{ }
}
public virtual Vector3 CurrentTextPosition
{
get{ return Vector3.zero;}
set{ }
}
public virtual Color CurrentTextColor
{
get{ return Color.black;}
set{ }
}
public virtual void ShowUI( bool _Show )
{
}
public void QueueText( string _Text )
{
m_MessageQueue.AddLast( _Text ) ;
}
void Awake()
{
SetupStructure() ;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
MessageUpdate();
}
protected virtual void MessageUpdate()
{
if( m_InAnimation )
{
CheckAnimationEnd() ;
}
else if( m_MessageQueue.Count > 0 )
{
RestartAnimation(m_MessageQueue.First.Value) ;
m_MessageQueue.RemoveFirst() ;
}
}
protected virtual void RestartAnimation( string _Text )
{
/** Reset animation position */
UpdateText( _Text ) ;
m_InAnimation = true ;
}
protected virtual void UpdateText( string _Text )
{
// assign text.
}
protected virtual void CheckAnimationEnd()
{
// check animation has finished.
/*
if( m_MessageTweenPosition.isActiveAndEnabled == false &&
m_MessageTweenAlpha.isActiveAndEnabled == false )
{
m_InAnimation = false ;
if (0 == m_MessageQueue.Count)
{
ShowUI(false);
}
}
*/
}
public virtual void TrySetupStructure()
{
if (!m_Initializaed)
{
SetupStructure();
}
}
protected virtual void SetupStructure()
{
m_Initializaed = true;
}
protected bool m_InAnimation = false ;
protected LinkedList<string> m_MessageQueue = new LinkedList<string>() ;
public bool IsInitialized { get { return m_Initializaed; } }
protected bool m_Initializaed = false ;
}
| /**
MIT License
Copyright (c) 2017 - 2020 NDark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NGUIMessageQueueControllerBase : MonoBehaviour
{
public virtual string CurrentText
{
get{ return string.Empty;}
set{ }
}
public virtual Vector3 CurrentTextPosition
{
get{ return Vector3.zero;}
set{ }
}
public virtual Color CurrentTextColor
{
get{ return Color.black;}
set{ }
}
public virtual void ShowUI( bool _Show )
{
}
public void QueueText( string _Text )
{
m_MessageQueue.AddLast( _Text ) ;
}
void Awake()
{
SetupStructure() ;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
MessageUpdate();
}
protected virtual void MessageUpdate()
{
if( m_InAnimation )
{
CheckAnimationEnd() ;
}
else if( m_MessageQueue.Count > 0 )
{
RestartAnimation(m_MessageQueue.First.Value) ;
m_MessageQueue.RemoveFirst() ;
}
}
protected virtual void RestartAnimation( string _Text )
{
/** Reset animation position */
UpdateText( _Text ) ;
m_InAnimation = true ;
}
protected virtual void UpdateText( string _Text )
{
// assign text.
}
protected virtual void CheckAnimationEnd()
{
// check animation has finished.
/*
if( m_MessageTweenPosition.isActiveAndEnabled == false &&
m_MessageTweenAlpha.isActiveAndEnabled == false )
{
m_InAnimation = false ;
if (0 == m_MessageQueue.Count)
{
ShowUI(false);
}
}
*/
}
public virtual void TrySetupStructure()
{
if (!m_Initializaed)
{
SetupStructure();
}
}
protected virtual void SetupStructure()
{
m_Initializaed = true;
}
protected bool m_InAnimation = false ;
protected LinkedList<string> m_MessageQueue = new LinkedList<string>() ;
public bool IsInitialized { get { return m_Initializaed; } }
protected bool m_Initializaed = false ;
}
| mit | C# |
4c63de7d2f669c5e2054934b51e64eb604924d9a | Add constructor info to DriverStanding | Krusen/ErgastApi.Net | src/ErgastApi/Responses/Models/Standings/DriverStanding.cs | src/ErgastApi/Responses/Models/Standings/DriverStanding.cs | using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace ErgastApi.Responses.Models.Standings
{
public class DriverStanding : Standing
{
public Driver Driver { get; set; }
/// <summary>
/// The latest constructor which the driver has driven for.
/// </summary>
public Constructor Constructor => AllConstructors.LastOrDefault();
/// <summary>
/// A list of all the constructors the driver has driven for up to this point in the season.
/// </summary>
[JsonProperty("Constructors")]
public IList<Constructor> AllConstructors { get; set; }
}
} | namespace ErgastApi.Responses.Models.Standings
{
public class DriverStanding : Standing
{
public Driver Driver { get; set; }
}
} | unlicense | C# |
874034d109b74125d87b8d1d6c44fae54476339b | Add error checking to basic auth header | IdentityModel/IdentityModelv2,IdentityModel/IdentityModel,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel2 | src/IdentityModel/Client/BasicAuthenticationHeaderValue.cs | src/IdentityModel/Client/BasicAuthenticationHeaderValue.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName));
if (password == null) password = "";
Encoding encoding = Encoding.UTF8;
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
}
} | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
Encoding encoding = Encoding.UTF8;
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
}
} | apache-2.0 | C# |
ecf00da10b26c962d3363fd2f01c88b4f77e4ae9 | Fix race condition in SystemEvents tests | ViktorHofer/corefx,wtgodbe/corefx,ptoonen/corefx,mmitche/corefx,Jiayili1/corefx,Jiayili1/corefx,BrennanConroy/corefx,ptoonen/corefx,shimingsg/corefx,BrennanConroy/corefx,mmitche/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,Jiayili1/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,ericstj/corefx,ptoonen/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,ptoonen/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,Jiayili1/corefx,mmitche/corefx,Jiayili1/corefx,Jiayili1/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,mmitche/corefx,Jiayili1/corefx,ericstj/corefx,BrennanConroy/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx | src/Microsoft.Win32.SystemEvents/tests/SystemEventsTest.cs | src/Microsoft.Win32.SystemEvents/tests/SystemEventsTest.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 Xunit;
using static Interop;
namespace Microsoft.Win32.SystemEventsTests
{
public abstract class SystemEventsTest
{
IntPtr s_hwnd = IntPtr.Zero;
public const int PostMessageWait = 10000;
public const int ExpectedEventMultiplier = 1000;
public const int UnexpectedEventMultiplier = 10;
protected IntPtr SendMessage(int msg, IntPtr wParam, IntPtr lParam)
{
EnsureHwnd();
return User32.SendMessageW(s_hwnd, msg, wParam, lParam);
}
private void EnsureHwnd()
{
if (s_hwnd == IntPtr.Zero)
{
// wait for the window to be created
var windowReadyField = typeof(SystemEvents).GetField("s_eventWindowReady", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic) ?? // corefx
typeof(SystemEvents).GetField("eventWindowReady", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); // desktop
Assert.NotNull(windowReadyField);
var windowReadyEvent = windowReadyField.GetValue(null) as ManualResetEvent;
if (windowReadyEvent != null)
{
// on an STA thread the HWND is created in the same thread synchronously when attaching to an event handler
// if we're on an MTA thread, a new thread is created to handle events and that thread creates the window, wait for it to complete.
Assert.True(windowReadyEvent.WaitOne(PostMessageWait * ExpectedEventMultiplier));
}
// locate the hwnd used by SystemEvents in this domain
var windowClassNameField = typeof(SystemEvents).GetField("s_className", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic) ?? // corefx
typeof(SystemEvents).GetField("className", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); // desktop
Assert.NotNull(windowClassNameField);
var windowClassName = windowClassNameField.GetValue(null) as string;
Assert.NotNull(windowClassName);
s_hwnd = User32.FindWindowW(windowClassName, null);
Assert.NotEqual(s_hwnd, IntPtr.Zero);
}
}
}
}
| // 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 Xunit;
using static Interop;
namespace Microsoft.Win32.SystemEventsTests
{
public abstract class SystemEventsTest
{
IntPtr s_hwnd = IntPtr.Zero;
public const int PostMessageWait = 10000;
public const int ExpectedEventMultiplier = 1000;
public const int UnexpectedEventMultiplier = 10;
protected IntPtr SendMessage(int msg, IntPtr wParam, IntPtr lParam)
{
if (s_hwnd == IntPtr.Zero)
{
// locate the hwnd used by SystemEvents in this domain
var windowClassNameField = typeof(SystemEvents).GetField("s_className", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
if (windowClassNameField == null)
{
// desktop doesn't use the s_ prefix
windowClassNameField = typeof(SystemEvents).GetField("className", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
}
Assert.NotNull(windowClassNameField);
var windowClassName = windowClassNameField.GetValue(null) as string;
Assert.NotNull(windowClassName);
s_hwnd = User32.FindWindowW(windowClassName, null);
Assert.NotEqual(s_hwnd, IntPtr.Zero);
}
return User32.SendMessageW(s_hwnd, msg, wParam, lParam);
}
}
}
| mit | C# |
c86f00b1374d72c390a7665e2c6ba86eac232297 | Switch to version 1.4.0 | Abc-Arbitrage/Zebus,biarne-a/Zebus | src/SharedVersionInfo.cs | src/SharedVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.4.0")]
[assembly: AssemblyFileVersion("1.4.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
| using System.Reflection;
[assembly: AssemblyVersion("1.3.7")]
[assembly: AssemblyFileVersion("1.3.7")]
[assembly: AssemblyInformationalVersion("1.3.7")]
| mit | C# |
765317466c304520f2b86a458f7cd760c373acf7 | Revert "bump only the revision version number, since this is a no-code change, just a nuget package metadata change" | Brightspace/D2L.Security.OAuth2 | D2L.Security.OAuth2/Properties/AssemblyInfo.cs | D2L.Security.OAuth2/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("D2L.Security.OAuth2")]
[assembly: AssemblyDescription("Library for interacting with OAuth2 based flows in D2L systems")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Desire2Learn")]
[assembly: AssemblyProduct("D2L.Security.OAuth2")]
[assembly: AssemblyCopyright("Copyright © D2L 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("88113573-2f5d-4c30-969a-46f32f2f4e9c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "4.4.3.0" )]
[assembly: AssemblyFileVersion( "4.4.3.0" )]
[assembly: AssemblyInformationalVersion( "4.4.3.0" )]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("D2L.Security.OAuth2")]
[assembly: AssemblyDescription("Library for interacting with OAuth2 based flows in D2L systems")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Desire2Learn")]
[assembly: AssemblyProduct("D2L.Security.OAuth2")]
[assembly: AssemblyCopyright("Copyright © D2L 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("88113573-2f5d-4c30-969a-46f32f2f4e9c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "4.4.2.1" )]
[assembly: AssemblyFileVersion( "4.4.2.1" )]
[assembly: AssemblyInformationalVersion( "4.4.2.1" )]
| apache-2.0 | C# |
db76125790885bbfa468b43013b8a8aa696956ba | Fix dead links | blrchen/AzureSpeed,blrchen/AzureSpeed,blrchen/AzureSpeed,blrchen/AzureSpeed | AzureSpeed.Web.App/Views/Azure/Reference.cshtml | AzureSpeed.Web.App/Views/Azure/Reference.cshtml | @{
ViewBag.Title = "Reference";
}
<div class="container-fluid">
<div class="page-header">
<h3>@ViewBag.Title</h3>
</div>
<div class="row">
<div class="col-md-12">
<ul class="list-unstyled">
<li>
<a href="https://azure.microsoft.com/en-us/regions/" target="_blank">Azure Datacenter Regions</a>
</li>
<li>
<a href="https://docs.microsoft.com/en-us/azure/cdn/cdn-pop-locations" target="_blank">Azure Content Delivery Network (CDN) Node Locations</a>
</li>
<li>
<a href="http://msdn.microsoft.com/library/azure/dn249410.aspx" target="_blank">Azure Storage Scalability and Performance Targets</a>
</li>
<li>
<a href="http://azure.microsoft.com/en-us/documentation/articles/azure-subscription-service-limits/" target="_blank">Azure Subscription and Service Limits, Quotas, and Constraints</a>
</li>
<li>
<a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html" target="_blank">AWS Regions and Availability Zones</a>
</li>
</ul>
</div>
</div>
</div> | @{
ViewBag.Title = "Reference";
}
<div class="container-fluid">
<div class="page-header">
<h3>@ViewBag.Title</h3>
</div>
<div class="row">
<div class="col-md-12">
<ul class="list-unstyled">
<li>
<a href="https://azure.microsoft.com/en-us/regions/" target="_blank">Azure Datacenter Regions</a>
</li>
<li>
<a href="http://msdn.microsoft.com/library/azure/dn175718.aspx" target="_blank">Azure Datacenter IP Ranges</a>
</li>
<li>
<a href="http://msdn.microsoft.com/library/azure/gg680302.aspx" target="_blank">Azure Content Delivery Network (CDN) Node Locations</a>
</li>
<li>
<a href="http://msdn.microsoft.com/library/azure/dn249410.aspx" target="_blank">Azure Storage Scalability and Performance Targets</a>
</li>
<li>
<a href="http://azure.microsoft.com/en-us/documentation/articles/azure-subscription-service-limits/" target="_blank">Azure Subscription and Service Limits, Quotas, and Constraints</a>
</li>
<li>
<a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html" target="_blank">AWS Regions and Availability Zones</a>
</li>
</ul>
</div>
</div>
</div> | mit | C# |
2eed4b0539d1678f7bc251204150a74b0dfbb76f | Fix missing ; | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Queries/GetSUTARequest.cs | Battery-Commander.Web/Queries/GetSUTARequest.cs | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetSUTARequest : IRequest<SUTA>
{
[FromRoute]
public int Id { get; set; }
private class Handler : IRequestHandler<GetSUTARequest, SUTA>
{
private readonly Database db;
public Handler(Database db)
{
this.db = db;
}
public async Task<SUTA> Handle(GetSUTARequest request, CancellationToken cancellationToken)
{
return await ById(db, request.Id);
}
}
public static async Task<SUTA> ById(Database db, int id)
{
return
await GetSUTARequests
.AsQueryable(db)
.Where(suta => suta.Id == id)
.SingleOrDefaultAsync();
}
}
}
| using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetSUTARequest : IRequest<SUTA>
{
[FromRoute]
public int Id { get; set; }
private class Handler : IRequestHandler<GetSUTARequest, SUTA>
{
private readonly Database db;
public Handler(Database db)
{
this.db = db;
}
public async Task<SUTA> Handle(GetSUTARequest request, CancellationToken cancellationToken)
{
return await ById(db, request.Id);
}
}
public static async Task<SUTA> ById(Database db, int id)
{
return
await GetSUTARequests
.AsQueryable(db)
.Where(suta => suta.Id == id)
.SingleOrDefaultAsync()
}
}
}
| mit | C# |
1230d0b8b3a29bc8a9145eb0ea9d607fc5d44dbd | Add another input datetime format | jozefizso/FogBugz-ExtendedEvents,jozefizso/FogBugz-ExtendedEvents | FBExtendedEvents.Tests/DatabaseHelpersTests.cs | FBExtendedEvents.Tests/DatabaseHelpersTests.cs | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using NUnit.Framework;
namespace FBExtendedEvents.Tests
{
[TestFixture]
public class DatabaseHelpersTests
{
public static IEnumerable<object[]> ValidDateTimeInputValues
{
get
{
yield return new object[] { "2015-01-01T17:47:27.0640000Z", new DateTime(2015, 1, 1, 17, 47, 27, 64, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.064000Z", new DateTime(2015, 1, 1, 17, 47, 27, 64, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27Z", new DateTime(2015, 1, 1, 17, 47, 27, 0, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.0000000+01:00", new DateTime(2015, 1, 1, 16, 47, 27, 0, DateTimeKind.Utc) };
yield return new object[] { "2016-12-09T14:50:47+01:00", new DateTime(2016, 12, 9, 13, 50, 47, 0, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.0645630Z", new DateTime(635557312470645630, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.064563Z", new DateTime(635557312470645630, DateTimeKind.Utc) };
}
}
[Test]
[TestCaseSource(nameof(ValidDateTimeInputValues))]
public void GetDateTime_ValidDateTimeStringValue_ConvertsToCorrectDateTime(string inputValue, DateTime expecteDateTimeUtc)
{
// Arrange
var defaultValue = DateTime.MinValue;
// Act
var actualDateTime = DatabaseHelpers.GetDateTime(inputValue, defaultValue);
// Assert
Assert.AreEqual(actualDateTime.Kind, DateTimeKind.Utc);
Assert.AreEqual(expecteDateTimeUtc, actualDateTime);
}
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using NUnit.Framework;
namespace FBExtendedEvents.Tests
{
[TestFixture]
public class DatabaseHelpersTests
{
public static IEnumerable<object[]> ValidDateTimeInputValues
{
get
{
yield return new object[] { "2015-01-01T17:47:27.0640000Z", new DateTime(2015, 1, 1, 17, 47, 27, 64, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.064000Z", new DateTime(2015, 1, 1, 17, 47, 27, 64, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27Z", new DateTime(2015, 1, 1, 17, 47, 27, 0, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.0000000+01:00", new DateTime(2015, 1, 1, 16, 47, 27, 0, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.0645630Z", new DateTime(635557312470645630, DateTimeKind.Utc) };
yield return new object[] { "2015-01-01T17:47:27.064563Z", new DateTime(635557312470645630, DateTimeKind.Utc) };
}
}
[Test]
[TestCaseSource(nameof(ValidDateTimeInputValues))]
public void GetDateTime_ValidDateTimeStringValue_ConvertsToCorrectDateTime(string inputValue, DateTime expecteDateTimeUtc)
{
// Arrange
var defaultValue = DateTime.MinValue;
// Act
var actualDateTime = DatabaseHelpers.GetDateTime(inputValue, defaultValue);
// Assert
Assert.AreEqual(actualDateTime.Kind, DateTimeKind.Utc);
Assert.AreEqual(expecteDateTimeUtc, actualDateTime);
}
}
}
| mit | C# |
934a6131f06347ae52b7fde0037789240b4f79f8 | Fix AuthFeature remove from modified collection bug | NServiceKit/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,ZocDoc/ServiceStack,MindTouch/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,nataren/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,MindTouch/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,meebey/ServiceStack,nataren/NServiceKit,meebey/ServiceStack,timba/NServiceKit,MindTouch/NServiceKit | src/ServiceStack.ServiceInterface/AuthFeature.cs | src/ServiceStack.ServiceInterface/AuthFeature.cs | using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.FluentValidation.Internal;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.WebHost.Endpoints;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Enable the authentication feature and configure the AuthService.
/// </summary>
public class AuthFeature : IPlugin
{
public const string AdminRole = "Admin";
public static bool AddUserIdHttpHeader = true;
private readonly Func<IAuthSession> sessionFactory;
private readonly IAuthProvider[] authProviders;
public Dictionary<Type, string[]> ServiceRoutes { get; set; }
public List<IPlugin> RegisterPlugins { get; set; }
public bool IncludeAssignRoleServices
{
set
{
if (!value)
{
(from registerService in ServiceRoutes
where registerService.Key == typeof(AssignRolesService)
|| registerService.Key == typeof(UnAssignRolesService)
select registerService.Key).ToList()
.ForEach(x => ServiceRoutes.Remove(x));
}
}
}
public AuthFeature(Func<IAuthSession> sessionFactory, IAuthProvider[] authProviders)
{
this.sessionFactory = sessionFactory;
this.authProviders = authProviders;
ServiceRoutes = new Dictionary<Type, string[]> {
{ typeof(AuthService), new[]{"/auth", "/auth/{provider}"} },
{ typeof(AssignRolesService), new[]{"/assignroles"} },
{ typeof(UnAssignRolesService), new[]{"/unassignroles"} },
};
RegisterPlugins = new List<IPlugin> {
new SessionFeature()
};
}
public void Register(IAppHost appHost)
{
AuthService.Init(sessionFactory, authProviders);
var unitTest = appHost == null;
if (unitTest) return;
foreach (var registerService in ServiceRoutes)
{
appHost.RegisterService(registerService.Key, registerService.Value);
}
RegisterPlugins.ForEach(x => appHost.LoadPlugin(x));
}
public static TimeSpan? GetDefaultSessionExpiry()
{
var authProvider = AuthService.AuthProviders.FirstOrDefault() as AuthProvider;
return authProvider == null ? null : authProvider.SessionExpiry;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.FluentValidation.Internal;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.WebHost.Endpoints;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Enable the authentication feature and configure the AuthService.
/// </summary>
public class AuthFeature : IPlugin
{
public const string AdminRole = "Admin";
public static bool AddUserIdHttpHeader = true;
private readonly Func<IAuthSession> sessionFactory;
private readonly IAuthProvider[] authProviders;
public Dictionary<Type, string[]> ServiceRoutes { get; set; }
public List<IPlugin> RegisterPlugins { get; set; }
public bool IncludeAssignRoleServices
{
set
{
if (!value)
{
(from registerService in ServiceRoutes
where registerService.Key == typeof(AssignRolesService)
|| registerService.Key == typeof(UnAssignRolesService)
select registerService.Key)
.ForEach(x => ServiceRoutes.Remove(x));
}
}
}
public AuthFeature(Func<IAuthSession> sessionFactory, IAuthProvider[] authProviders)
{
this.sessionFactory = sessionFactory;
this.authProviders = authProviders;
ServiceRoutes = new Dictionary<Type, string[]> {
{ typeof(AuthService), new[]{"/auth", "/auth/{provider}"} },
{ typeof(AssignRolesService), new[]{"/assignroles"} },
{ typeof(UnAssignRolesService), new[]{"/unassignroles"} },
};
RegisterPlugins = new List<IPlugin> {
new SessionFeature()
};
}
public void Register(IAppHost appHost)
{
AuthService.Init(sessionFactory, authProviders);
var unitTest = appHost == null;
if (unitTest) return;
foreach (var registerService in ServiceRoutes)
{
appHost.RegisterService(registerService.Key, registerService.Value);
}
RegisterPlugins.ForEach(x => appHost.LoadPlugin(x));
}
public static TimeSpan? GetDefaultSessionExpiry()
{
var authProvider = AuthService.AuthProviders.FirstOrDefault() as AuthProvider;
return authProvider == null ? null : authProvider.SessionExpiry;
}
}
} | bsd-3-clause | C# |
d3b8f291dea0101e1f831f9cb8d6eec5ee2b3037 | update path | lianzhao/wiki2dict,lianzhao/wiki2dict,lianzhao/wiki2dict | src/Wiki2Dict/Program.cs | src/Wiki2Dict/Program.cs | using System;
using System.Net.Http;
using System.Threading.Tasks;
using Autofac;
using Wiki2Dict.Core;
using Wiki2Dict.Kindle;
using Wiki2Dict.Wiki;
namespace Wiki2Dict
{
class Program
{
static void Main(string[] args)
{
Run(args).Wait();
}
private static async Task Run(string[] args)
{
try
{
var baseAddr = "http://coppermind.huiji.wiki/";
var builder = new ContainerBuilder();
builder.Register(ctx => new HttpClient() {BaseAddress = new Uri(baseAddr)}).InstancePerDependency();
builder.RegisterType<GetDescriptionAction>().AsImplementedInterfaces().InstancePerDependency();
builder.Register(
ctx => new Wiki.Wiki(ctx.Resolve<HttpClient>(), ctx.ResolveOptional<IDictEntryAction>()))
.AsImplementedInterfaces()
.InstancePerDependency();
builder.RegisterInstance(new DictConfig
{
FilePath = @"..\..\dist\dict.html",
TemplateFilePath = @"..\..\resources\knidle_dict_template.html",
EntryTemplateFilePath = @"..\..\resources\knidle_dict_entry_template.html",
}).SingleInstance();
builder.RegisterType<Dict>().AsImplementedInterfaces().SingleInstance();
var container = builder.Build();
var wiki = container.Resolve<IWiki>();
var entries = await wiki.GetEntriesAsync().ConfigureAwait(false);
var dict = container.Resolve<IDict>();
await dict.SaveAsync(entries).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| using System;
using System.Net.Http;
using System.Threading.Tasks;
using Autofac;
using Wiki2Dict.Core;
using Wiki2Dict.Kindle;
using Wiki2Dict.Wiki;
namespace Wiki2Dict
{
class Program
{
static void Main(string[] args)
{
Run(args).Wait();
}
private static async Task Run(string[] args)
{
try
{
var baseAddr = "http://coppermind.huiji.wiki/";
var builder = new ContainerBuilder();
builder.Register(ctx => new HttpClient() {BaseAddress = new Uri(baseAddr)}).InstancePerDependency();
builder.RegisterType<GetDescriptionAction>().AsImplementedInterfaces().InstancePerDependency();
builder.Register(
ctx => new Wiki.Wiki(ctx.Resolve<HttpClient>(), ctx.ResolveOptional<IDictEntryAction>()))
.AsImplementedInterfaces()
.InstancePerDependency();
builder.RegisterInstance(new DictConfig
{
FilePath = @"..\..\..\..\dist\dict.html",
TemplateFilePath = @"..\..\..\..\resources\knidle_dict_template.html",
EntryTemplateFilePath = @"..\..\..\..\resources\knidle_dict_entry_template.html",
}).SingleInstance();
builder.RegisterType<Dict>().AsImplementedInterfaces().SingleInstance();
var container = builder.Build();
var wiki = container.Resolve<IWiki>();
var entries = await wiki.GetEntriesAsync().ConfigureAwait(false);
var dict = container.Resolve<IDict>();
await dict.SaveAsync(entries).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| mit | C# |
f0f8a80cd6eeab1e8cef643d92000f109e8dc1e4 | Add test setting for TextTrackId. | mfilippov/vimeo-dot-net,mohibsheth/vimeo-dot-net,needham-develop/vimeo-dot-net | src/VimeoDotNet.Tests/Settings/SettingsLoader.cs | src/VimeoDotNet.Tests/Settings/SettingsLoader.cs | using System;
using System.IO;
using Newtonsoft.Json;
namespace VimeoDotNet.Tests.Settings
{
internal class SettingsLoader
{
private const string SETTINGS_FILE = "vimeoSettings.json";
public static VimeoApiTestSettings LoadSettings()
{
var fromEnv = GetSettingsFromEnvVars();
if (fromEnv.UserId != 0)
return fromEnv;
if (!File.Exists(SETTINGS_FILE))
{
// File was not found so create a new one with blanks
SaveSettings(new VimeoApiTestSettings());
throw new Exception(string.Format("The file {0} was not found. A file was created, please fill in the information", SETTINGS_FILE));
}
var json = File.ReadAllText(SETTINGS_FILE);
return JsonConvert.DeserializeObject<VimeoApiTestSettings>(json);
}
private static VimeoApiTestSettings GetSettingsFromEnvVars()
{
long userId;
long.TryParse(Environment.GetEnvironmentVariable("UserId"), out userId);
long albumId;
long.TryParse(Environment.GetEnvironmentVariable("AlbumId"), out albumId);
long channelId;
long.TryParse(Environment.GetEnvironmentVariable("ChannelId"), out channelId);
long videoId;
long.TryParse(Environment.GetEnvironmentVariable("VideoId"), out videoId);
long textTrackId;
long.TryParse(Environment.GetEnvironmentVariable("TextTrackId"), out textTrackId);
return new VimeoApiTestSettings()
{
ClientId = Environment.GetEnvironmentVariable("ClientId"),
ClientSecret = Environment.GetEnvironmentVariable("ClientSecret"),
AccessToken = Environment.GetEnvironmentVariable("AccessToken"),
UserId = userId,
AlbumId = albumId,
ChannelId = channelId,
VideoId = videoId,
TextTrackId = textTrackId
};
}
public static void SaveSettings(VimeoApiTestSettings settings)
{
var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
System.IO.File.WriteAllText(SETTINGS_FILE, json);
}
}
}
| using System;
using System.IO;
using Newtonsoft.Json;
namespace VimeoDotNet.Tests.Settings
{
internal class SettingsLoader
{
private const string SETTINGS_FILE = "vimeoSettings.json";
public static VimeoApiTestSettings LoadSettings()
{
var fromEnv = GetSettingsFromEnvVars();
if (fromEnv.UserId != 0)
return fromEnv;
if (!File.Exists(SETTINGS_FILE))
{
// File was not found so create a new one with blanks
SaveSettings(new VimeoApiTestSettings());
throw new Exception(string.Format("The file {0} was not found. A file was created, please fill in the information", SETTINGS_FILE));
}
var json = File.ReadAllText(SETTINGS_FILE);
return JsonConvert.DeserializeObject<VimeoApiTestSettings>(json);
}
private static VimeoApiTestSettings GetSettingsFromEnvVars()
{
long userId;
long.TryParse(Environment.GetEnvironmentVariable("UserId"), out userId);
long albumId;
long.TryParse(Environment.GetEnvironmentVariable("AlbumId"), out albumId);
long channelId;
long.TryParse(Environment.GetEnvironmentVariable("ChannelId"), out channelId);
long videoId;
long.TryParse(Environment.GetEnvironmentVariable("VideoId"), out videoId);
return new VimeoApiTestSettings()
{
ClientId = Environment.GetEnvironmentVariable("ClientId"),
ClientSecret = Environment.GetEnvironmentVariable("ClientSecret"),
AccessToken = Environment.GetEnvironmentVariable("AccessToken"),
UserId = userId,
AlbumId = albumId,
ChannelId = channelId,
VideoId = videoId,
};
}
public static void SaveSettings(VimeoApiTestSettings settings)
{
var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
System.IO.File.WriteAllText(SETTINGS_FILE, json);
}
}
}
| mit | C# |
c2ba47821a69993412a93c012c39ce8d90ff2b1e | Fix for get current user on anon page | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Queries/GetCurrentUser.cs | Battery-Commander.Web/Queries/GetCurrentUser.cs | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetCurrentUser : IRequest<Soldier>
{
private class Handler : IRequestHandler<GetCurrentUser, Soldier>
{
private readonly Database db;
private readonly IHttpContextAccessor http;
public Handler(Database db, IHttpContextAccessor http)
{
this.db = db;
this.http = http;
}
public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken)
{
var email =
http
.HttpContext
.User?
.Identity?
.Name;
if (string.IsNullOrWhiteSpace(email)) return default(Soldier);
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.CivilianEmail == email)
.AsNoTracking()
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
}
| using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetCurrentUser : IRequest<Soldier>
{
private class Handler : IRequestHandler<GetCurrentUser, Soldier>
{
private readonly Database db;
private readonly IHttpContextAccessor http;
public Handler(Database db, IHttpContextAccessor http)
{
this.db = db;
this.http = http;
}
public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken)
{
var email =
http
.HttpContext
.User?
.Identity?
.Name;
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.CivilianEmail == email)
.AsNoTracking()
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.