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 |
|---|---|---|---|---|---|---|---|---|
4a10aec8d413787184a874b6c3878e96d0ec2cd0 | make map hack work in multiplayer | ad510/plausible-deniability | Assets/Scripts/SimEvt/CmdEvt/CmdEvt.cs | Assets/Scripts/SimEvt/CmdEvt/CmdEvt.cs | // Copyright (c) 2013-2014 Andrew Downing
// 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 ProtoBuf;
/// <summary>
/// base class for user commands
/// </summary>
[ProtoContract]
[ProtoInclude(10, typeof(UnitCmdEvt))]
[ProtoInclude(11, typeof(GoLiveCmdEvt))]
[ProtoInclude(12, typeof(MapHackCmdEvt))]
public abstract class CmdEvt : SimEvt { }
| // Copyright (c) 2013-2014 Andrew Downing
// 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 ProtoBuf;
/// <summary>
/// base class for user commands
/// </summary>
[ProtoContract]
[ProtoInclude(10, typeof(UnitCmdEvt))]
[ProtoInclude(11, typeof(GoLiveCmdEvt))]
public abstract class CmdEvt : SimEvt { }
| mit | C# |
4816c034cedac503688438f7296b2196db865166 | bump version number | vendettamit/BenchmarkIt,bodyloss/BenchmarkIt | BenchmarkIt/Properties/AssemblyInfo.cs | BenchmarkIt/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("BenchmarkIt")]
[assembly: AssemblyDescription ("Benchmark utility")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("joeyciechanowicz")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.1.*")] | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("BenchmarkIt")]
[assembly: AssemblyDescription ("Benchmark utility")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("joeyciechanowicz")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
b93ac92d8c02a573319fe8365ed1dcbc95849e90 | Rename to maui application | Caliburn-Micro/Caliburn.Micro | samples/setup/Setup.Maui/App.xaml.cs | samples/setup/Setup.Maui/App.xaml.cs | using Caliburn.Micro.Maui;
using Setup.Maui.ViewModels;
namespace Setup.Maui
{
public partial class App : Caliburn.Micro.Maui.MauiApplication
{
public App()
{
InitializeComponent();
Initialize();
DisplayRootViewForAsync<MainViewModel>();
}
}
}
| using Caliburn.Micro.Maui;
using Setup.Maui.ViewModels;
namespace Setup.Maui
{
public partial class App : Caliburn.Micro.Maui.FormsApplication
{
public App()
{
InitializeComponent();
Initialize();
DisplayRootViewForAsync<MainViewModel>();
}
}
}
| mit | C# |
1b04145b486e799ca8ad64d88c189ac038511a11 | Fix default color temperature values | fistak/MaterialColor | Common/Data/TemperatureOverlayState.cs | Common/Data/TemperatureOverlayState.cs | using System.Collections.Generic;
namespace Common.Data
{
public class TemperatureOverlayState
{
public bool CustomRangesEnabled { get; set; } = true;
public List<float> Temperatures => new List<float>
{
Aqua, Turquoise, Blue, Green, Lime, Orange, RedOrange, Red
};
public float Red { get; set; } = 1800;
public float RedOrange { get; set; } = 0.1f;
public float Orange { get; set; } = 323;
public float Lime { get; set; } = 293;
public float Green { get; set; } = 273;
public float Blue { get; set; } = 0.2f;
public float Turquoise { get; set; } = 0.1f;
public float Aqua { get; set; } = 0;
public bool LogThresholds { get; set; } = false;
}
}
| using System.Collections.Generic;
namespace Common.Data
{
public class TemperatureOverlayState
{
public bool CustomRangesEnabled { get; set; } = true;
public List<float> Temperatures => new List<float>
{
Aqua, Turquoise, Blue, Green, Lime, Orange, RedOrange, Red
};
public float Red { get; set; } = 1800;
public float RedOrange { get; set; } = 773;
public float Orange { get; set; } = 373;
public float Lime { get; set; } = 303;
public float Green { get; set; } = 293;
public float Blue { get; set; } = 0.1f;
public float Turquoise { get; set; } = 273;
public float Aqua { get; set; } = 0;
public bool LogThresholds { get; set; } = false;
}
}
| mit | C# |
14879acd83c28391fc0f2b588a2f00fe47afbe3f | Fix possible nullref | peppy/osu,ZLima12/osu,naoey/osu,johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,DrabWeb/osu,2yangk23/osu,NeoAdonis/osu,naoey/osu,smoogipooo/osu,naoey/osu,smoogipoo/osu,ppy/osu,johnneijzen/osu,2yangk23/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu | osu.Game/Screens/Multi/Match/Components/HostInfo.cs | osu.Game/Screens/Multi/Match/Components/HostInfo.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 osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Containers;
using osu.Game.Online.Chat;
using osu.Game.Online.Multiplayer;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Screens.Multi.Match.Components
{
public class HostInfo : CompositeDrawable
{
public HostInfo(Room room)
{
AutoSizeAxes = Axes.X;
Height = 50;
LinkFlowContainer linkContainer;
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5, 0),
Children = new Drawable[]
{
new UpdateableAvatar
{
Size = new Vector2(50),
User = room.Host.Value
},
new FillFlowContainer
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Child = linkContainer = new LinkFlowContainer { AutoSizeAxes = Axes.Both }
}
}
};
if (room.Host.Value != null)
{
linkContainer.AddText("hosted by");
linkContainer.NewLine();
linkContainer.AddLink(room.Host.Value.Username, null, LinkAction.OpenUserProfile, room.Host.Value.Id.ToString(), "View Profile", s => s.Font = "Exo2.0-BoldItalic");
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Containers;
using osu.Game.Online.Chat;
using osu.Game.Online.Multiplayer;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Screens.Multi.Match.Components
{
public class HostInfo : CompositeDrawable
{
public HostInfo(Room room)
{
AutoSizeAxes = Axes.X;
Height = 50;
LinkFlowContainer linkContainer;
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5, 0),
Children = new Drawable[]
{
new UpdateableAvatar
{
Size = new Vector2(50),
User = room.Host.Value
},
new FillFlowContainer
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Child = linkContainer = new LinkFlowContainer { AutoSizeAxes = Axes.Both }
}
}
};
linkContainer.AddText("hosted by");
linkContainer.NewLine();
linkContainer.AddLink(room.Host.Value.Username, null, LinkAction.OpenUserProfile, room.Host.Value.Id.ToString(), "View Profile", s => s.Font = "Exo2.0-BoldItalic");
}
}
}
| mit | C# |
f17c7227f2222adaf93b4995ac7c81232ff9b47b | Update Error.cs | smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk | main/Smartsheet/Api/Models/Error.cs | main/Smartsheet/Api/Models/Error.cs | // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// 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.
// %[license]
namespace Smartsheet.Api.Models
{
/// <summary>
/// Represents Error object.
/// </summary>
public class Error
{
/// <summary>
/// Represents the error code.
/// </summary>
private int? errorCode;
/// <summary>
/// Represents the message.
/// </summary>
private string message;
/// <summary>
/// Reference Id of the specific error occurrence.
/// </summary>
private string refId;
/// <summary>
/// Additional error detail if it is available
/// </summary>
private object detail;
/// <summary>
/// Gets the error code.
/// </summary>
/// <returns> the error code </returns>
public virtual int? ErrorCode
{
get
{
return errorCode;
}
set
{
this.errorCode = value;
}
}
/// <summary>
/// Gets the message.
/// </summary>
/// <returns> the message </returns>
public virtual string Message
{
get
{
return message;
}
set
{
this.message = value;
}
}
/// <summary>
/// Gets the refId
/// </summary>
/// <returns> the refId </returns>
public virtual string RefId
{
get
{
return refId;
}
set
{
this.refId = value;
}
}
/// <summary>
/// Gets additional error detail if available
/// </summary>
/// <returns> error detail </returns>
public virtual object Detail
{
get
{
return detail;
}
set
{
this.detail = value;
}
}
}
}
| // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// 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.
// %[license]
namespace Smartsheet.Api.Models
{
/// <summary>
/// Represents Error object.
/// </summary>
public class Error
{
/// <summary>
/// Represents the error Code.
/// </summary>
private int? errorCode;
/// <summary>
/// Represents the Message.
/// </summary>
private string message;
/// <summary>
/// Reference Id of the specific error occurrence.
/// </summary>
private string refId;
/// <summary>
/// Additional error detail if it is available
/// </summary>
private object detail;
/// <summary>
/// Gets the error Code.
/// </summary>
/// <returns> the error Code </returns>
public virtual int? ErrorCode
{
get
{
return errorCode;
}
set
{
this.errorCode = value;
}
}
/// <summary>
/// Gets the Message.
/// </summary>
/// <returns> the Message </returns>
public virtual string Message
{
get
{
return message;
}
set
{
this.message = value;
}
}
/// <summary>
/// Gets the refId
/// </summary>
/// <returns> the refId </returns>
public virtual string RefId
{
get
{
return refId;
}
set
{
this.refId = value;
}
}
/// <summary>
/// Gets additional error detail if available
/// </summary>
/// <returns> error detail </returns>
public virtual object Detail
{
get
{
return detail;
}
set
{
this.detail = value;
}
}
}
} | apache-2.0 | C# |
c00d9b89e2354678120794b8bef7f13a313a88a8 | Update copyright | msgpack/msgpack-cli,msgpack/msgpack-cli | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2016 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
// Universal informations for entire MsgPack for CLI.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010-2017" )]
[assembly: AssemblyProduct( "MessagePack" )]
[assembly: CLSCompliant( true )]
[assembly: ComVisible( false )]
[assembly: NeutralResourcesLanguage( "en-US" )]
// This version represents API compatibility.
// Major : Represents Major update like re-architecting, remove obsoleted APIs etc.
// Minor : Represents Minor update like adding new feature, obsoleting APIs, fix specification issues, etc.
// Build/Revision : Always 0 since CLI implementations does not care these number, so these changes cause some binding failures.
[assembly: AssemblyVersion( "0.9.0.0" )]
// This version represents libarary 'version' for human beings.
// Major : Same as AssemblyVersion.
// Minor : Same as AssemblyVersion.
// Build : Bug fixes and improvements, which does not break API contract, but may break some code depends on internal implementation behaviors.
// For example, some programs use reflection to retrieve private fields, analyse human readable exception messages or stack trace, or so.
// Revision : Reserced. It might be used to indicate target platform or patch.
[assembly: AssemblyInformationalVersion( "0.9.0-dev" )]
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2016 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
// Universal informations for entire MsgPack for CLI.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010-2016" )]
[assembly: AssemblyProduct( "MessagePack" )]
[assembly: CLSCompliant( true )]
[assembly: ComVisible( false )]
[assembly: NeutralResourcesLanguage( "en-US" )]
// This version represents API compatibility.
// Major : Represents Major update like re-architecting, remove obsoleted APIs etc.
// Minor : Represents Minor update like adding new feature, obsoleting APIs, fix specification issues, etc.
// Build/Revision : Always 0 since CLI implementations does not care these number, so these changes cause some binding failures.
[assembly: AssemblyVersion( "0.9.0.0" )]
// This version represents libarary 'version' for human beings.
// Major : Same as AssemblyVersion.
// Minor : Same as AssemblyVersion.
// Build : Bug fixes and improvements, which does not break API contract, but may break some code depends on internal implementation behaviors.
// For example, some programs use reflection to retrieve private fields, analyse human readable exception messages or stack trace, or so.
// Revision : Reserced. It might be used to indicate target platform or patch.
[assembly: AssemblyInformationalVersion( "0.9.0-dev" )]
| apache-2.0 | C# |
df7530b752e428ef080f332d8b317412937a4ee4 | Add description to service resource | digirati-co-uk/iiif-model,Riksarkivet/iiif-model,dalbymodo/DalbyExperiment | Digirati.IIIF/Model/Types/Service.cs | Digirati.IIIF/Model/Types/Service.cs | using Digirati.IIIF.Model.JsonLD;
using Newtonsoft.Json;
namespace Digirati.IIIF.Model.Types
{
public class Service : JSONLDBase, IService
{
[JsonProperty(Order = 10, PropertyName = "profile")]
public dynamic Profile { get; set; }
[JsonProperty(Order = 11, PropertyName = "label")]
public MetaDataValue Label { get; set; }
[JsonProperty(Order = 12, PropertyName = "description")]
public MetaDataValue Description { get; set; }
}
}
| using Digirati.IIIF.Model.JsonLD;
using Newtonsoft.Json;
namespace Digirati.IIIF.Model.Types
{
public class Service : JSONLDBase, IService
{
[JsonProperty(Order = 10, PropertyName = "profile")]
public dynamic Profile { get; set; }
[JsonProperty(Order = 11, PropertyName = "label")]
public MetaDataValue Label { get; set; }
}
}
| mit | C# |
9cb1a9154e0fd3c5f6fd8924229ec4f5bc90b54d | Fix Xwt.Mac dll name | mono/guiunit | src/framework/GuiUnit/XwtMainLoopIntegration.cs | src/framework/GuiUnit/XwtMainLoopIntegration.cs | using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.Gtk.dll", "Xwt.GtkBackend.GtkEngine, Xwt.Gtk"),
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.XamMac.dll", "Xwt.Mac.MacEngine, Xwt.XamMac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.Gtk.dll", "Xwt.GtkBackend.GtkEngine, Xwt.Gtk"),
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.Mac.dll", "Xwt.Mac.MacEngine, Xwt.Mac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| mit | C# |
5f157e281ba6aa42abeb6598293e597584c0ba23 | Fix Xwt initialization to work with the WPF backend | mono/guiunit | src/framework/GuiUnit/XwtMainLoopIntegration.cs | src/framework/GuiUnit/XwtMainLoopIntegration.cs | using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
// List of Xwt backends we will try to use in order of priority
Tuple<string,string>[] backends = new[] {
Tuple.Create ("Xwt.Gtk.dll", "Xwt.GtkBackend.GtkEngine, Xwt.Gtk"),
Tuple.Create ("Xwt.WPF.dll", "Xwt.WPFBackend.WPFEngine, Xwt.WPF"),
Tuple.Create ("Xwt.Mac.dll", "Xwt.Mac.MacEngine, Xwt.Mac")
};
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
var initialized = false;
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters ()[0].ParameterType == typeof (string));
foreach (var impl in backends) {
var xwtImpl = Path.Combine (assemblyDirectory, impl.Item1);
if (File.Exists (xwtImpl)) {
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
initMethod.Invoke (null, new object[] { impl.Item2 });
initialized = true;
break;
}
}
if (!initialized)
initMethod.Invoke (null, new object[] { null });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace GuiUnit
{
public class XwtMainLoopIntegration : IMainLoopIntegration
{
Type Application {
get; set;
}
public XwtMainLoopIntegration ()
{
Application = Type.GetType ("Xwt.Application, Xwt");
if (Application == null)
throw new NotSupportedException ();
}
public void InitializeToolkit ()
{
Type assemblyType = typeof (Assembly);
PropertyInfo locationProperty = assemblyType.GetProperty ("Location");
if (locationProperty == null)
throw new NotSupportedException();
if (TestRunner.LoadFileMethod == null)
throw new NotSupportedException();
string assemblyDirectory = Path.GetDirectoryName ((string)locationProperty.GetValue (Application.Assembly, null));
// Firstly init Xwt
foreach (var impl in new [] { "Xwt.Gtk.dll", "Xwt.Mac.dll", "Xwt.Wpf.dll"}) {
var xwtImpl = Path.Combine (assemblyDirectory, impl);
if (File.Exists (xwtImpl))
TestRunner.LoadFileMethod.Invoke (null, new[] { xwtImpl });
}
var initMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var initMethod = initMethods.First (m => m.Name == "Initialize" && m.GetParameters ().Length == 1 && m.GetParameters () [0].ParameterType == typeof(string));
initMethod.Invoke (null, new [] { "Xwt.GtkBackend.GtkEngine, Xwt.Gtk" });
}
public void InvokeOnMainLoop (InvokerHelper helper)
{
var application = Type.GetType ("Xwt.Application, Xwt");
var invokeOnMainThreadMethod = application.GetMethod ("Invoke", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
invokeOnMainThreadMethod.Invoke (null, new [] { invoker });
}
public void RunMainLoop ()
{
Application.GetMethod ("Run").Invoke (null, null);
}
public void Shutdown ()
{
Application.GetMethod ("Exit").Invoke (null, null);
}
}
}
| mit | C# |
db4b5cc7a176541b51757e1a65fbc5d84fc2b4e4 | Fix version | gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer | LmpCommon/Properties/AssemblyInfo.cs | LmpCommon/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Luna Multiplayer Mod")]
[assembly: AssemblyDescription("Luna Multiplayer Mod (common)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LMP")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("Gabriel Vazquez")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("69dc2bdb-f7a3-4241-9990-6e067742788a")]
[assembly: AssemblyVersion("0.24.0")]
[assembly: AssemblyFileVersion("0.24.0")]
[assembly: AssemblyInformationalVersion("0.24.0-compiled")]
[assembly: InternalsVisibleTo("LmpCommonTest")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Luna Multiplayer Mod")]
[assembly: AssemblyDescription("Luna Multiplayer Mod (common)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LMP")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("Gabriel Vazquez")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("69dc2bdb-f7a3-4241-9990-6e067742788a")]
[assembly: AssemblyVersion("0.27.0")]
[assembly: AssemblyFileVersion("0.27.0")]
[assembly: AssemblyInformationalVersion("0.27.0-compiled")]
[assembly: InternalsVisibleTo("LmpCommonTest")]
| mit | C# |
fd1a9fda4610c4215d26e3e4d5305b494dd0cac8 | Update MessagePublisherTests.cs | serdardemir/EasyBus | EasyBus.Tests/MessagePublisherTests.cs | EasyBus.Tests/MessagePublisherTests.cs | using EasyBus.Abstraction;
using EasyBus.Types.MessageTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace EasyBus.Tests
{
public class MessagePublisherTests : IClassFixture<MessagePublisherFixture>
{
MessagePublisherFixture fixture;
public MessagePublisherTests(MessagePublisherFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void Message_Emitter_Test()
{
var messageEmitter = fixture.Container.GetInstance<MessageEmitter>();
messageEmitter.Emit(new LOGMessage()
{
ErrorId = Guid.NewGuid().ToString(),
Source = "SomeCode",
SourceId = "SomeCode",
Type = "Extrange Exception",
Detail = "Error Detail",
Host = "google.com",
InfoUrl = "",
Message = "We have a problem..",
ServerVariables = new Dictionary<string, string> { { "something", "something" } },
StatusCode = "404",
Time = DateTime.Now,
User = "TheUser",
WebHostHtmlMessage = "Error Message"
});
}
}
}
| using EasyBus.Abstraction;
using EasyBus.Types.MessageTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace EasyBus.Tests
{
public class MessagePublisherTests : IClassFixture<MessagePublisherFixture>
{
MessagePublisherFixture fixture;
public MessagePublisherTests(MessagePublisherFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void Message_Emitter_Test()
{
var messageEmitter = fixture.Container.GetInstance<MessageEmitter>();
messageEmitter.Emit(new LOGMessage()
{
ErrorId = Guid.NewGuid().ToString(),
Source = "SomeCode",
SourceId = "SomeCode",
Type = "Extrange Exception",
Detail = "Error Detail",
Host = "google.com",
InfoUrl = "",
Message = "We have a problem..",
ServerVariables = new Dictionary<string, string> { { "something", "something" } },
StatusCode = "404",
Time = DateTime.Now,
User = "TheUser",
WebHostHtmlMessage = "<b>Ugly Error Message</b>"
});
}
}
}
| mit | C# |
0f7037d696cc59f5e227d56fa3159516e08abe3e | Update src/ApiApprover/PublicApiApprover.cs | JakeGinnivan/ApiApprover | src/ApiApprover/PublicApiApprover.cs | src/ApiApprover/PublicApiApprover.cs | using System;
using System.IO;
using System.Reflection;
using ApprovalTests;
using ApprovalTests.Namers;
namespace ApiApprover
{
[Obsolete("The `ApiApprover` package will be removed in the next major version. Install the `PublicApiGenerator` package and use the `ApiGenerator` class directly instead.", false)]
public static class PublicApiApprover
{
[Obsolete("The package `ApiApprover` will be removed in the next major version. Install the package `PublicApiGenerator` and use the `ApiGenerator` directly or copy https://github.com/JakeGinnivan/ApiApprover/blob/master/src/ApiApprover/PublicApiApprover.cs into your repository if you plan to continue to use ApprovalTests in combination with the `ApiGenerator`.", false)]
public static void ApprovePublicApi(Assembly assembly)
{
var publicApi = PublicApiGenerator.ApiGenerator.GeneratePublicApi(assembly);
var writer = new ApprovalTextWriter(publicApi, "cs");
var approvalNamer = new AssemblyPathNamer(assembly.Location);
Approvals.Verify(writer, approvalNamer, Approvals.GetReporter());
}
private class AssemblyPathNamer : UnitTestFrameworkNamer
{
private readonly string name;
public AssemblyPathNamer(string assemblyPath)
{
name = Path.GetFileNameWithoutExtension(assemblyPath);
}
public override string Name
{
get { return name; }
}
}
}
}
| using System;
using System.IO;
using System.Reflection;
using ApprovalTests;
using ApprovalTests.Namers;
namespace ApiApprover
{
[Obsolete("The package `ApiApprover` will be removed in the next major version. Install the package `PublicApiGenerator` and use the `ApiGenerator` directly or copy https://github.com/JakeGinnivan/ApiApprover/blob/master/src/ApiApprover/PublicApiApprover.cs into your repository if you plan to continue to use ApprovalTests in combination with the `ApiGenerator`.", false)]
public static class PublicApiApprover
{
[Obsolete("The package `ApiApprover` will be removed in the next major version. Install the package `PublicApiGenerator` and use the `ApiGenerator` directly or copy https://github.com/JakeGinnivan/ApiApprover/blob/master/src/ApiApprover/PublicApiApprover.cs into your repository if you plan to continue to use ApprovalTests in combination with the `ApiGenerator`.", false)]
public static void ApprovePublicApi(Assembly assembly)
{
var publicApi = PublicApiGenerator.ApiGenerator.GeneratePublicApi(assembly);
var writer = new ApprovalTextWriter(publicApi, "cs");
var approvalNamer = new AssemblyPathNamer(assembly.Location);
Approvals.Verify(writer, approvalNamer, Approvals.GetReporter());
}
private class AssemblyPathNamer : UnitTestFrameworkNamer
{
private readonly string name;
public AssemblyPathNamer(string assemblyPath)
{
name = Path.GetFileNameWithoutExtension(assemblyPath);
}
public override string Name
{
get { return name; }
}
}
}
} | mit | C# |
f8ebecb08e209b4acaef11f959bccdad787ecd88 | Remove commented code | Free1man/SeleniumTestFramework,Free1man/SeleniumTestsRunner | SeleniumPageObjects/DriverService.cs | SeleniumPageObjects/DriverService.cs | using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.PhantomJS;
using System;
namespace SeleniumPageObjects
{
class DriverService
{
public IWebDriver GetBrowserForDriver(string browser)
{
switch (browser) {
case "Firefox":
return new FirefoxDriver();
case "Chrome":
return new ChromeDriver();
case "PhantomJS":
return new PhantomJSDriver();
default:
throw new ArgumentException("Not supported browser");
}
}
}
}
| using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.PhantomJS;
using System;
namespace SeleniumPageObjects
{
class DriverService
{
//public IWebDriver Driver { get; }
public IWebDriver GetBrowserForDriver(string browser)
{
switch (browser) {
case "Firefox":
return new FirefoxDriver();
case "Chrome":
return new ChromeDriver();
case "PhantomJS":
return new PhantomJSDriver();
default:
throw new ArgumentException("Not supported browser");
}
}
}
}
| mit | C# |
f17c563aed112dabbdbe977fcdb88772be7d85eb | move ticket generation code | HouseBreaker/Shameless | Shameless/Tickets/TicketGenerator.cs | Shameless/Tickets/TicketGenerator.cs | namespace Shameless.Tickets
{
using System;
using System.IO;
using System.Linq;
using Shameless.Properties;
using Shameless.Utils;
public static class TicketGenerator
{
public static void GenerateTicket(Nintendo3DSTitle title, string fileName, string outputDir)
{
var ticket = Convert.FromBase64String(Resources.TikTemplate);
var titleId = BitConversion.HexToBytes(title.TitleId);
var titleKey = BitConversion.HexToBytes(title.EncKey);
const int TitleKeyOffset = 0x1BF;
for (var offset = TitleKeyOffset; offset < TitleKeyOffset + 0x10; offset++)
{
ticket[offset] = titleKey[offset - TitleKeyOffset];
}
const int TitleIdOffset = 0x1DC;
for (int offset = TitleIdOffset; offset < TitleIdOffset + 0x8; offset++)
{
ticket[offset] = titleId[offset - TitleIdOffset];
}
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
fileName = SanitizeFileName(fileName);
File.WriteAllBytes($"{outputDir}\\{fileName}", ticket);
}
public static byte[] GenerateTicket(Nintendo3DSTitle title)
{
var ticket = Convert.FromBase64String(Resources.TikTemplate);
var titleId = BitConversion.HexToBytes(title.TitleId);
var titleKey = BitConversion.HexToBytes(title.EncKey);
const int TitleKeyOffset = 0x1BF;
for (var offset = TitleKeyOffset; offset < TitleKeyOffset + 0x10; offset++)
{
ticket[offset] = titleKey[offset - TitleKeyOffset];
}
const int TitleIdOffset = 0x1DC;
for (int offset = TitleIdOffset; offset < TitleIdOffset + 0x8; offset++)
{
ticket[offset] = titleId[offset - TitleIdOffset];
}
return ticket;
}
public static string SanitizeFileName(string title)
{
var sanitizedName = title;
var invalidFileNameChars = Path.GetInvalidFileNameChars().ToList();
invalidFileNameChars.AddRange(new[] { '™', '®', '®' }); // it's annoying...
foreach (var invalidFileNameChar in invalidFileNameChars)
{
if (sanitizedName.Contains(invalidFileNameChar))
{
sanitizedName = sanitizedName.Replace(invalidFileNameChar.ToString(), string.Empty);
}
}
sanitizedName = sanitizedName.Trim();
return sanitizedName;
}
}
}
| namespace Shameless.Tickets
{
using System;
using System.IO;
using System.Linq;
using Shameless.Properties;
using Shameless.Utils;
public static class TicketGenerator
{
public static void GenerateTicket(Nintendo3DSTitle title, string fileName, string outputDir)
{
var ticket = Convert.FromBase64String(Resources.TikTemplate);
var titleId = BitConversion.HexToBytes(title.TitleId);
var titleKey = BitConversion.HexToBytes(title.EncKey);
const int TitleKeyOffset = 0x1BF;
for (var offset = TitleKeyOffset; offset < TitleKeyOffset + 0x10; offset++)
{
ticket[offset] = titleKey[offset - TitleKeyOffset];
}
const int TitleIdOffset = 0x1DC;
for (int offset = TitleIdOffset; offset < TitleIdOffset + 0x8; offset++)
{
ticket[offset] = titleId[offset - TitleIdOffset];
}
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
fileName = SanitizeFileName(fileName);
File.WriteAllBytes($"{outputDir}\\{fileName}", ticket);
}
public static string SanitizeFileName(string title)
{
var sanitizedName = title;
var invalidFileNameChars = Path.GetInvalidFileNameChars().ToList();
invalidFileNameChars.AddRange(new[] { '™', '®', '®' }); // it's annoying...
foreach (var invalidFileNameChar in invalidFileNameChars)
{
if (sanitizedName.Contains(invalidFileNameChar))
{
sanitizedName = sanitizedName.Replace(invalidFileNameChar.ToString(), string.Empty);
}
}
sanitizedName = sanitizedName.Trim();
return sanitizedName;
}
}
}
| mit | C# |
5c0c210573ad42b2b5657e0bc0a4c931a5fcbd65 | Document ITransitionInfo<TState> | canton7/StateMechanic,canton7/StateMechanic | src/StateMechanic/ITransitionInfo.cs | src/StateMechanic/ITransitionInfo.cs | namespace StateMechanic
{
/// <summary>
/// Information about a transition
/// </summary>
/// <typeparam name="TState"></typeparam>
public interface ITransitionInfo<TState>
{
/// <summary>
/// Gets the state this transition is from
/// </summary>
TState From { get; }
/// <summary>
/// Gets the state this transition is to
/// </summary>
TState To { get; }
/// <summary>
/// Gets the event which triggered this transition
/// </summary>
IEvent Event { get; }
/// <summary>
/// Gets a value indicating whether this is an inner self transition, i.e. whether entry/exit handler are not executed
/// </summary>
bool IsInnerTransition { get; }
/// <summary>
/// Gets the method used to fire the event
/// </summary>
EventFireMethod EventFireMethod { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StateMechanic
{
public interface ITransitionInfo<TState>
{
/// <summary>
/// Gets the state this transition is from
/// </summary>
TState From { get; }
/// <summary>
/// Gets the state this transition is to
/// </summary>
TState To { get; }
/// <summary>
/// Gets the event which triggered this transition
/// </summary>
IEvent Event { get; }
/// <summary>
/// Gets a value indicating whether this is an inner self transition, i.e. whether entry/exit handler are not executed
/// </summary>
bool IsInnerTransition { get; }
/// <summary>
/// Gets the method used to fire the event
/// </summary>
EventFireMethod EventFireMethod { get; }
}
}
| mit | C# |
a2194513157febc4c5a90dfa6f066df012f83b5f | Fix exception caused by getting directory name from empty string in runner config editor | mkoscielniak/SSMScripter | SSMScripter/Config/RunnerConfigForm.cs | SSMScripter/Config/RunnerConfigForm.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SSMScripter.Runner;
namespace SSMScripter.Config
{
public partial class RunnerConfigForm : Form
{
private RunConfig _runConfig;
public RunnerConfigForm()
{
InitializeComponent();
}
public RunnerConfigForm(RunConfig runConfig)
: this()
{
_runConfig = runConfig;
tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty);
tbArgs.Text = _runConfig.RunArgs ?? String.Empty;
}
private void btnOk_Click(object sender, EventArgs e)
{
_runConfig.RunTool = tbTool.Text;
_runConfig.RunArgs = tbArgs.Text;
DialogResult = DialogResult.OK;
}
private void btnTool_Click(object sender, EventArgs e)
{
using(OpenFileDialog dialog = new OpenFileDialog())
{
if (!String.IsNullOrEmpty(tbTool.Text))
dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text);
dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty;
dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*";
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
tbTool.Text = dialog.FileName;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SSMScripter.Runner;
namespace SSMScripter.Config
{
public partial class RunnerConfigForm : Form
{
private RunConfig _runConfig;
public RunnerConfigForm()
{
InitializeComponent();
}
public RunnerConfigForm(RunConfig runConfig)
: this()
{
_runConfig = runConfig;
tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty);
tbArgs.Text = _runConfig.RunArgs ?? String.Empty;
}
private void btnOk_Click(object sender, EventArgs e)
{
_runConfig.RunTool = tbTool.Text;
_runConfig.RunArgs = tbArgs.Text;
DialogResult = DialogResult.OK;
}
private void btnTool_Click(object sender, EventArgs e)
{
using(OpenFileDialog dialog = new OpenFileDialog())
{
dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text) ?? String.Empty;
dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty;
dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*";
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
tbTool.Text = dialog.FileName;
}
}
}
}
}
| mit | C# |
c854cec188dfda99e930673af9d197a49b6923fc | Add constructors in KpTestView | RapidScada/scada,RapidScada/scada,RapidScada/scada,RapidScada/scada | ScadaComm/OpenKPs/KpTest/KpTestView.cs | ScadaComm/OpenKPs/KpTest/KpTestView.cs | /*
* Copyright 2015 Mikhail Shiryaev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Product : Rapid SCADA
* Module : KpTest
* Summary : Device library user interface
*
* Author : Mikhail Shiryaev
* Created : 2006
* Modified : 2015
*/
namespace Scada.Comm.Devices
{
/// <summary>
/// Device library user interface
/// <para>Пользовательский интерфейс библиотеки КП</para>
/// </summary>
public sealed class KpTestView : KPView
{
public KpTestView()
: this(0)
{
}
public KpTestView(int number)
: base(number)
{
}
public override string KPDescr
{
get
{
return Localization.UseRussian ?
"Библиотека КП для тестирования." :
"Device library for testing.";
}
}
}
}
| /*
* Copyright 2015 Mikhail Shiryaev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Product : Rapid SCADA
* Module : KpTest
* Summary : Device library user interface
*
* Author : Mikhail Shiryaev
* Created : 2006
* Modified : 2015
*/
namespace Scada.Comm.Devices
{
/// <summary>
/// Device library user interface
/// <para>Пользовательский интерфейс библиотеки КП</para>
/// </summary>
public sealed class KpTestView : KPView
{
public override string KPDescr
{
get
{
return Localization.UseRussian ?
"Библиотека КП для тестирования." :
"Device library for testing.";
}
}
}
}
| apache-2.0 | C# |
dc18d1723333b37f06e0edd8e9c3dd7f523cd77c | Fix bug with index in VectorEnumerator | ProgTrade/SharpMath | SharpMath/Geometry/VectorEnumerator.cs | SharpMath/Geometry/VectorEnumerator.cs | using System.Collections;
using System.Collections.Generic;
namespace SharpMath.Geometry
{
public class VectorEnumerator : IEnumerator<double>
{
private readonly Vector _vector;
private int _index = -1;
internal VectorEnumerator(Vector vector)
{
_vector = vector;
}
public double Current => _vector[(uint)_index];
object IEnumerator.Current => _vector[(uint)_index];
public void Dispose()
{ }
public bool MoveNext()
{
_index++;
return _index < _vector.Dimension;
}
public void Reset()
{
_index = -1;
}
}
} | using System.Collections;
using System.Collections.Generic;
namespace SharpMath.Geometry
{
public class VectorEnumerator : IEnumerator<double>
{
private readonly Vector _vector;
private int _index;
internal VectorEnumerator(Vector vector)
{
_vector = vector;
}
public double Current => _vector[(uint)_index];
object IEnumerator.Current => _vector[(uint)_index];
public void Dispose()
{ }
public bool MoveNext()
{
_index++;
return _index < _vector.Dimension;
}
public void Reset()
{
_index = -1;
}
}
}
| mit | C# |
1a26a557f6bf9ea540c8d59b4cb020ca105289d3 | fix tabs (again...) | activescott/lessmsi,activescott/lessmsi,activescott/lessmsi | src/LessMsi.Cli/OpenGuiCommand.cs | src/LessMsi.Cli/OpenGuiCommand.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using NDesk.Options;
namespace LessMsi.Cli
{
internal class OpenGuiCommand : LessMsiCommand
{
public override void Run(List<string> args)
{
if (args.Count < 2)
throw new OptionException("You must specify the name of the msi file to open when using the o command.", "o");
ShowGui(args);
}
public static void ShowGui(List<string> args)
{
var guiExe = Path.Combine(AppPath, "lessmsi-gui.exe");
if (File.Exists(guiExe))
{
var p = new Process();
p.StartInfo.FileName = guiExe;
//should we wait for exit?
if (args.Count > 0)
{
// We add double quotes to support paths with spaces, for ex: "E:\Downloads and Sofware\potato.msi".
p.StartInfo.Arguments = string.Format("\"{0}\"", args[1]);
p.Start();
}
else
p.Start();
}
}
private static string AppPath
{
get
{
var codeBase = new Uri(typeof(OpenGuiCommand).Assembly.CodeBase);
var local = Path.GetDirectoryName(codeBase.LocalPath);
return local;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using NDesk.Options;
namespace LessMsi.Cli
{
internal class OpenGuiCommand : LessMsiCommand
{
public override void Run(List<string> args)
{
if (args.Count < 2)
throw new OptionException("You must specify the name of the msi file to open when using the o command.", "o");
ShowGui(args);
}
public static void ShowGui(List<string> args)
{
var guiExe = Path.Combine(AppPath, "lessmsi-gui.exe");
if (File.Exists(guiExe))
{
var p = new Process();
p.StartInfo.FileName = guiExe;
//should we wait for exit?
if (args.Count > 0)
{
// We add double quotes to support paths with spaces, for ex: "E:\Downloads and Sofware\potato.msi".
p.StartInfo.Arguments = string.Format("\"{0}\"", args[1]);
p.Start();
}
else
p.Start();
}
}
private static string AppPath
{
get
{
var codeBase = new Uri(typeof(OpenGuiCommand).Assembly.CodeBase);
var local = Path.GetDirectoryName(codeBase.LocalPath);
return local;
}
}
}
}
| mit | C# |
bdcef9074fe9820ace06625c85f4b9188a4c12bb | add spacing above tag helpers | scottaddie/TagHelpersDemo,scottaddie/TagHelpersDemo | TagHelpersDemo/Views/Home/Index.cshtml | TagHelpersDemo/Views/Home/Index.cshtml | @using TagHelpersDemo.TagHelpers
@{
ViewData["Title"] = "Home Page";
}
<div class="clearfix"> </div>
<hand player="John">
<card suit="@CardTagHelper.CardSuit.Heart" rank="@CardTagHelper.CardRank.Ace"></card>
<card suit="@CardTagHelper.CardSuit.Club" rank="@CardTagHelper.CardRank.Eight"></card>
<card suit="@CardTagHelper.CardSuit.Diamond" rank="@CardTagHelper.CardRank.Jack"></card>
</hand>
<hand player="Jane">
<card suit="@CardTagHelper.CardSuit.Spade" rank="@CardTagHelper.CardRank.Four"></card>
<card suit="@CardTagHelper.CardSuit.Heart" rank="@CardTagHelper.CardRank.Queen"></card>
<card suit="@CardTagHelper.CardSuit.Heart" rank="@CardTagHelper.CardRank.Seven"></card>
</hand> | @using TagHelpersDemo.TagHelpers
@{
ViewData["Title"] = "Home Page";
}
<hand player="John">
<card suit="@CardTagHelper.CardSuit.Heart" rank="@CardTagHelper.CardRank.Ace"></card>
<card suit="@CardTagHelper.CardSuit.Club" rank="@CardTagHelper.CardRank.Eight"></card>
<card suit="@CardTagHelper.CardSuit.Diamond" rank="@CardTagHelper.CardRank.Jack"></card>
</hand>
<hand player="Jane">
<card suit="@CardTagHelper.CardSuit.Spade" rank="@CardTagHelper.CardRank.Four"></card>
<card suit="@CardTagHelper.CardSuit.Heart" rank="@CardTagHelper.CardRank.Queen"></card>
<card suit="@CardTagHelper.CardSuit.Heart" rank="@CardTagHelper.CardRank.Seven"></card>
</hand> | mit | C# |
69c6b92013d30e931f4be851db1c3ffdc106e101 | Kill server testing | robotdotnet/NetworkTablesCore | NetworkTablesCore.Test/TestServer.cs | NetworkTablesCore.Test/TestServer.cs | using System;
using System.Threading;
using NetworkTables;
using NetworkTables.Native;
using NUnit.Framework;
namespace NetworkTablesCore.Test
{
public class TestServer
{
public void Test()
{
NetworkTable.Shutdown();
CoreMethods.SetLogger(((level, file, line, message) =>
{
Console.Error.WriteLine(message);
}), 0);
NetworkTable.SetIPAddress("127.0.0.1");
NetworkTable.SetPort(10000);
NetworkTable.SetServerMode();
NetworkTable nt = NetworkTable.GetTable("");
Thread.Sleep(1000);
nt.PutNumber("foo", 0.5);
nt.SetFlags("foo", EntryFlags.Persistent);
nt.PutNumber("foo2", 0.5);
nt.PutNumber("foo2", 0.7);
nt.PutNumber("foo2", 0.6);
nt.PutNumber("foo2", 0.5);
Thread.Sleep(1000);
}
}
}
| using System;
using System.Threading;
using NetworkTables;
using NetworkTables.Native;
using NUnit.Framework;
namespace NetworkTablesCore.Test
{
[TestFixture]
public class TestServer
{
[Test]
public void Test()
{
NetworkTable.Shutdown();
CoreMethods.SetLogger(((level, file, line, message) =>
{
Console.Error.WriteLine(message);
}), 0);
NetworkTable.SetIPAddress("127.0.0.1");
NetworkTable.SetPort(10000);
NetworkTable.SetServerMode();
NetworkTable nt = NetworkTable.GetTable("");
Thread.Sleep(1000);
nt.PutNumber("foo", 0.5);
nt.SetFlags("foo", EntryFlags.Persistent);
nt.PutNumber("foo2", 0.5);
nt.PutNumber("foo2", 0.7);
nt.PutNumber("foo2", 0.6);
nt.PutNumber("foo2", 0.5);
Thread.Sleep(1000);
}
}
}
| bsd-3-clause | C# |
2364ac71c4fd827295cae8518c26dab282da12e6 | Update TestServer.cs | robotdotnet/NetworkTablesCore | NetworkTablesCore.Test/TestServer.cs | NetworkTablesCore.Test/TestServer.cs | using System;
using System.Threading;
using NetworkTables;
using NetworkTables.Native;
using NUnit.Framework;
namespace NetworkTablesCore.Test
{
[TestFixture]
public class TestServer
{
[Test]
public void Test()
{
CoreMethods.SetLogger(((level, file, line, message) =>
{
Console.Error.WriteLine(message);
}), LogLevel.LogDebug4);
Console.WriteLine("BeforeShuttingDown");
NetworkTable.Shutdown();
Console.WriteLine("Shutting Down");
NetworkTable.SetIPAddress("127.0.0.1");
Console.WriteLine("IP");
NetworkTable.SetPort(10000);
Console.WriteLine("Port");
NetworkTable.SetServerMode();
Console.WriteLine("Server");
NetworkTable nt = NetworkTable.GetTable("");
Console.WriteLine("GetTable");
Thread.Sleep(1000);
Console.WriteLine("FirstSleep");
nt.PutNumber("foo", 0.5);
Console.WriteLine("foo .5");
nt.SetFlags("foo", EntryFlags.Persistent);
Console.WriteLine("Persistent");
nt.PutNumber("foo2", 0.5);
Console.WriteLine("Foo 2 .5");
nt.PutNumber("foo2", 0.7);
Console.WriteLine("Foo 2 .7");
nt.PutNumber("foo2", 0.6);
Console.WriteLine("Foo 2 .6");
nt.PutNumber("foo2", 0.5);
Console.WriteLine("Foo 2 .5 2");
Thread.Sleep(1000);
Console.WriteLine("2ndSleep");
}
}
}
| using System;
using System.Threading;
using NetworkTables;
using NetworkTables.Native;
using NUnit.Framework;
namespace NetworkTablesCore.Test
{
[TestFixture]
public class TestServer
{
[Test]
public void Test()
{
CoreMethods.SetLogger(((level, file, line, message) =>
{
Console.Error.WriteLine(message);
}), LogLevel.Debug4);
Console.WriteLine("BeforeShuttingDown");
NetworkTable.Shutdown();
Console.WriteLine("Shutting Down");
NetworkTable.SetIPAddress("127.0.0.1");
Console.WriteLine("IP");
NetworkTable.SetPort(10000);
Console.WriteLine("Port");
NetworkTable.SetServerMode();
Console.WriteLine("Server");
NetworkTable nt = NetworkTable.GetTable("");
Console.WriteLine("GetTable");
Thread.Sleep(1000);
Console.WriteLine("FirstSleep");
nt.PutNumber("foo", 0.5);
Console.WriteLine("foo .5");
nt.SetFlags("foo", EntryFlags.Persistent);
Console.WriteLine("Persistent");
nt.PutNumber("foo2", 0.5);
Console.WriteLine("Foo 2 .5");
nt.PutNumber("foo2", 0.7);
Console.WriteLine("Foo 2 .7");
nt.PutNumber("foo2", 0.6);
Console.WriteLine("Foo 2 .6");
nt.PutNumber("foo2", 0.5);
Console.WriteLine("Foo 2 .5 2");
Thread.Sleep(1000);
Console.WriteLine("2ndSleep");
}
}
}
| bsd-3-clause | C# |
7510f0d9c06a4fa14110c1f394d4989dcbeed00a | Bump version to 0.31.4 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.31.4";
}
}
| #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.31.3";
}
}
| mit | C# |
828072bceaad5cb10ae39abdec82148136707fa0 | Fix issue #15869 | ppy/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu | osu.Game/Rulesets/Mods/ModCinema.cs | osu.Game/Rulesets/Mods/ModCinema.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T>
where T : HitObject
{
public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset)
{
drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap, drawableRuleset.Mods));
// AlwaysPresent required for hitsounds
drawableRuleset.AlwaysPresent = true;
drawableRuleset.Hide();
}
}
public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer
{
public override string Name => "Cinema";
public override string Acronym => "CN";
public override IconUsage? Icon => OsuIcon.ModCinema;
public override string Description => "Watch the video without visual distractions.";
public void ApplyToHUD(HUDOverlay overlay)
{
overlay.ShowHud.Value = false;
overlay.ShowHud.Disabled = true;
}
public void ApplyToPlayer(Player player)
{
player.ApplyToBackground(b => b.IgnoreUserSettings.Value = true);
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
player.BreakOverlay.Hide();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T>
where T : HitObject
{
public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset)
{
drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap, drawableRuleset.Mods));
// AlwaysPresent required for hitsounds
drawableRuleset.Playfield.AlwaysPresent = true;
drawableRuleset.Playfield.Hide();
}
}
public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer
{
public override string Name => "Cinema";
public override string Acronym => "CN";
public override IconUsage? Icon => OsuIcon.ModCinema;
public override string Description => "Watch the video without visual distractions.";
public void ApplyToHUD(HUDOverlay overlay)
{
overlay.ShowHud.Value = false;
overlay.ShowHud.Disabled = true;
}
public void ApplyToPlayer(Player player)
{
player.ApplyToBackground(b => b.IgnoreUserSettings.Value = true);
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
player.BreakOverlay.Hide();
}
}
}
| mit | C# |
52336e9062affa6742ad49c7802f31153364e04a | Fix pause tests | ppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,ZLima12/osu,2yangk23/osu,peppy/osu-new | osu.Game/Tests/Visual/PlayerTestCase.cs | osu.Game/Tests/Visual/PlayerTestCase.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual
{
public abstract class PlayerTestCase : RateAdjustedBeatmapTestCase
{
private readonly Ruleset ruleset;
protected Player Player;
protected PlayerTestCase(Ruleset ruleset)
{
this.ruleset = ruleset;
}
[SetUpSteps]
public void SetUpSteps()
{
AddStep(ruleset.RulesetInfo.Name, loadPlayer);
AddUntilStep(() => Player.IsLoaded && Player.Alpha == 1, "player loaded");
}
protected virtual IBeatmap CreateBeatmap(Ruleset ruleset) => new TestBeatmap(ruleset.RulesetInfo);
protected virtual bool AllowFail => false;
private void loadPlayer()
{
var beatmap = CreateBeatmap(ruleset);
Beatmap.Value = new TestWorkingBeatmap(beatmap, Clock);
if (!AllowFail)
Mods.Value = new[] { ruleset.GetAllMods().First(m => m is ModNoFail) };
Player = CreatePlayer(ruleset);
LoadScreen(Player);
}
protected virtual Player CreatePlayer(Ruleset ruleset) => new Player(false, false);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Play;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual
{
public abstract class PlayerTestCase : RateAdjustedBeatmapTestCase
{
private readonly Ruleset ruleset;
protected Player Player;
protected PlayerTestCase(Ruleset ruleset)
{
this.ruleset = ruleset;
}
[SetUpSteps]
public void SetUpSteps()
{
AddStep(ruleset.RulesetInfo.Name, loadPlayer);
AddUntilStep(() => Player.IsLoaded, "player loaded");
}
protected virtual IBeatmap CreateBeatmap(Ruleset ruleset) => new TestBeatmap(ruleset.RulesetInfo);
protected virtual bool AllowFail => false;
private void loadPlayer()
{
var beatmap = CreateBeatmap(ruleset);
Beatmap.Value = new TestWorkingBeatmap(beatmap, Clock);
if (!AllowFail)
Mods.Value = new[] { ruleset.GetAllMods().First(m => m is ModNoFail) };
Player = CreatePlayer(ruleset);
LoadScreen(Player);
}
protected virtual Player CreatePlayer(Ruleset ruleset) => new Player(false, false);
}
}
| mit | C# |
17decd464b5883c95b3d48033d4967f998df7d63 | add DNT.Diag.Settings | rockyx/dntdiag | DNT/Diag/Settings.cs | DNT/Diag/Settings.cs | using System;
namespace DNT.Diag
{
public static class Settings
{
private static Language lang;
private static string langText;
public static Language Language
{
get { return lang; }
set {
lang = value;
langText = ToString (lang);
}
}
public static string ToString(Language value)
{
return value.ToString ().Replace ('_', '-');
}
public static string LanguageText
{
get { return langText; }
}
}
}
| using System;
namespace DNT.Diag
{
public static class Settings
{
public Settings ()
{
}
}
}
| apache-2.0 | C# |
560a2fa9f6be7c403f90866a9c69ba264def52c6 | Convert to NFluent | picklesdoc/pickles,ludwigjossieaux/pickles,irfanah/pickles,irfanah/pickles,blorgbeard/pickles,ludwigjossieaux/pickles,magicmonty/pickles,irfanah/pickles,dirkrombauts/pickles,picklesdoc/pickles,magicmonty/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,blorgbeard/pickles,blorgbeard/pickles,irfanah/pickles,dirkrombauts/pickles,dirkrombauts/pickles,magicmonty/pickles,blorgbeard/pickles,magicmonty/pickles,picklesdoc/pickles,picklesdoc/pickles | src/Pickles/Pickles.Test/WhenDeterminingRelevantFilesToConsider.cs | src/Pickles/Pickles.Test/WhenDeterminingRelevantFilesToConsider.cs | using System;
using NUnit.Framework;
using Autofac;
using PicklesDoc.Pickles.DirectoryCrawler;
using NFluent;
namespace PicklesDoc.Pickles.Test
{
[TestFixture]
public class WhenDeterminingRelevantFilesToConsider : BaseFixture
{
[Test]
public void ThenCanDetectFeatureFilesSuccessfully()
{
var relevantFileDetector = Container.Resolve<RelevantFileDetector>();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.feature"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.markdown"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdown"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mkdn"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.md"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdwn"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdtext"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdtxt"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.text"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.txt"))).IsTrue();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.pdf"))).IsFalse();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.doc"))).IsFalse();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.docx"))).IsFalse();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.docx"))).IsFalse();
Check.That(relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("myproject.csproj.FileListAbsolute.txt"))).IsFalse();
}
}
} | using System;
using NUnit.Framework;
using Autofac;
using PicklesDoc.Pickles.DirectoryCrawler;
using Should;
namespace PicklesDoc.Pickles.Test
{
[TestFixture]
public class WhenDeterminingRelevantFilesToConsider : BaseFixture
{
[Test]
public void ThenCanDetectFeatureFilesSuccessfully()
{
var relevantFileDetector = Container.Resolve<RelevantFileDetector>();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.feature")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.markdown")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdown")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mkdn")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.md")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdwn")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdtext")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.mdtxt")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.text")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.txt")).ShouldBeTrue();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.pdf")).ShouldBeFalse();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.doc")).ShouldBeFalse();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.docx")).ShouldBeFalse();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("test.docx")).ShouldBeFalse();
relevantFileDetector.IsRelevant(FileSystem.FileInfo.FromFileName("myproject.csproj.FileListAbsolute.txt")).ShouldBeFalse();
}
}
} | apache-2.0 | C# |
953a7a6a3d703b795a6a736a116fc426ebb644c8 | Add non formatting overloads | xPaw/WendySharp | WendySharp/Wendy/CommandArguments.cs | WendySharp/Wendy/CommandArguments.cs | using System;
using System.Text.RegularExpressions;
using NetIrc2.Events;
namespace WendySharp
{
class CommandArguments
{
public bool IsDirect;
public string MatchedCommand;
public ChatMessageEventArgs Event;
public Match Arguments;
public User User;
public void ReplyAsNotice(string message)
{
Reply(message, true);
}
public void ReplyAsNotice(string message, params object[] args)
{
Reply(string.Format(message, args), true);
}
public void Reply(string message)
{
Reply(message, false);
}
public void Reply(string message, params object[] args)
{
Reply(string.Format(message, args), false);
}
private void Reply(string message, bool notice)
{
string recipient = Event.Recipient;
if (recipient[0] == '#')
{
if (!notice)
{
message = $"{Event.Sender.Nickname}: {message}";
}
else
{
recipient = Event.Sender.Nickname.ToString();
}
}
else
{
notice = false;
recipient = Event.Sender.Nickname.ToString();
}
Bootstrap.Client.SendReply(recipient, message, notice);
}
}
}
| using System;
using System.Text.RegularExpressions;
using NetIrc2.Events;
namespace WendySharp
{
class CommandArguments
{
public bool IsDirect;
public string MatchedCommand;
public ChatMessageEventArgs Event;
public Match Arguments;
public User User;
public void ReplyAsNotice(string message, params object[] args)
{
Reply(string.Format(message, args), true);
}
public void Reply(string message, params object[] args)
{
Reply(string.Format(message, args), false);
}
private void Reply(string message, bool notice)
{
string recipient = Event.Recipient;
if (recipient[0] == '#')
{
if (!notice)
{
message = $"{Event.Sender.Nickname}: {message}";
}
else
{
recipient = Event.Sender.Nickname.ToString();
}
}
else
{
notice = false;
recipient = Event.Sender.Nickname.ToString();
}
Bootstrap.Client.SendReply(recipient, message, notice);
}
}
}
| mit | C# |
adfe419f491bb3d1c80c624bc59bbae52dd45405 | Add properties to "MP3File" class | elp87/TagReader | elp87.TagReader/MP3File.cs | elp87.TagReader/MP3File.cs | using elp87.TagReader.id3v2;
namespace elp87.TagReader
{
public class MP3File
{
#region Fields
private ID3V2 _id3v2;
#endregion
#region Constructors
public MP3File()
{
}
public MP3File(string filename)
{
_id3v2 = new ID3V2(filename);
}
#endregion
#region Properties
public ID3V2 Id3v2 { get { return _id3v2; } }
public string Performer
{
get
{
if (_id3v2 == null || _id3v2.PersonsFrames.TPE1 == null) { return ""; }
else { return _id3v2.PersonsFrames.TPE1.ToString(); }
}
}
public string Album
{
get
{
if (_id3v2 == null || _id3v2.IdentificationFrames.TALB == null) { return ""; }
else { return _id3v2.IdentificationFrames.TALB.ToString(); }
}
}
public string Title
{
get
{
if (_id3v2 == null || _id3v2.IdentificationFrames.TIT2 == null) { return ""; }
else { return _id3v2.IdentificationFrames.TIT2.ToString(); }
}
}
public string Year
{
get
{
if (_id3v2 == null || _id3v2.OtherFrames.TDRC == null) { return ""; }
else { return _id3v2.OtherFrames.TDRC.Year.ToString(); }
}
}
#endregion
}
}
| using elp87.TagReader.id3v2;
namespace elp87.TagReader
{
public class MP3File
{
private ID3V2 _id3v2;
public MP3File()
{
}
public MP3File(string filename)
{
_id3v2 = new ID3V2(filename);
}
public ID3V2 Id3v2
{
get
{
return _id3v2;
}
}
}
}
| lgpl-2.1 | C# |
4a151edb6327e6b8344249c0009aac7013ecdcb9 | Use local LayoutManager instance for OffscreenTopLevel. | wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex | src/Avalonia.Controls/Embedding/Offscreen/OffscreenTopLevel.cs | src/Avalonia.Controls/Embedding/Offscreen/OffscreenTopLevel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Layout;
using Avalonia.Styling;
namespace Avalonia.Controls.Embedding.Offscreen
{
class OffscreenTopLevel : TopLevel, IStyleable
{
public OffscreenTopLevelImplBase Impl { get; }
public OffscreenTopLevel(OffscreenTopLevelImplBase impl) : base(impl)
{
Impl = impl;
Prepare();
}
public void Prepare()
{
EnsureInitialized();
ApplyTemplate();
LayoutManager.ExecuteInitialLayoutPass(this);
}
private void EnsureInitialized()
{
if (!this.IsInitialized)
{
var init = (ISupportInitialize)this;
init.BeginInit();
init.EndInit();
}
}
private readonly NameScope _nameScope = new NameScope();
public event EventHandler<NameScopeEventArgs> Registered
{
add { _nameScope.Registered += value; }
remove { _nameScope.Registered -= value; }
}
public event EventHandler<NameScopeEventArgs> Unregistered
{
add { _nameScope.Unregistered += value; }
remove { _nameScope.Unregistered -= value; }
}
public void Register(string name, object element) => _nameScope.Register(name, element);
public object Find(string name) => _nameScope.Find(name);
public void Unregister(string name) => _nameScope.Unregister(name);
Type IStyleable.StyleKey => typeof(EmbeddableControlRoot);
public void Dispose()
{
PlatformImpl?.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Layout;
using Avalonia.Styling;
namespace Avalonia.Controls.Embedding.Offscreen
{
class OffscreenTopLevel : TopLevel, IStyleable
{
public OffscreenTopLevelImplBase Impl { get; }
public OffscreenTopLevel(OffscreenTopLevelImplBase impl) : base(impl)
{
Impl = impl;
Prepare();
}
public void Prepare()
{
EnsureInitialized();
ApplyTemplate();
LayoutManager.Instance.ExecuteInitialLayoutPass(this);
}
private void EnsureInitialized()
{
if (!this.IsInitialized)
{
var init = (ISupportInitialize)this;
init.BeginInit();
init.EndInit();
}
}
private readonly NameScope _nameScope = new NameScope();
public event EventHandler<NameScopeEventArgs> Registered
{
add { _nameScope.Registered += value; }
remove { _nameScope.Registered -= value; }
}
public event EventHandler<NameScopeEventArgs> Unregistered
{
add { _nameScope.Unregistered += value; }
remove { _nameScope.Unregistered -= value; }
}
public void Register(string name, object element) => _nameScope.Register(name, element);
public object Find(string name) => _nameScope.Find(name);
public void Unregister(string name) => _nameScope.Unregister(name);
Type IStyleable.StyleKey => typeof(EmbeddableControlRoot);
public void Dispose()
{
PlatformImpl?.Dispose();
}
}
}
| mit | C# |
054cb7f3f0d5d9cc648cb156fb71f9d674b58e82 | Set env vars in GitHub Actions | AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning | src/NerdBank.GitVersioning/CloudBuildServices/GitHubActions.cs | src/NerdBank.GitVersioning/CloudBuildServices/GitHubActions.cs | namespace NerdBank.GitVersioning.CloudBuildServices
{
using System;
using System.Collections.Generic;
using System.IO;
using Nerdbank.GitVersioning;
internal class GitHubActions : ICloudBuild
{
public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent";
public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null;
public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null;
public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA");
private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF");
public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr)
{
return new Dictionary<string, string>();
}
public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr)
{
(stdout ?? Console.Out).WriteLine($"##[set-env name={name};]{value}");
return GetDictionaryFor(name, value);
}
private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ GetEnvironmentVariableNameForVariable(variableName), value },
};
}
private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_');
}
}
| namespace NerdBank.GitVersioning.CloudBuildServices
{
using System;
using System.Collections.Generic;
using System.IO;
using Nerdbank.GitVersioning;
internal class GitHubActions : ICloudBuild
{
public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent";
public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null;
public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null;
public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA");
private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF");
public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr)
{
return new Dictionary<string, string>();
}
public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr)
{
return new Dictionary<string, string>();
}
}
}
| mit | C# |
5c0ac2c8181861c19a7cd4c1b2d3d11039231564 | Fix #291: Dot-source reference detection should ignore ScriptBlocks | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices/Language/FindDotSourcedVisitor.cs | src/PowerShellEditorServices/Language/FindDotSourcedVisitor.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.Collections.Generic;
using System.Management.Automation.Language;
namespace Microsoft.PowerShell.EditorServices
{
/// <summary>
/// The vistor used to find the dont sourced files in an AST
/// </summary>
internal class FindDotSourcedVisitor : AstVisitor
{
/// <summary>
/// A hash set of the dot sourced files (because we don't want duplicates)
/// </summary>
public HashSet<string> DotSourcedFiles { get; private set; }
public FindDotSourcedVisitor()
{
this.DotSourcedFiles = new HashSet<string>();
}
/// <summary>
/// Checks to see if the command invocation is a dot
/// in order to find a dot sourced file
/// </summary>
/// <param name="commandAst">A CommandAst object in the script's AST</param>
/// <returns>A descion to stop searching if the right commandAst was found,
/// or a decision to continue if it wasn't found</returns>
public override AstVisitAction VisitCommand(CommandAst commandAst)
{
if (commandAst.InvocationOperator.Equals(TokenKind.Dot) &&
commandAst.CommandElements[0] is StringConstantExpressionAst)
{
// Strip any quote characters off of the string
string fileName = commandAst.CommandElements[0].Extent.Text.Trim('\'', '"');
DotSourcedFiles.Add(fileName);
}
return base.VisitCommand(commandAst);
}
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using System.Management.Automation.Language;
namespace Microsoft.PowerShell.EditorServices
{
/// <summary>
/// The vistor used to find the dont sourced files in an AST
/// </summary>
internal class FindDotSourcedVisitor : AstVisitor
{
/// <summary>
/// A hash set of the dot sourced files (because we don't want duplicates)
/// </summary>
public HashSet<string> DotSourcedFiles { get; private set; }
public FindDotSourcedVisitor()
{
this.DotSourcedFiles = new HashSet<string>();
}
/// <summary>
/// Checks to see if the command invocation is a dot
/// in order to find a dot sourced file
/// </summary>
/// <param name="commandAst">A CommandAst object in the script's AST</param>
/// <returns>A descion to stop searching if the right commandAst was found,
/// or a decision to continue if it wasn't found</returns>
public override AstVisitAction VisitCommand(CommandAst commandAst)
{
if (commandAst.InvocationOperator.Equals(TokenKind.Dot))
{
// Strip any quote characters off of the string
string fileName = commandAst.CommandElements[0].Extent.Text.Trim('\'', '"');
DotSourcedFiles.Add(fileName);
}
return base.VisitCommand(commandAst);
}
}
}
| mit | C# |
35f69b9fc75911e0b72afb4592fe661ffb6e422b | Change uow to default to IsolationLevel.RepeatableRead | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/UnitOfWork.cs | using System;
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; }
private readonly Guid _guid = Guid.NewGuid();
public UnitOfWork(IDbFactory factory, ISession session,
IsolationLevel isolationLevel = IsolationLevel.RepeatableRead, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
{
if (sessionOnlyForThisUnitOfWork)
{
Session = session;
}
Transaction = session.BeginTransaction(isolationLevel);
SqlDialect = session.SqlDialect;
}
protected bool Equals(UnitOfWork other)
{
return _guid.Equals(other._guid);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UnitOfWork) obj);
}
public override int GetHashCode()
{
return _guid.GetHashCode();
}
public static bool operator ==(UnitOfWork left, UnitOfWork right)
{
return Equals(left, right);
}
public static bool operator !=(UnitOfWork left, UnitOfWork right)
{
return !Equals(left, right);
}
}
}
| using System;
using System.Data;
using Dapper.FastCrud;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public class UnitOfWork : DbTransaction, IUnitOfWork
{
public SqlDialect SqlDialect { get; }
private readonly Guid _guid = Guid.NewGuid();
public UnitOfWork(IDbFactory factory, ISession session,
IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory)
{
if (sessionOnlyForThisUnitOfWork)
{
Session = session;
}
Transaction = session.BeginTransaction(isolationLevel);
SqlDialect = session.SqlDialect;
}
protected bool Equals(UnitOfWork other)
{
return _guid.Equals(other._guid);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((UnitOfWork) obj);
}
public override int GetHashCode()
{
return _guid.GetHashCode();
}
public static bool operator ==(UnitOfWork left, UnitOfWork right)
{
return Equals(left, right);
}
public static bool operator !=(UnitOfWork left, UnitOfWork right)
{
return !Equals(left, right);
}
}
}
| mit | C# |
f5987a931c10cf1c67307f80c8fb0a3dbcfce5a8 | Add lazy loading | Branimir123/ZobShop,Branimir123/ZobShop,Branimir123/ZobShop | src/ZobShop.Data/ZobShopEntities.cs | src/ZobShop.Data/ZobShopEntities.cs | using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Microsoft.AspNet.Identity.EntityFramework;
using ZobShop.Models;
namespace ZobShop.Data
{
public class ZobShopEntities : IdentityDbContext<User>
{
public ZobShopEntities()
: base("ZobShopDb", throwIfV1Schema: false)
{
this.Configuration.AutoDetectChangesEnabled = true;
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ProxyCreationEnabled = true;
}
public static ZobShopEntities Create()
{
return new ZobShopEntities();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<ProductRating> ProductRatings { get; set; }
public DbSet<Review> Reviews { get; set; }
}
}
| using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Microsoft.AspNet.Identity.EntityFramework;
using ZobShop.Models;
namespace ZobShop.Data
{
public class ZobShopEntities : IdentityDbContext<User>
{
public ZobShopEntities()
: base("ZobShopDb", throwIfV1Schema: false)
{
}
public static ZobShopEntities Create()
{
return new ZobShopEntities();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<ProductRating> ProductRatings { get; set; }
public DbSet<Review> Reviews { get; set; }
}
}
| mit | C# |
a4be1c45c6991896515a40f22e72b069e99f633e | Comment fix | OPEXGroup/ITCC.Library | ITCC.HTTP/Enums/AuthorizationStatus.cs | ITCC.HTTP/Enums/AuthorizationStatus.cs | namespace ITCC.HTTP.Enums
{
/// <summary>
/// Represents possible authorization result
/// </summary>
public enum AuthorizationStatus
{
NotRequired,
/// <summary>
/// Request will be processed
/// </summary>
Ok,
/// <summary>
/// Another authentification token must be provided (401)
/// </summary>
Unauthorized,
/// <summary>
/// Resourse access in permanently forbidded for this account (403)
/// </summary>
Forbidden,
/// <summary>
/// Too many requests from current user
/// </summary>
TooManyRequests,
/// <summary>
/// Internal server error occured during authentification
/// </summary>
InternalError
}
} | namespace ITCC.HTTP.Enums
{
/// <summary>
/// Represents possible authorization result
/// </summary>
public enum AuthorizationStatus
{
NotRequired,
/// <summary>
/// Request will be processed
/// </summary>
Ok,
/// <summary>
/// Another authentification token must be provided (401)
/// </summary>
Unauthorized,
/// <summary>
/// Resourse access in permanently forbidded for this account (403)
/// </summary>
Forbidden,
/// <summary>
/// Too many requests from current user
/// </summary>
TooManyRequests,
// <summary>
/// Internal server error occured during authentification
/// </summary>
InternalError
}
} | bsd-2-clause | C# |
2872c89ab086e473b305280e61c4f018e5eaaddc | Revert to main menu on 0 balls left. | s-soltys/PoolVR | Assets/PoolVR/Scripts/ScoreCounter.cs | Assets/PoolVR/Scripts/ScoreCounter.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zenject;
public class ScoreCounter : MonoBehaviour
{
[Inject]
public StageStats Stats { get; private set; }
void Start() {
Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
StartCoroutine(Count());
}
IEnumerator Count()
{
while (true)
{
yield return new WaitForSeconds(1);
Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
if (Stats.BallsLeft == 0)
{
SceneManager.LoadScene("MainMenu");
}
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Zenject;
public class ScoreCounter : MonoBehaviour
{
[Inject]
public StageStats Stats { get; private set; }
void Start() {
Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
StartCoroutine(Count());
}
IEnumerator Count()
{
while (true)
{
yield return new WaitForSeconds(1);
Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length;
}
}
}
| mit | C# |
5183a606f5a27edbb63732179bf2cd9b869973d8 | Add ThrowsAnyWithMessage | whampson/cascara,whampson/bft-spec | Cascara.Tests/Src/Extensions/AssertExtensions.cs | Cascara.Tests/Src/Extensions/AssertExtensions.cs | using System;
using Xunit;
namespace Cascara.Tests.Extensions
{
public class AssertExtensions : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(message, ex.Message);
return ex;
}
public static T ThrowsWithMessage<T>(Func<object> testCode, string fmt, params object[] args)
where T : Exception
{
string message = string.Format(fmt, args);
var ex = Assert.Throws<T>(testCode);
Assert.Equal(message, ex.Message);
return ex;
}
public static T ThrowsAnyWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.ThrowsAny<T>(testCode);
Assert.Equal(message, ex.Message);
return ex;
}
public static T ThrowsAnyWithMessage<T>(Func<object> testCode, string fmt, params object[] args)
where T : Exception
{
string message = string.Format(fmt, args);
var ex = Assert.ThrowsAny<T>(testCode);
Assert.Equal(message, ex.Message);
return ex;
}
}
}
| using System;
using Xunit;
namespace Cascara.Tests.Extensions
{
public class AssertExtensions : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
public static T ThrowsWithMessage<T>(Func<object> testCode, string fmt, params object[] args)
where T : Exception
{
string message = string.Format(fmt, args);
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
}
}
| mit | C# |
21501ddf905989dc82e2a3fb8238a525e403631f | Fix field order in keyboard reactive effect | WolfspiritM/Colore,danpierce1/Colore,CoraleStudios/Colore | Corale.Colore/Razer/Keyboard/Effects/Reactive.cs | Corale.Colore/Razer/Keyboard/Effects/Reactive.cs | // ---------------------------------------------------------------------------------------
// <copyright file="Reactive.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
// of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
// do not take responsibility for any harm caused, direct or indirect, to any
// Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Keyboard.Effects
{
using System.Runtime.InteropServices;
using Corale.Colore.Annotations;
using Corale.Colore.Core;
/// <summary>
/// Describes the reactive effect type.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Reactive
{
/// <summary>
/// The duration of the effect.
/// </summary>
[PublicAPI]
public Duration Duration;
/// <summary>
/// Color of the effect.
/// </summary>
[PublicAPI]
public Color Color;
/// <summary>
/// Initializes a new instance of the <see cref="Reactive" /> struct.
/// </summary>
/// <param name="color">Color to apply when key is hit.</param>
/// <param name="duration">Duration to illuminate the key.</param>
public Reactive(Color color, Duration duration)
{
Color = color;
Duration = duration;
}
}
}
| // ---------------------------------------------------------------------------------------
// <copyright file="Reactive.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
// of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
// do not take responsibility for any harm caused, direct or indirect, to any
// Razer peripherals via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Keyboard.Effects
{
using System.Runtime.InteropServices;
using Corale.Colore.Annotations;
using Corale.Colore.Core;
/// <summary>
/// Describes the reactive effect type.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Reactive
{
/// <summary>
/// Color of the effect.
/// </summary>
[PublicAPI]
public Color Color;
/// <summary>
/// The duration of the effect.
/// </summary>
[PublicAPI]
public Duration Duration;
/// <summary>
/// Initializes a new instance of the <see cref="Reactive" /> struct.
/// </summary>
/// <param name="color">Color to apply when key is hit.</param>
/// <param name="duration">Duration to illuminate the key.</param>
public Reactive(Color color, Duration duration)
{
Color = color;
Duration = duration;
}
}
}
| mit | C# |
84b591396487a6dde844feff050dca57f425fc68 | Add constructors to table.cs | Ackara/Daterpillar | src/Daterpillar.Core/Table.cs | src/Daterpillar.Core/Table.cs | using System.Collections.Generic;
using System.Xml.Serialization;
namespace Gigobyte.Daterpillar
{
/// <summary>
/// Represents a database table.
/// </summary>
public class Table
{
public Table() : this(string.Empty, new Column[0])
{
}
public Table(string name) : this(name, new Column[0])
{
}
public Table(string name, IEnumerable<Column> columns)
{
Name = name;
Columns = new List<Column>(columns);
ForeignKeys = new List<ForeignKey>();
Modifiers = new List<string>();
Indexes = new List<Index>();
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
[XmlAttribute("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the comment.
/// </summary>
/// <value>The comment.</value>
[XmlElement("comment")]
public string Comment { get; set; }
/// <summary>
/// Gets or sets the modifiers.
/// </summary>
/// <value>The modifiers.</value>
[XmlElement("modifier")]
public List<string> Modifiers { get; set; }
/// <summary>
/// Gets or sets the columns.
/// </summary>
/// <value>The columns.</value>
[XmlElement("column")]
public List<Column> Columns { get; set; }
/// <summary>
/// Gets or sets the foreign keys.
/// </summary>
/// <value>The foreign keys.</value>
[XmlElement("foreignKey")]
public List<ForeignKey> ForeignKeys { get; set; }
/// <summary>
/// Gets or sets the indexes.
/// </summary>
/// <value>The indexes.</value>
[XmlElement("index")]
public List<Index> Indexes { get; set; }
}
} | using System.Collections.Generic;
using System.Xml.Serialization;
namespace Gigobyte.Daterpillar
{
/// <summary>
/// Represents a database table.
/// </summary>
public class Table
{
public Table()
{
Columns = new List<Column>();
Modifiers = new List<string>();
ForeignKeys = new List<ForeignKey>();
Indexes = new List<Index>();
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
[XmlAttribute("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the comment.
/// </summary>
/// <value>The comment.</value>
[XmlElement("comment")]
public string Comment { get; set; }
/// <summary>
/// Gets or sets the modifiers.
/// </summary>
/// <value>The modifiers.</value>
[XmlElement("modifier")]
public List<string> Modifiers { get; set; }
/// <summary>
/// Gets or sets the columns.
/// </summary>
/// <value>The columns.</value>
[XmlElement("column")]
public List<Column> Columns { get; set; }
/// <summary>
/// Gets or sets the foreign keys.
/// </summary>
/// <value>The foreign keys.</value>
[XmlElement("foreignKey")]
public List<ForeignKey> ForeignKeys { get; set; }
/// <summary>
/// Gets or sets the indexes.
/// </summary>
/// <value>The indexes.</value>
[XmlElement("index")]
public List<Index> Indexes { get; set; }
}
} | mit | C# |
1a378ce1c62ba1db44c4e266617a579d1745e525 | Update version | smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | // #[license]
// Smartsheet SDK for C#
// %%
// Copyright (C) 2014 Smartsheet
// %%
// 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.
// %[license]
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("Smartsheet C# SDK")]
[assembly: AssemblyDescription("Library that uses C# to connect to Smartsheet services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Smartsheet")]
[assembly: AssemblyProduct("Smartsheet_csharp_sdk.Properties")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible To false makes the types in this assembly not visible
// To COM components. If you need To access a Type in this assembly from
// COM, set the ComVisible attribute To true on that Type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed To COM
[assembly: Guid("77f0da27-4da3-437b-ac15-82643cdf2fa6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
| // #[license]
// Smartsheet SDK for C#
// %%
// Copyright (C) 2014 Smartsheet
// %%
// 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.
// %[license]
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("Smartsheet C# SDK")]
[assembly: AssemblyDescription("Library that uses C# to connect to Smartsheet services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Smartsheet")]
[assembly: AssemblyProduct("Smartsheet_csharp_sdk.Properties")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible To false makes the types in this assembly not visible
// To COM components. If you need To access a Type in this assembly from
// COM, set the ComVisible attribute To true on that Type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed To COM
[assembly: Guid("77f0da27-4da3-437b-ac15-82643cdf2fa6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.0.2.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
| apache-2.0 | C# |
845295cd57fafda4198aece29a518bd1d352bebf | Set up initial UI | xNovax/Fortitude | Fortitude/Program.cs | Fortitude/Program.cs | using System;
using System.Threading;
namespace Fortitude
{
internal class Program
{
private char[] allCharacters =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '<', '>', '?'
};
private static void Main()
{
InitializeProgram();
string realPass = "password123";
Console.ReadLine();
}
public static void MakePassword()
{
}
public static void CheckPassword()
{
}
public static void InitializeProgram()
{
Console.Title = ("Fortitude");
DrawSeparator();
Console.WriteLine("Welcome to Fortitude!");
DrawSeparator();
}
public static void DrawSeparator()
{
var worker = new Thread(DrawSeparatorWork);
worker.Start();
worker.Join();
}
private static void DrawSeparatorWork()
{
for (int i = 0; i < Console.WindowWidth; i++)
{
Console.Write("=");
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fortitude
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
c8cfe292add6424a3959806839e2993ba8297a57 | Improve naming of tests to clearly indicate the feature to be tested | oliverzick/Delizious-Filtering | src/Library.Test/SameTests.cs | src/Library.Test/SameTests.cs | #region Copyright and license
// // <copyright file="SameTests.cs" company="Oliver Zick">
// // Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// // 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.
// // </license>
#endregion
namespace Delizious.Filtering
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class SameTests
{
[TestMethod]
public void Match_Fails_When_Value_To_Match_Is_Null_But_Reference_Is_An_Instance()
{
Assert.IsFalse(Match.Same(new GenericParameterHelper()).Matches(null));
}
[TestMethod]
public void Match_Fails_When_Value_To_Match_And_Reference_Are_Different_Instances()
{
Assert.IsFalse(Match.Same(new GenericParameterHelper()).Matches(new GenericParameterHelper()));
}
[TestMethod]
public void Match_Succeeds_When_Value_To_Match_And_Reference_Are_Same_Instance()
{
var obj = new GenericParameterHelper();
Assert.IsTrue(Match.Same(obj).Matches(obj));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Match_Throws_Exception_When_Reference_Is_Null()
{
Match.Same<GenericParameterHelper>(null);
}
}
}
| #region Copyright and license
// // <copyright file="SameTests.cs" company="Oliver Zick">
// // Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// // 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.
// // </license>
#endregion
namespace Delizious.Filtering
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class SameTests
{
[TestMethod]
public void Fail__When_Reference_Is_An_Instance_And_Value_Is_Null()
{
Assert.IsFalse(Match.Same(new GenericParameterHelper()).Matches(null));
}
[TestMethod]
public void Fail__When_Reference_And_Value_Are_Not_Same()
{
Assert.IsFalse(Match.Same(new GenericParameterHelper()).Matches(new GenericParameterHelper()));
}
[TestMethod]
public void Succeed__When_Reference_And_Value_Are_Same()
{
var obj = new GenericParameterHelper();
Assert.IsTrue(Match.Same(obj).Matches(obj));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Throw_Exception__When_Reference_Is_Null()
{
Match.Same<GenericParameterHelper>(null);
}
}
}
| apache-2.0 | C# |
e479051daaac55a20d04265f89072879b97a010e | add some summary documentation | jadiaz/aspnet5 | src/MvcApplication/Startup.cs | src/MvcApplication/Startup.cs | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
namespace MvcApplication.Web
{
public class Startup
{
public Startup (IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("webConfig.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; private set; }
/// The purpose of this method is to setup dependency injection
/// Here the application learns about the services that will be
/// supplied to the application
public void ConfigureServices(IServiceCollection services)
{
// Add MVC to services container
services.AddMvc();
}
public void ConfigureDevelopment(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// Add Console logging to container
loggerFactory.AddConsole();
// Use default error page
app.UseErrorPage();
// Show runtime information on a page (DEVELOPMENT)
app.UseRuntimeInfoPage();
Configure(app);
}
public void ConfigureProduction(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// Add Console logging to container
loggerFactory.AddConsole();
// Use custom error handler to catch exceptions and log them
app.UseErrorHandler("/error.html");
Configure(app);
}
/// Configure allows the application to opt-into the services that are needed
/// We can also have separate environment configurations
public void Configure(IApplicationBuilder app)
{
// Add MVC to the request pipeline
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "api",
template: "{controller}/{id?}");
});
}
}
}
| using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
namespace MvcApplication.Web
{
public class Startup
{
public Startup (IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("webConfig.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
// Add MVC to services container
services.AddMvc();
}
public void ConfigureDevelopment(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// Add Console logging to container
loggerFactory.AddConsole();
// Use default error page
app.UseErrorPage();
// Show runtime information on a page (DEVELOPMENT)
app.UseRuntimeInfoPage();
Configure(app);
}
public void ConfigureProduction(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// Add Console logging to container
loggerFactory.AddConsole();
// Use custom error handler to catch exceptions and log them
app.UseErrorHandler("/error.html");
Configure(app);
}
public void Configure(IApplicationBuilder app)
{
// Add MVC to the request pipeline
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "api",
template: "{controller}/{id?}");
});
}
}
}
| mit | C# |
9359e1271712866edf3b9495b4690217e5d917e9 | Update Access.cs | lordmilko/PrtgAPI,lordmilko/PrtgAPI | PrtgAPI/Enums/Access.cs | PrtgAPI/Enums/Access.cs | namespace Prtg
{
/// <summary>
/// Specifies the Access Rights applied to a PRTG Object.
/// </summary>
public enum Access
{
Inherited,
/// <summary>
/// The object is not displayed. Logs, tickets and alarms pertaining to the object are not visible.
/// </summary>
None,
/// <summary>
/// The object can be viewed but not edited.
/// </summary>
Read,
/// <summary>
/// The object can be viewed, edited and deleted.
/// </summary>
Write,
/// <summary>
/// The object can be viewed, edited and deleted. In addition, Access Rights can be modified.
/// </summary>
Full,
/// <summary>
/// All options are available.
/// </summary>
Admin
}
}
| namespace Prtg
{
/// <summary>
/// Specifies the Access Rights applied to a PRTG Object.
/// </summary>
public enum Access
{
/// <summary>
/// The object is not displayed. Logs, tickets and alarms pertaining to the object are not visible.
/// </summary>
None,
/// <summary>
/// The object can be viewed but not edited.
/// </summary>
Read,
/// <summary>
/// The object can be viewed, edited and deleted.
/// </summary>
Write,
/// <summary>
/// The object can be viewed, edited and deleted. In addition, Access Rights can be modified.
/// </summary>
Full,
/// <summary>
/// All options are available.
/// </summary>
Admin
}
}
| mit | C# |
b81081b7638adfd2f01b3c1234cea6c0ea1a4c38 | Update FizzBuzz.cs | michaeljwebb/Algorithm-Practice | LeetCode/FizzBuzz.cs | LeetCode/FizzBuzz.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Services;
using System.Text;
class FizzBuzz
{
private static void Main(string[] args)
{
for (int i = 1; i < 16; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Services;
using System.Text;
using System.Threading.Tasks;
class FizzBuzz
{
private static void Main(string[] args)
{
for (int i = 1; i < 16; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
}
}
| mit | C# |
2314d3e15c38ac16d4528e1c4fc2dec74b0d152c | Move the watchdog verify | Cyberboss/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server | tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs | tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs | using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Host.Watchdog;
namespace Tgstation.Server.Host.Service.Tests
{
/// <summary>
/// Tests for <see cref="ServerService"/>
/// </summary>
[TestClass]
public sealed class TestServerService
{
[TestMethod]
public void TestConstructionAndDisposal()
{
Assert.ThrowsException<ArgumentNullException>(() => new ServerService(null, null, default));
var mockWatchdogFactory = new Mock<IWatchdogFactory>();
Assert.ThrowsException<ArgumentNullException>(() => new ServerService(mockWatchdogFactory.Object, null, default));
var mockLoggerFactory = new LoggerFactory();
new ServerService(mockWatchdogFactory.Object, mockLoggerFactory, default).Dispose();
}
[TestMethod]
public void TestRun()
{
var type = typeof(ServerService);
var onStart = type.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
var onStop = type.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
var mockWatchdog = new Mock<IWatchdog>();
var args = Array.Empty<string>();
CancellationToken cancellationToken;
mockWatchdog.Setup(x => x.RunAsync(false, args, It.IsAny<CancellationToken>())).Callback((bool x, string[] _, CancellationToken token) => cancellationToken = token).Returns(Task.CompletedTask).Verifiable();
var mockWatchdogFactory = new Mock<IWatchdogFactory>();
var mockLoggerFactory = new LoggerFactory();
mockWatchdogFactory.Setup(x => x.CreateWatchdog(mockLoggerFactory)).Returns(mockWatchdog.Object).Verifiable();
using (var service = new ServerService(mockWatchdogFactory.Object, mockLoggerFactory, default))
{
onStart.Invoke(service, new object[] { args });
mockWatchdog.VerifyAll();
Assert.IsFalse(cancellationToken.IsCancellationRequested);
onStop.Invoke(service, Array.Empty<object>());
Assert.IsTrue(cancellationToken.IsCancellationRequested);
}
mockWatchdogFactory.VerifyAll();
}
}
}
| using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Host.Watchdog;
namespace Tgstation.Server.Host.Service.Tests
{
/// <summary>
/// Tests for <see cref="ServerService"/>
/// </summary>
[TestClass]
public sealed class TestServerService
{
[TestMethod]
public void TestConstructionAndDisposal()
{
Assert.ThrowsException<ArgumentNullException>(() => new ServerService(null, null, default));
var mockWatchdogFactory = new Mock<IWatchdogFactory>();
Assert.ThrowsException<ArgumentNullException>(() => new ServerService(mockWatchdogFactory.Object, null, default));
var mockLoggerFactory = new LoggerFactory();
new ServerService(mockWatchdogFactory.Object, mockLoggerFactory, default).Dispose();
}
[TestMethod]
public void TestRun()
{
var type = typeof(ServerService);
var onStart = type.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
var onStop = type.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
var mockWatchdog = new Mock<IWatchdog>();
var args = Array.Empty<string>();
CancellationToken cancellationToken;
mockWatchdog.Setup(x => x.RunAsync(false, args, It.IsAny<CancellationToken>())).Callback((bool x, string[] _, CancellationToken token) => cancellationToken = token).Returns(Task.CompletedTask).Verifiable();
var mockWatchdogFactory = new Mock<IWatchdogFactory>();
var mockLoggerFactory = new LoggerFactory();
mockWatchdogFactory.Setup(x => x.CreateWatchdog(mockLoggerFactory)).Returns(mockWatchdog.Object).Verifiable();
using (var service = new ServerService(mockWatchdogFactory.Object, mockLoggerFactory, default))
{
onStart.Invoke(service, new object[] { args });
Assert.IsFalse(cancellationToken.IsCancellationRequested);
onStop.Invoke(service, Array.Empty<object>());
Assert.IsTrue(cancellationToken.IsCancellationRequested);
mockWatchdog.VerifyAll();
}
mockWatchdogFactory.VerifyAll();
}
}
}
| agpl-3.0 | C# |
aed438e99ede87d718b6fc021823558c73dc0fb0 | Clone event on wrapping to TimedEvent | melanchall/drymidi,melanchall/drywetmidi,melanchall/drywetmidi | DryWetMidi/Smf/Interaction/TimedEventsManager/TimedEventsManager.cs | DryWetMidi/Smf/Interaction/TimedEventsManager/TimedEventsManager.cs | using System;
using System.Collections.Generic;
namespace Melanchall.DryWetMidi.Smf.Interaction
{
public sealed class TimedEventsManager : IDisposable
{
#region Fields
private readonly EventsCollection _eventsCollection;
private bool _disposed;
#endregion
#region Constructor
public TimedEventsManager(EventsCollection eventsCollection, Comparison<MidiEvent> sameTimeEventsComparison = null)
{
if (eventsCollection == null)
throw new ArgumentNullException(nameof(eventsCollection));
_eventsCollection = eventsCollection;
Events = new TimedEventsCollection(CreateTimedEvents(eventsCollection));
}
#endregion
#region Properties
public TimedEventsCollection Events { get; }
#endregion
#region Methods
public void SaveChanges()
{
_eventsCollection.Clear();
var time = 0L;
foreach (var e in Events)
{
var midiEvent = e.Event;
midiEvent.DeltaTime = e.Time - time;
_eventsCollection.Add(midiEvent);
time = e.Time;
}
}
private static IEnumerable<TimedEvent> CreateTimedEvents(EventsCollection events)
{
if (events == null)
throw new ArgumentNullException(nameof(events));
var time = 0L;
foreach (var midiEvent in events)
{
time += midiEvent.DeltaTime;
yield return new TimedEvent(midiEvent.Clone(), time);
}
}
#endregion
#region IDisposable
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
SaveChanges();
_disposed = true;
}
#endregion
}
}
| using System;
using System.Collections.Generic;
namespace Melanchall.DryWetMidi.Smf.Interaction
{
public sealed class TimedEventsManager : IDisposable
{
#region Fields
private readonly EventsCollection _eventsCollection;
private bool _disposed;
#endregion
#region Constructor
public TimedEventsManager(EventsCollection eventsCollection, Comparison<MidiEvent> sameTimeEventsComparison = null)
{
if (eventsCollection == null)
throw new ArgumentNullException(nameof(eventsCollection));
_eventsCollection = eventsCollection;
Events = new TimedEventsCollection(CreateTimedEvents(eventsCollection));
}
#endregion
#region Properties
public TimedEventsCollection Events { get; }
#endregion
#region Methods
public void SaveChanges()
{
_eventsCollection.Clear();
var time = 0L;
foreach (var e in Events)
{
var midiEvent = e.Event;
midiEvent.DeltaTime = e.Time - time;
_eventsCollection.Add(midiEvent);
time = e.Time;
}
}
private static IEnumerable<TimedEvent> CreateTimedEvents(EventsCollection events)
{
if (events == null)
throw new ArgumentNullException(nameof(events));
var time = 0L;
foreach (var midiEvent in events)
{
time += midiEvent.DeltaTime;
yield return new TimedEvent(midiEvent, time);
}
}
#endregion
#region IDisposable
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
SaveChanges();
_disposed = true;
}
#endregion
}
}
| mit | C# |
c4af9af5eb54017031677ef0d2cb345cea8ba886 | fix redundent code | mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,duplicati/duplicati | Duplicati/Library/Utility/WinTools.cs | Duplicati/Library/Utility/WinTools.cs | #region Disclaimer / License
// Copyright (C) 2019, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library 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.
//
// This library 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.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#endregion
using System;
using Duplicati.Library.Common;
namespace Duplicati.Library.Utility
{
public static class WinTools
{
public static string GetWindowsGpgExePath()
{
if (!Platform.IsClientWindows)
{
return null;
}
// return gpg4win if it exists
var location32 = Library.Utility.RegistryUtility.GetDataByValueName(@"SOFTWARE\WOW6432Node\GnuPG", "Install Directory");
var location64 = Library.Utility.RegistryUtility.GetDataByValueName(@"SOFTWARE\GnuPG", "Install Directory");
var gpg4winLocation = string.IsNullOrEmpty(location64) ? location32 : location64;
if (!string.IsNullOrEmpty(gpg4winLocation))
{
return System.IO.Path.Combine(gpg4winLocation, "bin", "gpg.exe");
}
// otherwise return our included win-tools
var wintoolsPath = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
"win-tools", "gpg.exe");
return string.IsNullOrEmpty(wintoolsPath) ? null : wintoolsPath;
}
}
}
| #region Disclaimer / License
// Copyright (C) 2019, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library 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.
//
// This library 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.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#endregion
using System;
using Duplicati.Library.Common;
namespace Duplicati.Library.Utility
{
public static class WinTools
{
public static string GetWindowsGpgExePath()
{
if (!Platform.IsClientWindows)
{
return null;
}
// return gpg4win if it exists
var location32 = Library.Utility.RegistryUtility.GetDataByValueName(@"SOFTWARE\WOW6432Node\GnuPG", "Install Directory");
var location64 = Library.Utility.RegistryUtility.GetDataByValueName(@"SOFTWARE\GnuPG", "Install Directory");
var gpg4winLocation = string.IsNullOrEmpty(location64) ? location32 : location64;
if (!string.IsNullOrEmpty(gpg4winLocation))
{
return string.IsNullOrEmpty(gpg4winLocation) ? null : System.IO.Path.Combine(gpg4winLocation, "bin", "gpg.exe");
}
// otherwise return our included win-tools
var wintoolsPath = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
"win-tools", "gpg.exe");
return string.IsNullOrEmpty(wintoolsPath) ? null : wintoolsPath;
}
}
}
| lgpl-2.1 | C# |
15a0ce09d614208018c60f6a9354feba66b8bad8 | fix build | MetacoSA/NBitcoin,NicolasDorier/NBitcoin,MetacoSA/NBitcoin | NBitcoin/Protocol/Behaviors/SlimChainBehavior.cs | NBitcoin/Protocol/Behaviors/SlimChainBehavior.cs | #if !NOSOCKET
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace NBitcoin.Protocol.Behaviors
{
/// <summary>
/// Behavior to keep a SlimChain in sync with the remote node
/// </summary>
public class SlimChainBehavior : NodeBehavior
{
private readonly SlimChain _Chain;
public SlimChain Chain
{
get
{
return _Chain;
}
}
public SlimChainBehavior(SlimChain chain)
{
if(chain == null)
throw new ArgumentNullException(nameof(chain));
_Chain = chain;
}
public override object Clone()
{
return new SlimChainBehavior(Chain);
}
Timer _Refresh;
protected override void AttachCore()
{
_Refresh = new Timer(o =>
{
TrySync();
}, null, 0, (int)TimeSpan.FromMinutes(10).TotalMilliseconds);
RegisterDisposable(_Refresh);
if(AttachedNode.State == NodeState.Connected)
{
AttachedNode.MyVersion.StartHeight = Chain.Height;
}
AttachedNode.StateChanged += AttachedNode_StateChanged;
RegisterDisposable(AttachedNode.Filters.Add(Intercept));
}
void Intercept(IncomingMessage message, Action act)
{
message.Message.IfPayloadIs<HeadersPayload>(headers =>
{
bool updated = false;
foreach(var h in headers.Headers)
{
updated |= AddToChain(h);
}
if(updated)
{
message.Node.SendMessageAsync(new GetHeadersPayload()
{
BlockLocators = Chain.GetTipLocator()
});
}
});
message.Message.IfPayloadIs<InvPayload>(invs =>
{
var needSync = invs.Where(v => v.Type == InventoryType.MSG_BLOCK)
.Any(b => !_Chain.Contains(b.Hash));
if(needSync)
TrySync();
});
}
private bool AddToChain(BlockHeader blockHeader)
{
return Chain.TrySetTip(blockHeader.GetHash(), blockHeader.HashPrevBlock, true);
}
private void TrySync()
{
var node = AttachedNode;
if(node != null)
{
if(node.State == NodeState.HandShaked)
{
node.SendMessageAsync(new GetHeadersPayload()
{
BlockLocators = Chain.GetTipLocator()
});
}
}
}
void AttachedNode_StateChanged(Node node, NodeState oldState)
{
if(node.State == NodeState.HandShaked)
{
node.SendMessageAsync(new SendHeadersPayload());
TrySync();
}
}
protected override void DetachCore()
{
AttachedNode.StateChanged -= AttachedNode_StateChanged;
}
}
}
#endif | using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace NBitcoin.Protocol.Behaviors
{
/// <summary>
/// Behavior to keep a SlimChain in sync with the remote node
/// </summary>
public class SlimChainBehavior : NodeBehavior
{
private readonly SlimChain _Chain;
public SlimChain Chain
{
get
{
return _Chain;
}
}
public SlimChainBehavior(SlimChain chain)
{
if(chain == null)
throw new ArgumentNullException(nameof(chain));
_Chain = chain;
}
public override object Clone()
{
return new SlimChainBehavior(Chain);
}
Timer _Refresh;
protected override void AttachCore()
{
_Refresh = new Timer(o =>
{
TrySync();
}, null, 0, (int)TimeSpan.FromMinutes(10).TotalMilliseconds);
RegisterDisposable(_Refresh);
if(AttachedNode.State == NodeState.Connected)
{
AttachedNode.MyVersion.StartHeight = Chain.Height;
}
AttachedNode.StateChanged += AttachedNode_StateChanged;
RegisterDisposable(AttachedNode.Filters.Add(Intercept));
}
void Intercept(IncomingMessage message, Action act)
{
message.Message.IfPayloadIs<HeadersPayload>(headers =>
{
bool updated = false;
foreach(var h in headers.Headers)
{
updated |= AddToChain(h);
}
if(updated)
{
message.Node.SendMessageAsync(new GetHeadersPayload()
{
BlockLocators = Chain.GetTipLocator()
});
}
});
message.Message.IfPayloadIs<InvPayload>(invs =>
{
var needSync = invs.Where(v => v.Type == InventoryType.MSG_BLOCK)
.Any(b => !_Chain.Contains(b.Hash));
if(needSync)
TrySync();
});
}
private bool AddToChain(BlockHeader blockHeader)
{
return Chain.TrySetTip(blockHeader.GetHash(), blockHeader.HashPrevBlock, true);
}
private void TrySync()
{
var node = AttachedNode;
if(node != null)
{
if(node.State == NodeState.HandShaked)
{
node.SendMessageAsync(new GetHeadersPayload()
{
BlockLocators = Chain.GetTipLocator()
});
}
}
}
void AttachedNode_StateChanged(Node node, NodeState oldState)
{
if(node.State == NodeState.HandShaked)
{
node.SendMessageAsync(new SendHeadersPayload());
TrySync();
}
}
protected override void DetachCore()
{
AttachedNode.StateChanged -= AttachedNode_StateChanged;
}
}
}
| mit | C# |
29a293aac7e1880006ed0de760c19bf00f19c4c9 | Remove superfluous test parameter | jagrem/slang,jagrem/slang,jagrem/slang | slang.Tests/Lexing/Literals/StringLiteralTests.cs | slang.Tests/Lexing/Literals/StringLiteralTests.cs | using System;
using NUnit.Framework;
using slang.Lexing;
using System.Linq;
using FluentAssertions;
using System.Collections.Generic;
namespace slang.Tests.Lexing.Literals
{
[TestFixture]
public class StringLiteralTests
{
[TestCaseSource("GetLiterals")]
public void Given_a_literal_as_a_string_When_parsed_Then_a_literal_type_is_returned(string input)
{
var result = Lexer.Analyze (input).ToArray ();
result.ShouldBeEquivalentTo (new[] { new { Value = "$" }, new { Value = input }, new { Value = "EOF" } });
}
static IEnumerable<TestCaseData> GetLiterals()
{
//string-literal:
// regular-string-literal
// | verbatim-string-literal
//regular-string-literal:
// " regular-string-literal-charactersopt "
//regular-string-literal-characters:
// regular-string-literal-character
// | regular-string-literal-characters regular-string-literal-character
//regular-string-literal-character:
// single-regular-string-literal-character
// | simple-escape-sequence
// | hexadecimal-escape-sequence
// | unicode-escape-sequence
//single-regular-string-literal-character:
// Any character except " (U+0022), \ (U+005C), and new-line-character
//verbatim-string-literal:
// @" verbatim -string-literal-charactersopt "
//verbatim-string-literal-characters:
// verbatim-string-literal-character
// | verbatim-string-literal-characters verbatim-string-literal-character
//verbatim-string-literal-character:
// single-verbatim-string-literal-character
// | quote-escape-sequence
//single-verbatim-string-literal-character:
// Any character except "
//quote-escape-sequence:
// ""
yield return null;
}
}
}
| using System;
using NUnit.Framework;
using slang.Lexing;
using System.Linq;
using FluentAssertions;
using System.Collections.Generic;
namespace slang.Tests.Lexing.Literals
{
[TestFixture]
public class StringLiteralTests
{
[TestCaseSource("GetLiterals")]
public void Given_a_literal_as_a_string_When_parsed_Then_a_literal_type_is_returned(string input, Type expectedType)
{
var result = Lexer.Analyze (input).ToArray ();
result.ShouldBeEquivalentTo (new[] { new { Value = "$" }, new { Value = input }, new { Value = "EOF" } });
result[1].Should ().BeOfType(expectedType);
}
static IEnumerable<TestCaseData> GetLiterals()
{
//string-literal:
// regular-string-literal
// | verbatim-string-literal
//regular-string-literal:
// " regular-string-literal-charactersopt "
//regular-string-literal-characters:
// regular-string-literal-character
// | regular-string-literal-characters regular-string-literal-character
//regular-string-literal-character:
// single-regular-string-literal-character
// | simple-escape-sequence
// | hexadecimal-escape-sequence
// | unicode-escape-sequence
//single-regular-string-literal-character:
// Any character except " (U+0022), \ (U+005C), and new-line-character
//verbatim-string-literal:
// @" verbatim -string-literal-charactersopt "
//verbatim-string-literal-characters:
// verbatim-string-literal-character
// | verbatim-string-literal-characters verbatim-string-literal-character
//verbatim-string-literal-character:
// single-verbatim-string-literal-character
// | quote-escape-sequence
//single-verbatim-string-literal-character:
// Any character except "
//quote-escape-sequence:
// ""
yield return null;
}
}
}
| mit | C# |
0fba772ab5bb374f3a2829b06b2f2859f4ad50b5 | Bump version to account for bug fix | dustyburwell/garlic | Garlic/Properties/AssemblyInfo.cs | Garlic/Properties/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Garlic")]
[assembly: AssemblyDescription("Google Analytics Client for .Net")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Dusty Burwell")]
[assembly: AssemblyProduct("Garlic Google Analytics Client")]
[assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Garlic")]
[assembly: AssemblyDescription("Google Analytics Client for .Net")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Dusty Burwell")]
[assembly: AssemblyProduct("Garlic Google Analytics Client")]
[assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
b68d1bc5e6f6814ca283b7c223944b5b3aa5ae4f | Build update | WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework | Framework.BuildTool/Command/RunSql.cs | Framework.BuildTool/Command/RunSql.cs | namespace Framework.BuildTool
{
using System;
using System.Data.SqlClient;
public class CommandRunSql : Command
{
public CommandRunSql()
: base("runSql", "Run sql scripts")
{
}
private void RunSql(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
var fileNameList = Framework.UtilFramework.FileNameList(Framework.UtilFramework.FolderName + "BuildTool/Sql/");
foreach (string fileName in fileNameList)
{
string text = Framework.UtilFramework.FileRead(fileName);
var sqlList = text.Split(new string[] { "\r\nGO", "\nGO", "GO\r\n", "GO\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string sql in sqlList)
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
}
public override void Run()
{
RunSql(Server.ConnectionManager.ConnectionString);
}
}
}
| namespace Framework.BuildTool
{
using System;
using System.Data.SqlClient;
public class CommandRunSql : Command
{
public CommandRunSql()
: base("runSql", "Run sql scripts")
{
}
private void RunSql(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
var fileNameList = Framework.UtilFramework.FileNameList(Framework.UtilFramework.FolderName + "BuildTool/Sql/");
foreach (string fileName in fileNameList)
{
string text = Framework.UtilFramework.FileRead(fileName);
var sqlList = text.Split(new string[] { "\r\nGO", "\nGO", "GO\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string sql in sqlList)
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.ExecuteNonQuery();
}
}
}
}
public override void Run()
{
RunSql(Server.ConnectionManager.ConnectionString);
}
}
}
| mit | C# |
6eca85a8bc49362dc581888c7e0185293c41ddfe | Comment for 'unit' structure | modulexcite/lokad-cqrs | Framework/Lokad.Cqrs.Portable/unit.cs | Framework/Lokad.Cqrs.Portable/unit.cs | using System;
using System.Runtime.InteropServices;
namespace Lokad.Cqrs
{
/// <summary>
/// Equivalent to System.Void which is not allowed to be used in the code for some reason.
/// </summary>
[ComVisible(true)]
[Serializable]
[StructLayout(LayoutKind.Sequential, Size = 1)]
public struct unit
{
public static readonly unit it = default(unit);
}
} | using System;
using System.Runtime.InteropServices;
namespace Lokad.Cqrs
{
[ComVisible(true)]
[Serializable]
[StructLayout(LayoutKind.Sequential, Size = 1)]
public struct unit
{
public static readonly unit it = default(unit);
}
} | bsd-3-clause | C# |
a65cfaef4b001bdb8f10cc776f05947515d5ecf0 | Update Relationship entity | glacasa/Mastonet | Mastonet/Entities/Relationship.cs | Mastonet/Entities/Relationship.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Mastonet.Entities
{
public class Relationship
{
/// <summary>
/// Target account id
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Whether the user is currently following the account
/// </summary>
[JsonProperty("following")]
public bool Following { get; set; }
/// <summary>
/// Whether the user is currently being followed by the account
/// </summary>
[JsonProperty("followed_by")]
public bool FollowedBy { get; set; }
/// <summary>
/// Whether the user is currently blocking the account
/// </summary>
[JsonProperty("blocking")]
public bool Blocking { get; set; }
/// <summary>
/// Whether the user is currently muting the account
/// </summary>
[JsonProperty("muting")]
public bool Muting { get; set; }
/// <summary>
/// Whether the user is also muting notifications
/// </summary>
[JsonProperty("muting_notifications")]
public bool MutingNotifications { get; set; }
/// <summary>
/// Whether the user has requested to follow the account
/// </summary>
[JsonProperty("requested")]
public bool Requested { get; set; }
/// <summary>
/// Whether the user is currently blocking the accounts's domain
/// </summary>
[JsonProperty("domain_blocking")]
public bool DomainBlocking { get; set; }
/// <summary>
/// Whether the user's reblogs will show up in the home timeline
/// </summary>
[JsonProperty("showing_reblogs")]
public bool ShowingReblogs { get; set; }
/// <summary>
/// Whether the user is currently endorsing the account
/// </summary>
[JsonProperty("endorsed")]
public bool Endorsed { get; set; }
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Mastonet.Entities
{
public class Relationship
{
/// <summary>
/// Target account id
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Whether the user is currently following the account
/// </summary>
[JsonProperty("following")]
public bool Following { get; set; }
/// <summary>
/// Whether the user is currently being followed by the account
/// </summary>
[JsonProperty("followed_by")]
public bool FollowedBy { get; set; }
/// <summary>
/// Whether the user is currently blocking the account
/// </summary>
[JsonProperty("blocking")]
public bool Blocking { get; set; }
/// <summary>
/// Whether the user is currently muting the account
/// </summary>
[JsonProperty("muting")]
public bool Muting { get; set; }
/// <summary>
/// Whether the user has requested to follow the account
/// </summary>
[JsonProperty("requested")]
public bool Requested { get; set; }
/// <summary>
/// Whether the user is currently blocking the accounts's domain
/// </summary>
[JsonProperty("domain_blocking")]
public bool DomainBlocking { get; set; }
}
}
| mit | C# |
787c16612f5e26c52c240dd9201525b81b89cd58 | Update CameraMovement.cs | highnet/Java-101,highnet/Java-101 | Unity/CameraMovement.cs | Unity/CameraMovement.cs | using UnityEngine;
using System.Collections;
public class CameraMovement : MonoBehaviour
{
public GameObject player; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
// Use this for initialization
void Start()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = this.transform.position - player.transform.position;
}
// LateUpdate is called after Update each frame
void LateUpdate()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
this.transform.position = player.transform.position + offset;
}
}
| mit | C# | |
2c77e8d9c394b12d3607bc8c2c162fac328895e9 | Fix for load by id | Red-Folder/WebCrawl-Functions | WebCrawlResults/run.csx | WebCrawlResults/run.csx | #r "Red-Folder.WebCrawl.dll"
using System.Net;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using Red_Folder.WebCrawl.Models;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
// parse query parameter
string id = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
.Value;
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set id to query string or body data
id = id ?? data?.id;
// Convert from connection string to uri & key
// Doesn't currently appear to be a vary to create a DocumentClient from a connection string
string documentDbEndpoint = System.Environment.GetEnvironmentVariable("APPSETTING_rfcwebcrawl_DOCUMENTDB");
string endpointUri = documentDbEndpoint.Split(';')[0].Split('=')[1];
string primaryKey = documentDbEndpoint.Split(';')[1].Split('=')[1];
string databaseName = "crawlOutput";
string collectionName = "WebCrawl";
DocumentClient client;
log.Info($"Creating client for: {endpointUri}");
client = new DocumentClient(new Uri(endpointUri), primaryKey);
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));
// Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
log.Info("Running LINQ query...");
CrawlResults results;
if (id == null || id.Length == 0)
{
results = client.CreateDocumentQuery<CrawlResults>(UriFactory
.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.OrderByDescending(f => f.Timestamp)
.FirstOrDefault();
}
else
{
results = client.CreateDocumentQuery<CrawlResults>(UriFactory
.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.Where(f => f.Id == id)
.FirstOrDefault();
}
string message = JsonConvert.SerializeObject(results);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(message)
};
return response;
}
| #r "Red-Folder.WebCrawl.dll"
using System.Net;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using Red_Folder.WebCrawl.Models;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
// parse query parameter
string id = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
.Value;
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set id to query string or body data
id = id ?? data?.id;
// Convert from connection string to uri & key
// Doesn't currently appear to be a vary to create a DocumentClient from a connection string
string documentDbEndpoint = System.Environment.GetEnvironmentVariable("APPSETTING_rfcwebcrawl_DOCUMENTDB");
string endpointUri = documentDbEndpoint.Split(';')[0].Split('=')[1];
string primaryKey = documentDbEndpoint.Split(';')[1].Split('=')[1];
string databaseName = "crawlOutput";
string collectionName = "WebCrawl";
DocumentClient client;
log.Info($"Creating client for: {endpointUri}");
client = new DocumentClient(new Uri(endpointUri), primaryKey);
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));
// Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
log.Info("Running LINQ query...");
CrawlResults results;
if (id == null || id.Length == 0)
{
results = client.CreateDocumentQuery<CrawlResults>(UriFactory
.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.OrderByDescending(f => f.Timestamp)
.FirstOrDefault();
}
else
{
results = client.CreateDocumentQuery<CrawlResults>(UriFactory
.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.Where(f => f.id == Id)
.FirstOrDefault();
}
string message = JsonConvert.SerializeObject(results);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(message)
};
return response;
}
| mit | C# |
ea4a13c317e8e125e830799e2644aba77725aa58 | add more exploratory tests to isolate the issue | pauldambra/ModulusChecker,pauldambra/ModulusChecker | PublicInterfaceTests/IssueFive.cs | PublicInterfaceTests/IssueFive.cs | using System;
using ModulusChecking;
using ModulusChecking.Models;
using NUnit.Framework;
namespace PublicInterfaceTests
{
/// <summary>
/// See https://github.com/pauldambra/ModulusChecker/issues/5
/// </summary>
public class IssueFive
{
private const string Sortcode = "775024";
private const string AccNumber = "26862368";
[Test]
public void ItCanRevalidateDetailsOnImmediateRepeat()
{
var checker = new ModulusChecker();
Assert.IsTrue(checker.CheckBankAccount(Sortcode, AccNumber));
Assert.IsTrue(checker.CheckBankAccount(Sortcode, AccNumber));
}
[Test]
[TestCase("776203", "01193899")]
[TestCase("089999", "66374958")]
public void SeparatingCheckPassesInIsolation(string sc, string an)
{
var checker = new ModulusChecker();
Assert.IsTrue(checker.CheckBankAccount(Sortcode, AccNumber));
}
[Test]
[TestCase("776203", "01193899")]
[TestCase("089999", "66374958")]
public void ItCanRevalidateDetailsOnSeparatedRepeat(string sc, string an)
{
var checker = new ModulusChecker();
Assert.IsTrue(checker.CheckBankAccount(Sortcode, AccNumber), string.Format("first check should have passed for {0} and {1}", Sortcode, AccNumber));
Assert.IsTrue(checker.CheckBankAccount(sc, an), string.Format("separating check should have passed for {0} and {1}", sc, an));
Assert.IsTrue(checker.CheckBankAccount(Sortcode, AccNumber), string.Format("second check should have passed for {0} and {1}", Sortcode, AccNumber));
}
}
} | using ModulusChecking;
using NUnit.Framework;
namespace PublicInterfaceTests
{
/// <summary>
/// See https://github.com/pauldambra/ModulusChecker/issues/5
/// </summary>
public class IssueFive
{
[Test]
public void ItCanRevalidateDetailsOnImmediateRepeat()
{
var sortcode = "775024";
var accNumber = "26862368";
var checker = new ModulusChecker();
Assert.IsTrue(checker.CheckBankAccount(sortcode, accNumber));
//Assert.IsTrue(checker.CheckBankAccount("776203", "01193899"));
Assert.IsTrue(checker.CheckBankAccount(sortcode, accNumber));
}
[Test]
public void ItCanRevalidateDetailsOnSeparatedRepeat()
{
const string sortcode = "775024";
const string accNumber = "26862368";
var checker = new ModulusChecker();
Assert.IsTrue(checker.CheckBankAccount(sortcode, accNumber));
Assert.IsTrue(checker.CheckBankAccount("776203", "01193899"));
Assert.IsTrue(checker.CheckBankAccount(sortcode, accNumber));
}
}
} | mit | C# |
fab04e5ca5e10af32d902cb93cdcff2bcf59e642 | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.Adobe/ValuesOut.cs | RegistryPlugin.Adobe/ValuesOut.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.Adobe
{
public class ValuesOut:IValueOut
{
public ValuesOut(string productName, string productVersion, string fullPath, DateTimeOffset lastOpened, string fileName, int fileSize, string fileSource, int pageCount)
{
ProductName = productName;
ProductVersion = productVersion;
FullPath = fullPath;
LastOpened = lastOpened;
FileName = fileName;
FileSize = fileSize;
FileSource = fileSource;
PageCount = pageCount;
}
public string ProductName { get; }
public string ProductVersion { get; }
public string FullPath { get; }
public DateTimeOffset LastOpened { get; }
public string FileName { get; }
public int FileSize { get; }
public string FileSource { get; }
public int PageCount { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Product: {ProductName} {ProductVersion}";
public string BatchValueData2 => $"FullPath: {FullPath}";
public string BatchValueData3 => $"LastOpened: {LastOpened.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.Adobe
{
public class ValuesOut:IValueOut
{
public ValuesOut(string productName, string productVersion, string fullPath, DateTimeOffset lastOpened, string fileName, int fileSize, string fileSource, int pageCount)
{
ProductName = productName;
ProductVersion = productVersion;
FullPath = fullPath;
LastOpened = lastOpened;
FileName = fileName;
FileSize = fileSize;
FileSource = fileSource;
PageCount = pageCount;
}
public string ProductName { get; }
public string ProductVersion { get; }
public string FullPath { get; }
public DateTimeOffset LastOpened { get; }
public string FileName { get; }
public int FileSize { get; }
public string FileSource { get; }
public int PageCount { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Product: {ProductName} {ProductVersion}";
public string BatchValueData2 => $"FullPath: {FullPath}";
public string BatchValueData3 => $"LastOpened: {LastOpened.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})";
}
}
| mit | C# |
56a27eee7d35d676d06c8cd8b4b432e23211635a | rename for enum type | tinohager/Nager.AmazonProductAdvertising,tinohager/Nager.AmazonProductAdvertising | Nager.AmazonProductAdvertising/Operation/AmazonOperationBase.cs | Nager.AmazonProductAdvertising/Operation/AmazonOperationBase.cs | using Nager.AmazonProductAdvertising.Model;
using System.Collections.Generic;
namespace Nager.AmazonProductAdvertising.Operation
{
public class AmazonOperationBase
{
public Dictionary<string, string> ParameterDictionary;
public AmazonOperationBase()
{
this.ParameterDictionary = new Dictionary<string, string>();
}
public void ResponseGroup(AmazonResponseGroup responseGroup)
{
this.AddOrReplace("ResponseGroup", responseGroup.ToString().Replace(" ", ""));
if (responseGroup == AmazonResponseGroup.RelatedItems)
{
RelationshipType(AmazonRelationshipType.Tracks);
}
}
public void RelationshipType(AmazonRelationshipType relationshipType)
{
this.AddOrReplace("RelationshipType", relationshipType.ToString());
}
public void SearchIndex(AmazonSearchIndex searchIndex)
{
this.AddOrReplace("SearchIndex", searchIndex.ToString());
}
public void AssociateTag(string associateTag)
{
this.AddOrReplace("AssociateTag", associateTag);
}
protected void AddOrReplace(string param, object value)
{
if (this.ParameterDictionary.ContainsKey(param))
{
this.ParameterDictionary[param] = value.ToString();
}
else
{
this.ParameterDictionary.Add(param, value.ToString());
}
}
}
}
| using Nager.AmazonProductAdvertising.Model;
using System.Collections.Generic;
namespace Nager.AmazonProductAdvertising.Operation
{
public class AmazonOperationBase
{
public Dictionary<string, string> ParameterDictionary;
public AmazonOperationBase()
{
this.ParameterDictionary = new Dictionary<string, string>();
}
public void ResponseGroup(AmazonResponseGroup responseGroup)
{
this.AddOrReplace("ResponseGroup", responseGroup.ToString().Replace(" ", ""));
if (responseGroup == AmazonResponseGroup.RelatedItems)
{
RelationshipType(AmazonRelationshipType.Tracks);
}
}
public void RelationshipType(AmazonRelationshipType responseGroup)
{
this.AddOrReplace("RelationshipType", responseGroup.ToString());
}
public void SearchIndex(AmazonSearchIndex searchIndex)
{
this.AddOrReplace("SearchIndex", searchIndex.ToString());
}
public void AssociateTag(string associateTag)
{
this.AddOrReplace("AssociateTag", associateTag);
}
protected void AddOrReplace(string param, object value)
{
if (this.ParameterDictionary.ContainsKey(param))
{
this.ParameterDictionary[param] = value.ToString();
}
else
{
this.ParameterDictionary.Add(param, value.ToString());
}
}
}
}
| mit | C# |
aabfe1617aef41497aa17fe11e4b4f29bd78680f | Fix WinRT build breaks (dotnet/corert#4398) | russellhadley/coreclr,ruben-ayrapetyan/coreclr,russellhadley/coreclr,hseok-oh/coreclr,ruben-ayrapetyan/coreclr,kyulee1/coreclr,parjong/coreclr,yizhang82/coreclr,botaberg/coreclr,AlexGhiondea/coreclr,dpodder/coreclr,yizhang82/coreclr,AlexGhiondea/coreclr,kyulee1/coreclr,mmitche/coreclr,poizan42/coreclr,parjong/coreclr,wateret/coreclr,hseok-oh/coreclr,AlexGhiondea/coreclr,yizhang82/coreclr,wateret/coreclr,poizan42/coreclr,kyulee1/coreclr,poizan42/coreclr,dpodder/coreclr,cshung/coreclr,AlexGhiondea/coreclr,krk/coreclr,rartemev/coreclr,botaberg/coreclr,AlexGhiondea/coreclr,AlexGhiondea/coreclr,wtgodbe/coreclr,russellhadley/coreclr,dpodder/coreclr,wateret/coreclr,poizan42/coreclr,parjong/coreclr,wateret/coreclr,russellhadley/coreclr,ruben-ayrapetyan/coreclr,wtgodbe/coreclr,yizhang82/coreclr,JonHanna/coreclr,botaberg/coreclr,wateret/coreclr,wtgodbe/coreclr,poizan42/coreclr,cshung/coreclr,wtgodbe/coreclr,JonHanna/coreclr,dpodder/coreclr,JonHanna/coreclr,krk/coreclr,krk/coreclr,krk/coreclr,dpodder/coreclr,mmitche/coreclr,hseok-oh/coreclr,wtgodbe/coreclr,rartemev/coreclr,kyulee1/coreclr,cshung/coreclr,dpodder/coreclr,parjong/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,rartemev/coreclr,wateret/coreclr,botaberg/coreclr,parjong/coreclr,poizan42/coreclr,ruben-ayrapetyan/coreclr,JosephTremoulet/coreclr,botaberg/coreclr,hseok-oh/coreclr,wtgodbe/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,JonHanna/coreclr,botaberg/coreclr,yizhang82/coreclr,rartemev/coreclr,russellhadley/coreclr,JonHanna/coreclr,mmitche/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,kyulee1/coreclr,JosephTremoulet/coreclr,yizhang82/coreclr,rartemev/coreclr,rartemev/coreclr,hseok-oh/coreclr,kyulee1/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,JosephTremoulet/coreclr,cshung/coreclr,JonHanna/coreclr,hseok-oh/coreclr,cshung/coreclr,parjong/coreclr,krk/coreclr,russellhadley/coreclr,krk/coreclr | src/mscorlib/shared/System/IO/FileStream.WinRT.cs | src/mscorlib/shared/System/IO/FileStream.WinRT.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 Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
namespace System.IO
{
public partial class FileStream : Stream
{
private unsafe SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
int access =
((_access & FileAccess.Read) == FileAccess.Read ? GENERIC_READ : 0) |
((_access & FileAccess.Write) == FileAccess.Write ? GENERIC_WRITE : 0);
// Our Inheritable bit was stolen from Windows, but should be set in
// the security attributes class. Don't leave this bit set.
share &= ~FileShare.Inheritable;
// Must use a valid Win32 constant here...
if (mode == FileMode.Append)
mode = FileMode.OpenOrCreate;
Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS parameters = new Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS();
parameters.dwSize = (uint)sizeof(Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS);
parameters.dwFileFlags = (uint)options;
parameters.lpSecurityAttributes = &secAttrs;
using (DisableMediaInsertionPrompt.Create())
{
return ValidateFileHandle(Interop.Kernel32.CreateFile2(
lpFileName: _path,
dwDesiredAccess: access,
dwShareMode: share,
dwCreationDisposition: mode,
pCreateExParams: ref parameters));
}
}
}
}
| // 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 Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
namespace System.IO
{
public partial class FileStream : Stream
{
#if !CORECLR
private unsafe SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
{
return CreateFile2OpenHandle(mode, share, options);
}
#endif
private unsafe SafeFileHandle CreateFile2OpenHandle(FileMode mode, FileShare share, FileOptions options)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
int access =
((_access & FileAccess.Read) == FileAccess.Read ? GENERIC_READ : 0) |
((_access & FileAccess.Write) == FileAccess.Write ? GENERIC_WRITE : 0);
// Our Inheritable bit was stolen from Windows, but should be set in
// the security attributes class. Don't leave this bit set.
share &= ~FileShare.Inheritable;
// Must use a valid Win32 constant here...
if (mode == FileMode.Append)
mode = FileMode.OpenOrCreate;
Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS parameters = new Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS();
parameters.dwSize = (uint)sizeof(Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS);
parameters.dwFileFlags = (uint)options;
parameters.lpSecurityAttributes = &secAttrs;
using (DisableMediaInsertionPrompt.Create())
{
return ValidateFileHandle(Interop.FileApiInterop.CreateFile2(
lpFileName: _path,
dwDesiredAccess: access,
dwShareMode: share,
dwCreationDisposition: mode,
pCreateExParams: ref parameters));
}
}
}
}
| mit | C# |
1d651dcf24ffe0b4cad1bf6257248c8fd992bee7 | Add delay for ReloadActiveScene to prevent stuck button | antila/castle-game-jam-2016 | Assets/ReloadScene.cs | Assets/ReloadScene.cs | using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class ReloadScene : MonoBehaviour {
GlobalControl globalController;
bool allowLevelLoad = true;
void OnEnable()
{
allowLevelLoad = true;
}
// Use this for initialization
public void ReloadActiveScene () {
if (allowLevelLoad)
{
allowLevelLoad = false;
Invoke("LoadScene", 0.33f);
}
}
private void LoadScene()
{
globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl));
globalController.globalMultiplayerManager.gameObject.SetActive(true);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
| using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class ReloadScene : MonoBehaviour {
GlobalControl globalController;
bool allowLevelLoad = true;
void OnEnable()
{
allowLevelLoad = true;
}
// Use this for initialization
public void ReloadActiveScene () {
if (allowLevelLoad)
{
allowLevelLoad = false;
globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl));
globalController.globalMultiplayerManager.gameObject.SetActive(true);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
| mit | C# |
9462d719ccb6787a96a83bd588eecdc6ac27bd15 | bump version | Fody/Equals | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fody.Equals")]
[assembly: AssemblyProduct("Fody.Equals")]
[assembly: AssemblyVersion("1.4.6")]
[assembly: AssemblyFileVersion("1.4.6")]
| using System.Reflection;
[assembly: AssemblyTitle("Fody.Equals")]
[assembly: AssemblyProduct("Fody.Equals")]
[assembly: AssemblyVersion("1.4.5")]
[assembly: AssemblyFileVersion("1.4.5")]
| mit | C# |
17c285224784ec1e358881a1ba0255b9d79ac0ce | Bump version number | ehelse/Helsenorge.Messaging,chriscena/Helsenorge.Messaging | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Direktoratet for e-helse")]
[assembly: AssemblyProduct("Helsenorge.Messaging")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: CLSCompliant(false)]
| using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Direktoratet for e-helse")]
[assembly: AssemblyProduct("Helsenorge.Messaging")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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)]
// 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.25.0")]
[assembly: AssemblyFileVersion("1.0.25.0")]
[assembly: CLSCompliant(false)]
| mit | C# |
b8723ae27385d3141ab7916749886699cfe15f0a | Revert "fix body" | darrenkopp/SassyStudio | SassyStudio.Compiler/Parsing/ControlDirectiveBody.cs | SassyStudio.Compiler/Parsing/ControlDirectiveBody.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SassyStudio.Compiler.Parsing
{
public class ControlDirectiveBody : RuleBlock
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SassyStudio.Compiler.Parsing
{
public class ControlDirectiveBody : BlockItem
{
}
}
| mit | C# |
dc794a1ca3d98ea366ff13d1f0970d52a93bee73 | bump version | Fody/Obsolete | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Obsolete")]
[assembly: AssemblyProduct("Obsolete")]
[assembly: AssemblyVersion("3.0.1")]
[assembly: AssemblyFileVersion("3.0.1")]
| using System.Reflection;
[assembly: AssemblyTitle("Obsolete")]
[assembly: AssemblyProduct("Obsolete")]
[assembly: AssemblyVersion("3.0.0")]
[assembly: AssemblyFileVersion("3.0.0")]
| mit | C# |
95e654a1017e8c88dfb3fc0e306d71cdc8942924 | Increment version to 0.1.0.7. | rhythmagency/formulate,rhythmagency/formulate,rhythmagency/formulate | src/formulate.meta/Constants.cs | src/formulate.meta/Constants.cs | namespace formulate.meta
{
/// <summary>
/// Constants relating to Formulate itself (i.e., does not
/// include constants used by Formulate).
/// </summary>
public class Constants
{
/// <summary>
/// This is the version of Formulate. It is used on
/// assemblies and during the creation of the
/// installer package.
/// </summary>
/// <remarks>
/// Do not reformat this code. A grunt task reads this
/// version number with a regular expression.
/// </remarks>
public const string Version = "0.1.0.7";
/// <summary>
/// The name of the Formulate package.
/// </summary>
public const string PackageName = "Formulate";
/// <summary>
/// The name of the Formulate package, in camel case.
/// </summary>
public const string PackageNameCamelCase = "formulate";
}
} | namespace formulate.meta
{
/// <summary>
/// Constants relating to Formulate itself (i.e., does not
/// include constants used by Formulate).
/// </summary>
public class Constants
{
/// <summary>
/// This is the version of Formulate. It is used on
/// assemblies and during the creation of the
/// installer package.
/// </summary>
/// <remarks>
/// Do not reformat this code. A grunt task reads this
/// version number with a regular expression.
/// </remarks>
public const string Version = "0.1.0.6";
/// <summary>
/// The name of the Formulate package.
/// </summary>
public const string PackageName = "Formulate";
/// <summary>
/// The name of the Formulate package, in camel case.
/// </summary>
public const string PackageNameCamelCase = "formulate";
}
} | mit | C# |
5c13997e8552a9a67043f1f4f6be9752e4bf6ec3 | Use the options when connecting to GitHub | rprouse/GetChanges | GetChanges/Program.cs | GetChanges/Program.cs | using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
Console.WriteLine(options.GetUsage());
return -1;
}
AsyncContext.Run(() => MainAsync(options));
Console.WriteLine("*** Press ENTER to Exit ***");
Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetAllMilestones();
var issues = await github.GetClosedIssues();
var noMilestoneIssues = from i in issues where i.Milestone == null select i;
DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues);
foreach (var milestone in milestones)
{
var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i;
DisplayIssuesForMilestone(milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title);
}
Console.WriteLine();
}
}
}
| using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
Console.WriteLine(options.GetUsage());
return -1;
}
AsyncContext.Run(() => MainAsync(options));
Console.WriteLine("*** Press ENTER to Exit ***");
Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi("nunit", "nunit");
var milestones = await github.GetAllMilestones();
var issues = await github.GetClosedIssues();
var noMilestoneIssues = from i in issues where i.Milestone == null select i;
DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues);
foreach (var milestone in milestones)
{
var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i;
DisplayIssuesForMilestone(milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title);
}
Console.WriteLine();
}
}
}
| mit | C# |
d993515add947a6fc3fe98fadc5204571c30288c | Update year | NRules/NRules | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("NRules")]
[assembly: AssemblyCopyright("Copyright 2012-2021 Sergiy Nikolayev. All rights reserved.")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.0.0.0")]
| using System.Reflection;
[assembly: AssemblyCompany("NRules")]
[assembly: AssemblyCopyright("Copyright 2012-2020 Sergiy Nikolayev. All rights reserved.")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.0.0.0")]
| mit | C# |
177533cb36313e64f695e8c76fbb407e5dd8ec45 | Kill commented code | another-guy/CSharpToTypeScript,another-guy/CSharpToTypeScript | TsModelGen/Program.cs | TsModelGen/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using TsModelGen.Core;
using TsModelGen.Core.TypeTranslationContext;
namespace TsModelGen
{
public class Program
{
public static void Main(string[] args)
{
// TODO Move this to input parameters
// TODO Translate into a list of namespaces, types, rules on types (such as
var targetNameSpace = "TsModelGen.TargetNamespace";
var targetNamespaces = new[] { targetNameSpace }; // TODO Make a parameter
var rootTranslationTargetTypes = RootTargetTypes.LocateFrom(targetNamespaces).ToList();
var translationContext = new TranslationContextBuilder().Build(rootTranslationTargetTypes);
var generatedCode = translationContext
.OrderedTargetTypes
.Select(targetType =>
translationContext
.First(typeTranslationContext => typeTranslationContext.CanProcess(targetType.AsType()))
.Process(targetType.AsType())
.Definition
)
.Where(definition => string.IsNullOrWhiteSpace(definition) == false)
.Aggregate((accumulated, typeDefinition) => accumulated + "\n\n" + typeDefinition);
Console.WriteLine(generatedCode);
Console.ReadKey();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using TsModelGen.Core;
using TsModelGen.Core.TypeTranslationContext;
namespace TsModelGen
{
public class Program
{
public static void Main(string[] args)
{
// TODO Move this to input parameters
// TODO Translate into a list of namespaces, types, rules on types (such as
var targetNameSpace = "TsModelGen.TargetNamespace";
var targetNamespaces = new[] { targetNameSpace }; // TODO Make a parameter
var rootTranslationTargetTypes = RootTargetTypes.LocateFrom(targetNamespaces).ToList();
var translationContext = new TranslationContextBuilder().Build(rootTranslationTargetTypes);
var generatedCode =
//rootTranslationTargetTypes
//.Union(
// translationContext
// .OfType<RegularTypeTranslationContext>()
// .Select(typeTranslationContext => typeTranslationContext.TypeInfo)
//)
translationContext
.OrderedTargetTypes
.Select(targetType =>
translationContext
.First(typeTranslationContext => typeTranslationContext.CanProcess(targetType.AsType()))
.Process(targetType.AsType())
.Definition
)
.Where(definition => string.IsNullOrWhiteSpace(definition) == false)
.Aggregate((accumulated, typeDefinition) => accumulated + "\n\n" + typeDefinition);
Console.WriteLine(generatedCode);
Console.ReadKey();
}
}
} | mit | C# |
b2899529c38a280ef6806ae899f6f5fcb0a3114a | fix build | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Server/User.cshtml | BTCPayServer/Views/Server/User.cshtml | @model UsersViewModel.UserViewModel
@{
ViewData.SetActivePageAndTitle(ServerNavPages.Users);
}
<h4>Modify User - @Model.Email</h4>
<partial name="_StatusMessage" />
<div class="row">
<div class="col-md-8">
<form method="post">
<div class="form-group">
<div class="form-check">
<input asp-for="IsAdmin" type="checkbox" class="form-check-input" />
<label asp-for="IsAdmin" class="form-check-label"></label>
</div>
</div>
<button name="command" type="submit" class="btn btn-primary" value="Save">Save</button>
</form>
</div>
</div>
| @model UserViewModel
@{
ViewData.SetActivePageAndTitle(ServerNavPages.Users);
}
<h4>Modify User - @Model.Email</h4>
<partial name="_StatusMessage" />
<div class="row">
<div class="col-md-8">
<form method="post">
<div class="form-group">
<div class="form-check">
<input asp-for="IsAdmin" type="checkbox" class="form-check-input" />
<label asp-for="IsAdmin" class="form-check-label"></label>
</div>
</div>
<button name="command" type="submit" class="btn btn-primary" value="Save">Save</button>
</form>
</div>
</div>
| mit | C# |
f35d1c17e07e080a1804a510c2749c10cb82e631 | Allow setting grouping hash and context | bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet | src/Bugsnag/Report/Event.cs | src/Bugsnag/Report/Event.cs | using System.Collections.Generic;
using System.Linq;
namespace Bugsnag
{
public class Event : Dictionary<string, object>
{
public Event(IConfiguration configuration, System.Exception exception, Severity severity)
{
this["payloadVersion"] = 4;
this["exceptions"] = new Exceptions(exception).ToArray();
this["app"] = new App(configuration);
switch (severity)
{
case Severity.Info:
this["severity"] = "info";
break;
case Severity.Warning:
this["severity"] = "warning";
break;
default:
this["severity"] = "error";
break;
}
}
public Exception[] Exceptions
{
get { return this["exceptions"] as Exception[]; }
set { this.AddToPayload("exceptions", value); }
}
public string Context
{
get { return this["context"] as string; }
set { this.AddToPayload("context", value); }
}
public string GroupingHash
{
get { return this["groupingHash"] as string; }
set { this.AddToPayload("groupingHash", value); }
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace Bugsnag
{
public class Event : Dictionary<string, object>
{
public Event(IConfiguration configuration, System.Exception exception, Severity severity)
{
this["payloadVersion"] = 2;
this["exceptions"] = new Exceptions(exception).ToArray();
this["app"] = new App(configuration);
switch (severity)
{
case Severity.Info:
this["severity"] = "info";
break;
case Severity.Warning:
this["severity"] = "warning";
break;
default:
this["severity"] = "error";
break;
}
}
public Exception[] Exceptions
{
get { return this["exceptions"] as Exception[]; }
set { this.AddToPayload("exceptions", value); }
}
}
}
| mit | C# |
32c43c6eaeb408eb8b47877b2caa4d6ffcd9cb69 | Improve object cache | axelheer/nein-linq,BenJenkinson/nein-linq | src/NeinLinq/ObjectCache.cs | src/NeinLinq/ObjectCache.cs | using System;
using System.Collections.Generic;
using System.Threading;
namespace NeinLinq
{
sealed class ObjectCache<TKey, TValue> : IDisposable
{
readonly Dictionary<TKey, TValue> cache = new Dictionary<TKey, TValue>();
readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
var value = default(TValue);
cacheLock.EnterReadLock();
try
{
if (cache.TryGetValue(key, out value))
return value;
}
finally
{
cacheLock.ExitReadLock();
}
cacheLock.EnterWriteLock();
try
{
if (cache.TryGetValue(key, out value))
return value;
value = valueFactory(key);
cache.Add(key, value);
return value;
}
finally
{
cacheLock.ExitWriteLock();
}
}
public void Dispose()
{
cacheLock.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
namespace NeinLinq
{
sealed class ObjectCache<TKey, TValue> : IDisposable
{
readonly Dictionary<TKey, TValue> cache = new Dictionary<TKey, TValue>();
readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
cacheLock.EnterUpgradeableReadLock();
try
{
var value = default(TValue);
if (cache.TryGetValue(key, out value))
return value;
cacheLock.EnterWriteLock();
try
{
value = valueFactory(key);
cache.Add(key, value);
return value;
}
finally
{
cacheLock.ExitWriteLock();
}
}
finally
{
cacheLock.ExitUpgradeableReadLock();
}
}
public void Dispose()
{
cacheLock.Dispose();
}
}
}
| mit | C# |
107062b190a9a042905e7f141b0a23a1b4ed78c5 | Improve search | leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | JoinRpg.Services.Impl/Search/UserSearchProvider.cs | JoinRpg.Services.Impl/Search/UserSearchProvider.cs | using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using JoinRpg.Data.Write.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Services.Interfaces.Search;
namespace JoinRpg.Services.Impl.Search
{
internal class UserSearchProvider : ISearchProvider
{
public IUnitOfWork UnitOfWork { private get; set; }
public async Task<IReadOnlyCollection<ISearchResult>> SearchAsync(string searchString)
{
var results =
await
UnitOfWork.GetDbSet<User>()
.Where(user =>
//TODO There should be magic way to do this. Experiment with Expression.Voodoo
user.Email.Contains(searchString)
|| user.FatherName.Contains(searchString)
|| user.BornName.Contains(searchString)
|| user.SurName.Contains(searchString)
|| user.PrefferedName.Contains(searchString)
|| (user.Extra != null && user.Extra.Nicknames != null && user.Extra.Nicknames.Contains(searchString))
)
.ToListAsync();
return results.Select(user => new SearchResultImpl
{
LinkType = LinkType.ResultUser,
Name = user.DisplayName,
Description = "",
Identification = user.UserId.ToString(),
ProjectId = null //Users not associated with any project
}).ToList();
}
}
} | using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using JoinRpg.Data.Write.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Services.Interfaces.Search;
namespace JoinRpg.Services.Impl.Search
{
internal class UserSearchProvider : ISearchProvider
{
public IUnitOfWork UnitOfWork { private get; set; }
public async Task<IReadOnlyCollection<ISearchResult>> SearchAsync(string searchString)
{
var results =
await
UnitOfWork.GetDbSet<User>()
.Where(user =>
//TODO There should be magic way to do this. Experiment with Expression.Voodoo
user.Email.Contains(searchString)
|| user.FatherName.Contains(searchString)
|| user.BornName.Contains(searchString)
|| user.SurName.Contains(searchString)
)
.ToListAsync();
return results.Select(user => new SearchResultImpl
{
LinkType = LinkType.ResultUser,
Name = user.DisplayName,
Description = "",
Identification = user.UserId.ToString(),
ProjectId = null //Users not associated with any project
}).ToList();
}
}
} | mit | C# |
2a2637e47e564d2f8052affe1683a4d6cd26559f | Add Visible to the Device DTO | nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner | MultiMiner.Remoting.Server/Data/Transfer/Device.cs | MultiMiner.Remoting.Server/Data/Transfer/Device.cs | using MultiMiner.Engine;
using MultiMiner.Xgminer;
using System;
using System.Collections.Generic;
namespace MultiMiner.Remoting.Server.Data.Transfer
{
public class Device : DeviceDescriptor
{
public Device()
{
Workers = new List<Device>();
}
//device info
public bool Enabled { get; set; }
public string Name { get; set; }
public DevicePlatform Platform { get; set; }
public int ProcessorCount { get; set; }
//coin info
public CryptoCoin Coin { get; set; }
public double Difficulty { get; set; }
public double Price { get; set; }
public double Profitability { get; set; }
public double AdjustedProfitability { get; set; }
public double AverageProfitability { get; set; }
//calculated
public string Pool { get; set; }
public double Exchange { get; set; }
public double EffectiveHashRate { get; set; }
//device stats
public double Temperature { get; set; }
public int FanPercent { get; set; }
public double AverageHashrate { get; set; }
public double CurrentHashrate { get; set; }
public int AcceptedShares { get; set; }
public int RejectedShares { get; set; }
public int HardwareErrors { get; set; }
public double Utility { get; set; }
public double WorkUtility { get; set; }
public string Intensity { get; set; } //string, might be D
public int PoolIndex { get; set; }
public double RejectedSharesPercent { get; set; }
public double HardwareErrorsPercent { get; set; }
//pool info
public double LastShareDifficulty { get; set; }
public DateTime? LastShareTime { get; set; }
public string Url { get; set; }
public int BestShare { get; set; }
public double PoolStalePercent { get; set; }
//worker info
public string WorkerName { get; set; }
public int Index { get; set; }
public List<Device> Workers { get; set; }
//ViewModel specific
public bool Visible { get; set; }
}
}
| using MultiMiner.Engine;
using MultiMiner.Xgminer;
using System;
using System.Collections.Generic;
namespace MultiMiner.Remoting.Server.Data.Transfer
{
public class Device : DeviceDescriptor
{
public Device()
{
Workers = new List<Device>();
}
//device info
public bool Enabled { get; set; }
public string Name { get; set; }
public DevicePlatform Platform { get; set; }
public int ProcessorCount { get; set; }
//coin info
public CryptoCoin Coin { get; set; }
public double Difficulty { get; set; }
public double Price { get; set; }
public double Profitability { get; set; }
public double AdjustedProfitability { get; set; }
public double AverageProfitability { get; set; }
//calculated
public string Pool { get; set; }
public double Exchange { get; set; }
public double EffectiveHashRate { get; set; }
//device stats
public double Temperature { get; set; }
public int FanPercent { get; set; }
public double AverageHashrate { get; set; }
public double CurrentHashrate { get; set; }
public int AcceptedShares { get; set; }
public int RejectedShares { get; set; }
public int HardwareErrors { get; set; }
public double Utility { get; set; }
public double WorkUtility { get; set; }
public string Intensity { get; set; } //string, might be D
public int PoolIndex { get; set; }
public double RejectedSharesPercent { get; set; }
public double HardwareErrorsPercent { get; set; }
//pool info
public double LastShareDifficulty { get; set; }
public DateTime? LastShareTime { get; set; }
public string Url { get; set; }
public int BestShare { get; set; }
public double PoolStalePercent { get; set; }
//worker info
public string WorkerName { get; set; }
public int Index { get; set; }
public List<Device> Workers { get; set; }
}
}
| mit | C# |
bb17076952ebe3f392da53f12852f4e4dd8415b7 | Change TimeZoneOffset to use double instead of int. Closes #6. | jcheng31/DarkSkyApi,jcheng31/ForecastPCL | ForecastPCL/Models/Forecast.cs | ForecastPCL/Models/Forecast.cs | namespace ForecastIOPortable.Models
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// A forecast for a particular location.
/// Models the response returned by the service.
/// </summary>
[DataContract]
public class Forecast
{
/// <summary>
/// Gets or sets the latitude of this forecast.
/// </summary>
[DataMember(Name = "latitude")]
public float Latitude { get; set; }
/// <summary>
/// Gets or sets the longitude of this forecast.
/// </summary>
[DataMember(Name = "longitude")]
public float Longitude { get; set; }
/// <summary>
/// Gets or sets the IANA time zone name for this location.
/// </summary>
[DataMember(Name = "timezone")]
public string TimeZone { get; set; }
/// <summary>
/// Gets or sets the time zone offset, in hours from GMT.
/// </summary>
[DataMember(Name = "offset")]
public double TimeZoneOffset { get; set; }
/// <summary>
/// Gets or sets the current conditions at the requested location.
/// </summary>
[DataMember(Name = "currently")]
public CurrentDataPoint Currently { get; set; }
/// <summary>
/// Gets or sets the minute-by-minute conditions for the next hour.
/// </summary>
[DataMember(Name = "minutely")]
public MinutelyForecast Minutely { get; set; }
/// <summary>
/// Gets or sets the hour-by-hour conditions for the next two days.
/// </summary>
[DataMember(Name = "hourly")]
public HourlyForecast Hourly { get; set; }
/// <summary>
/// Gets or sets the daily conditions for the next week.
/// </summary>
[DataMember(Name = "daily")]
public DailyForecast Daily { get; set; }
/// <summary>
/// Gets or sets the metadata (flags) associated with this forecast.
/// </summary>
[DataMember(Name = "flags")]
public Flags Flags { get; set; }
/// <summary>
/// Gets or sets any weather alerts related to this location.
/// </summary>
[DataMember(Name = "alerts")]
public IList<Alert> Alerts { get; set; }
}
}
| namespace ForecastIOPortable.Models
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// A forecast for a particular location.
/// Models the response returned by the service.
/// </summary>
[DataContract]
public class Forecast
{
/// <summary>
/// Gets or sets the latitude of this forecast.
/// </summary>
[DataMember(Name = "latitude")]
public float Latitude { get; set; }
/// <summary>
/// Gets or sets the longitude of this forecast.
/// </summary>
[DataMember(Name = "longitude")]
public float Longitude { get; set; }
/// <summary>
/// Gets or sets the IANA time zone name for this location.
/// </summary>
[DataMember(Name = "timezone")]
public string TimeZone { get; set; }
/// <summary>
/// Gets or sets the time zone offset, in hours from GMT.
/// </summary>
[DataMember(Name = "offset")]
public int TimeZoneOffset { get; set; }
/// <summary>
/// Gets or sets the current conditions at the requested location.
/// </summary>
[DataMember(Name = "currently")]
public CurrentDataPoint Currently { get; set; }
/// <summary>
/// Gets or sets the minute-by-minute conditions for the next hour.
/// </summary>
[DataMember(Name = "minutely")]
public MinutelyForecast Minutely { get; set; }
/// <summary>
/// Gets or sets the hour-by-hour conditions for the next two days.
/// </summary>
[DataMember(Name = "hourly")]
public HourlyForecast Hourly { get; set; }
/// <summary>
/// Gets or sets the daily conditions for the next week.
/// </summary>
[DataMember(Name = "daily")]
public DailyForecast Daily { get; set; }
/// <summary>
/// Gets or sets the metadata (flags) associated with this forecast.
/// </summary>
[DataMember(Name = "flags")]
public Flags Flags { get; set; }
/// <summary>
/// Gets or sets any weather alerts related to this location.
/// </summary>
[DataMember(Name = "alerts")]
public IList<Alert> Alerts { get; set; }
}
}
| mit | C# |
15be5a69d8a8e87cf2dac63798e38f7061aa2f12 | undo my "fix" - it broke stuff that we are not testing. | hig-ag/CocosSharp,mono/cocos2d-xna,TukekeSoft/CocosSharp,netonjm/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,mono/cocos2d-xna,TukekeSoft/CocosSharp,mono/CocosSharp,mono/CocosSharp,haithemaraissia/CocosSharp,zmaruo/CocosSharp,zmaruo/CocosSharp,MSylvia/CocosSharp,hig-ag/CocosSharp,netonjm/CocosSharp | cocos2d/actions/action_intervals/CCTargetedAction.cs | cocos2d/actions/action_intervals/CCTargetedAction.cs | namespace Cocos2D
{
public class CCTargetedAction : CCActionInterval
{
protected CCFiniteTimeAction m_pAction;
protected CCNode m_pForcedTarget;
public CCNode ForcedTarget
{
get { return m_pForcedTarget; }
}
public CCTargetedAction(CCNode target, CCFiniteTimeAction pAction)
{
InitWithTarget(target, pAction);
}
public CCTargetedAction(CCTargetedAction targetedAction) : base(targetedAction)
{
InitWithTarget(targetedAction.m_pForcedTarget, (CCFiniteTimeAction) targetedAction.m_pAction.Copy());
}
protected bool InitWithTarget(CCNode target, CCFiniteTimeAction pAction)
{
if (base.InitWithDuration(pAction.Duration))
{
m_pForcedTarget = target;
m_pAction = pAction;
return true;
}
return false;
}
public override object Copy(ICCCopyable pZone)
{
if (pZone != null) //in case of being called at sub class
{
var pRet = (CCTargetedAction) (pZone);
base.Copy(pZone);
// win32 : use the m_pOther's copy object.
pRet.InitWithTarget(m_pForcedTarget, (CCFiniteTimeAction) m_pAction.Copy());
return pRet;
}
return new CCTargetedAction(this);
}
public override void StartWithTarget(CCNode target)
{
base.StartWithTarget(target);
m_pAction.StartWithTarget(m_pForcedTarget);
}
public override void Stop()
{
m_pAction.Stop();
}
public override void Update(float time)
{
m_pAction.Update(time);
}
public override CCFiniteTimeAction Reverse()
{
return new CCTargetedAction(m_pForcedTarget, m_pAction.Reverse());
}
}
} | namespace Cocos2D
{
public class CCTargetedAction : CCActionInterval
{
protected CCFiniteTimeAction m_pAction;
protected CCNode m_pForcedTarget;
public CCNode ForcedTarget
{
get { return m_pForcedTarget; }
}
public CCTargetedAction(CCNode target, CCFiniteTimeAction pAction)
{
InitWithTarget(target, pAction);
}
public CCTargetedAction(CCTargetedAction targetedAction) : base(targetedAction)
{
InitWithTarget(targetedAction.m_pForcedTarget, (CCFiniteTimeAction) targetedAction.m_pAction.Copy());
}
protected bool InitWithTarget(CCNode target, CCFiniteTimeAction pAction)
{
if (base.InitWithDuration(pAction.Duration))
{
m_pForcedTarget = target;
m_pAction = pAction;
return true;
}
return false;
}
public override object Copy(ICCCopyable pZone)
{
if (pZone != null) //in case of being called at sub class
{
var pRet = (CCTargetedAction) (pZone);
base.Copy(pZone);
// win32 : use the m_pOther's copy object.
pRet.InitWithTarget(m_pForcedTarget, (CCFiniteTimeAction) m_pAction.Copy());
return pRet;
}
return new CCTargetedAction(this);
}
public override void StartWithTarget(CCNode target)
{
base.StartWithTarget(target);
m_pForcedTarget = target;
m_pAction.StartWithTarget(m_pForcedTarget);
}
public override void Stop()
{
m_pAction.Stop();
}
public override void Update(float time)
{
m_pAction.Update(time);
}
public override CCFiniteTimeAction Reverse()
{
return new CCTargetedAction(m_pForcedTarget, m_pAction.Reverse());
}
}
} | mit | C# |
a62b4e2f7dc55ccad6997082b2e327844ad8bcac | Bump to v1.5 | CryptonZylog/carbonator,lhoworko/carbonator | Carbonator/Properties/AssemblyInfo.cs | Carbonator/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("Carbonator")]
[assembly: AssemblyDescription("Collects performance counter metrics and reports them to Graphite/Carbon server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Carbonator")]
[assembly: AssemblyCopyright("Copyright © Crypton Technologies 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a92aff8a-bbd6-4d7d-8ba2-4d4b1c7c2f33")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.*")]
[assembly: AssemblyFileVersion("1.5.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("Carbonator")]
[assembly: AssemblyDescription("Collects performance counter metrics and reports them to Graphite/Carbon server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Carbonator")]
[assembly: AssemblyCopyright("Copyright © Crypton Technologies 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a92aff8a-bbd6-4d7d-8ba2-4d4b1c7c2f33")]
// 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.4.*")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| mit | C# |
d275787f174c4249077fc02f42c04fd56195fdf8 | optimize Problem 1 | arbing/ProjectEuler | ProjectEuler/Problems/No001.cs | ProjectEuler/Problems/No001.cs | using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using ProjectEuler.Attributes;
namespace ProjectEuler.Problems
{
[Title("Multiples of 3 and 5")]
[Description(@"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.")]
[Answer(233168)]
public class No001
{
public long Run(long n = 1000)
{
return SumDivisibleBy(n - 1, 3) + SumDivisibleBy(n - 1, 5) - SumDivisibleBy(n - 1, 3 * 5);
}
public long SumDivisibleBy(long max, long n)
{
var p = max / n;
return n * (p * (p + 1)) / 2;
}
public long Run1(long n = 1000000)
{
return LongRangeIterator(1, (int)n - 1)
.Where(i => i % 3 == 0 || i % 5 == 0)
.Sum();
}
private static IEnumerable<long> LongRangeIterator(long start, long count)
{
for (long i = 0; i < count; ++i)
yield return start + i;
}
}
}
| using System.ComponentModel;
using System.Linq;
using ProjectEuler.Attributes;
namespace ProjectEuler.Problems
{
[Title("Multiples of 3 and 5")]
[Description(@"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.")]
[Answer(233168)]
public class No001
{
public long Run(long n = 1000)
{
return Enumerable.Range(1, (int)n - 1)
.Where(i => i % 3 == 0 || i % 5 == 0)
.Sum();
}
}
}
| mit | C# |
884dfd83ac1ac991cf442f61f6bd8f594f6d6e90 | Remove untested branch from PEFileCollection. | ethanmoffat/EndlessClient | EOLib.Graphics/PEFileCollection.cs | EOLib.Graphics/PEFileCollection.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using System.IO;
using PELoaderLib;
namespace EOLib.Graphics
{
public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
{
public void PopulateCollectionWithStandardGFX()
{
var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes));
foreach (var type in gfxTypes)
Add(type, CreateGFXFile(type));
}
private IPEFile CreateGFXFile(GFXTypes file)
{
var number = ((int)file).ToString("D3");
var fName = Path.Combine("gfx", "gfx" + number + ".egf");
return new PEFile(fName);
}
public void Dispose()
{
foreach (var pair in this)
pair.Value.Dispose();
}
}
public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
{
void PopulateCollectionWithStandardGFX();
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using System.IO;
using PELoaderLib;
namespace EOLib.Graphics
{
public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
{
public void PopulateCollectionWithStandardGFX()
{
var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes));
foreach (var type in gfxTypes)
Add(type, CreateGFXFile(type));
}
private IPEFile CreateGFXFile(GFXTypes file)
{
var number = ((int)file).ToString("D3");
var fName = Path.Combine("gfx", "gfx" + number + ".egf");
return new PEFile(fName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!disposing)
return;
foreach (var pair in this)
pair.Value.Dispose();
}
}
public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
{
void PopulateCollectionWithStandardGFX();
}
}
| mit | C# |
bf84a0c4293b6f3c7c8391fed2f40b717c8fc077 | Update version to 2.3.0 | TheOtherTimDuncan/TOTD | SharedAssemblyInfo.cs | SharedAssemblyInfo.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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("2.3.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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
| mit | C# |
e655701af7de495a28c2eb54a138a4ed9048d4c1 | Bump version | roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon | R7.Epsilon/Properties/SolutionInfo.cs | R7.Epsilon/Properties/SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany ("R7.Labs")]
[assembly: AssemblyProduct ("R7.Epsilon")]
[assembly: AssemblyCopyright ("Roman M. Yagodin")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyVersion ("2.4.0")]
[assembly: AssemblyInformationalVersion ("2.4.0")]
| using System.Reflection;
[assembly: AssemblyCompany ("R7.Labs")]
[assembly: AssemblyProduct ("R7.Epsilon")]
[assembly: AssemblyCopyright ("Roman M. Yagodin")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyVersion ("2.3.2")]
[assembly: AssemblyInformationalVersion ("2.3.2")]
| agpl-3.0 | C# |
3535abdeb46a3591e6f9d1bdba5a40da4ac09073 | Update assembly version. | MatthewKing/DeviceId | src/DeviceId/Properties/AssemblyInfo.cs | src/DeviceId/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DeviceId")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeviceId")]
[assembly: AssemblyCopyright("Copyright © Matthew King 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("13803197-daeb-4ba4-8a38-7be03930f463")]
[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("2.2.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DeviceId")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeviceId")]
[assembly: AssemblyCopyright("Copyright © Matthew King 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("13803197-daeb-4ba4-8a38-7be03930f463")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
| mit | C# |
ed1fd5bb1c66959a0bb5b9764392b710f399be00 | Hide occurrence members that should be handled via Times now | RobSiklos/moq4,Moq/moq4,ocoanet/moq4,AhmedAssaf/moq4,ericschultz/Moq,LeonidLevin/moq4,cgourlay/moq4,HelloKitty/moq4,breyed/moq4,JohanLarsson/moq4,jeremymeng/moq4,chkpnt/moq4,kolomanschaft/moq4,AhmedAssaf/moq4,ramanraghur/moq4,iskiselev/moq4,kulkarnisachin07/moq4,madcapsoftware/moq4 | Source/Language/IOccurrence.cs | Source/Language/IOccurrence.cs | //Copyright (c) 2007, Moq Team
//http://code.google.com/p/moq/
//All rights reserved.
//Redistribution and use in source and binary forms,
//with or without modification, are permitted provided
//that the following conditions are met:
// * Redistributions of source code must retain the
// above copyright notice, this list of conditions and
// the following disclaimer.
// * Redistributions in binary form must reproduce
// the above copyright notice, this list of conditions
// and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the Moq Team nor the
// names of its contributors may be used to endorse
// or promote products derived from this software
// without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
//CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.
//[This is the BSD license, see
// http://www.opensource.org/licenses/bsd-license.php]
using System.ComponentModel;
namespace Moq.Language
{
/// <summary>
/// Defines occurrence members to constraint setups.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public interface IOccurrence : IHideObjectMembers
{
/// <summary>
/// The expected invocation can happen at most once.
/// </summary>
/// <example>
/// <code>
/// var mock = new Mock<ICommand>();
/// mock.Setup(foo => foo.Execute("ping"))
/// .AtMostOnce();
/// </code>
/// </example>
[EditorBrowsable(EditorBrowsableState.Never)]
IVerifies AtMostOnce();
/// <summary>
/// The expected invocation can happen at most specified number of times.
/// </summary>
/// <example>
/// <code>
/// var mock = new Mock<ICommand>();
/// mock.Setup(foo => foo.Execute("ping"))
/// .AtMost( 5 );
/// </code>
/// </example>
[EditorBrowsable(EditorBrowsableState.Never)]
IVerifies AtMost(int callCount);
}
}
| //Copyright (c) 2007, Moq Team
//http://code.google.com/p/moq/
//All rights reserved.
//Redistribution and use in source and binary forms,
//with or without modification, are permitted provided
//that the following conditions are met:
// * Redistributions of source code must retain the
// above copyright notice, this list of conditions and
// the following disclaimer.
// * Redistributions in binary form must reproduce
// the above copyright notice, this list of conditions
// and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the Moq Team nor the
// names of its contributors may be used to endorse
// or promote products derived from this software
// without specific prior written permission.
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
//CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.
//[This is the BSD license, see
// http://www.opensource.org/licenses/bsd-license.php]
using System.ComponentModel;
namespace Moq.Language
{
/// <summary>
/// Defines occurrence members to constraint setups.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public interface IOccurrence : IHideObjectMembers
{
/// <summary>
/// The expected invocation can happen at most once.
/// </summary>
/// <example>
/// <code>
/// var mock = new Mock<ICommand>();
/// mock.Setup(foo => foo.Execute("ping"))
/// .AtMostOnce();
/// </code>
/// </example>
IVerifies AtMostOnce();
/// <summary>
/// The expected invocation can happen at most specified number of times.
/// </summary>
/// <example>
/// <code>
/// var mock = new Mock<ICommand>();
/// mock.Setup(foo => foo.Execute("ping"))
/// .AtMost( 5 );
/// </code>
/// </example>
IVerifies AtMost( int callCount);
}
}
| bsd-3-clause | C# |
20a62bbfab72220f9151095726c8f2d61512bde9 | Remove some unused experiment names | bartdesmet/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,diryboy/roslyn,dotnet/roslyn,dotnet/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,eriawan/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,mavasani/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,bartdesmet/roslyn,weltkante/roslyn,KevinRansom/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,sharwell/roslyn,mavasani/roslyn,dotnet/roslyn | src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs | src/Workspaces/Core/Portable/Experiments/IExperimentationService.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.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
void EnableExperiment(string experimentName, bool value);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
public void EnableExperiment(string experimentName, bool value) { }
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string OOPCoreClr = "Roslyn.OOPCoreClr";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
}
}
| // 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.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
void EnableExperiment(string experimentName, bool value);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
public void EnableExperiment(string experimentName, bool value) { }
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string OOPCoreClr = "Roslyn.OOPCoreClr";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
}
}
| mit | C# |
d0906d8232a3a0048a2e2630b44f7a7df05dfdb0 | Adjust xmldocs to conform to TransformableExtensions. | smoogipoo/osu,NeoAdonis/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,naoey/osu,EVAST9919/osu,UselessToucan/osu,Drezi126/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,ZLima12/osu,2yangk23/osu,peppy/osu,DrabWeb/osu,naoey/osu,Frontear/osuKyzer,EVAST9919/osu,peppy/osu-new,DrabWeb/osu,peppy/osu,Nabile-Rahmani/osu,ppy/osu,johnneijzen/osu,Damnae/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,DrabWeb/osu,2yangk23/osu | osu.Game/Graphics/IHasAccentColour.cs | osu.Game/Graphics/IHasAccentColour.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Transforms;
namespace osu.Game.Graphics
{
/// <summary>
/// A type of drawable that has an accent colour.
/// The accent colour is used to colorize various objects inside a drawable
/// without colorizing the drawable itself.
/// </summary>
public interface IHasAccentColour : IDrawable
{
Color4 AccentColour { get; set; }
}
public static class AccentedColourExtensions
{
/// <summary>
/// Smoothly adjusts <see cref="IHasAccentColour.AccentColour"/> over time.
/// </summary>
/// <returns>A <see cref="TransformSequence{T}"/> to which further transforms can be added.</returns>
public static TransformSequence<T> FadeAccent<T>(this T accentedDrawable, Color4 newColour, double duration = 0, Easing easing = Easing.None)
where T : IHasAccentColour
=> accentedDrawable.TransformTo(nameof(accentedDrawable.AccentColour), newColour, duration, easing);
/// <summary>
/// Smoothly adjusts <see cref="IHasAccentColour.AccentColour"/> over time.
/// </summary>
/// <returns>A <see cref="TransformSequence{T}"/> to which further transforms can be added.</returns>
public static TransformSequence<T> FadeAccent<T>(this TransformSequence<T> t, Color4 newColour, double duration = 0, Easing easing = Easing.None)
where T : Drawable, IHasAccentColour
=> t.Append(o => o.FadeAccent(newColour, duration, easing));
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Transforms;
namespace osu.Game.Graphics
{
/// <summary>
/// A type of drawable that has an accent colour.
/// The accent colour is used to colorize various objects inside a drawable
/// without colorizing the drawable itself.
/// </summary>
public interface IHasAccentColour : IDrawable
{
Color4 AccentColour { get; set; }
}
public static class AccentedColourExtensions
{
/// <summary>
/// Tweens the accent colour of a drawable to another colour.
/// </summary>
/// <param name="accentedDrawable">The drawable to apply the accent colour to.</param>
/// <param name="newColour">The new accent colour.</param>
/// <param name="duration">The tween duration.</param>
/// <param name="easing">The tween easing.</param>
public static TransformSequence<T> FadeAccent<T>(this T accentedDrawable, Color4 newColour, double duration = 0, Easing easing = Easing.None)
where T : IHasAccentColour
=> accentedDrawable.TransformTo(nameof(accentedDrawable.AccentColour), newColour, duration, easing);
/// <summary>
/// Tweens the accent colour of a drawable to another colour.
/// </summary>
/// <param name="accentedDrawable">The drawable to apply the accent colour to.</param>
/// <param name="newColour">The new accent colour.</param>
/// <param name="duration">The tween duration.</param>
/// <param name="easing">The tween easing.</param>
public static TransformSequence<T> FadeAccent<T>(this TransformSequence<T> t, Color4 newColour, double duration = 0, Easing easing = Easing.None)
where T : Drawable, IHasAccentColour
=> t.Append(o => o.FadeAccent(newColour, duration, easing));
}
}
| mit | C# |
fcdcf0e57dca53e231228c3f8c5511260f63722d | Add ToHashSet extension methods on IEnumerable. | CamTechConsultants/CvsntGitImporter | Utils/IEnumerableExtensions.cs | Utils/IEnumerableExtensions.cs | /*
* John.Hall <john.hall@camtechconsultants.com>
* Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
namespace CTC.CvsntGitImporter.Utils
{
/// <summary>
/// Extension methods for IEnumerable.
/// </summary>
static class IEnumerableExtensions
{
/// <summary>
/// Perform the equivalent of String.Join on a sequence.
/// </summary>
/// <typeparam name="T">the type of the elements of source</typeparam>
/// <param name="source">the sequence of values to join</param>
/// <param name="separator">a string to insert between each item</param>
/// <returns>a string containing the items in the sequence concenated and separated by the separator</returns>
public static string StringJoin<T>(this IEnumerable<T> source, string separator)
{
return String.Join(separator, source);
}
/// <summary>
/// Create a HashSet from a list of items.
/// </summary>
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
/// <summary>
/// Create a HashSet from a list of items.
/// </summary>
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
return new HashSet<T>(source, comparer);
}
}
} | /*
* John.Hall <john.hall@camtechconsultants.com>
* Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
namespace CTC.CvsntGitImporter.Utils
{
/// <summary>
/// Extension methods for IEnumerable.
/// </summary>
static class IEnumerableExtensions
{
/// <summary>
/// Perform the equivalent of String.Join on a sequence.
/// </summary>
/// <typeparam name="T">the type of the elements of source</typeparam>
/// <param name="source">the sequence of values to join</param>
/// <param name="separator">a string to insert between each item</param>
/// <returns>a string containing the items in the sequence concenated and separated by the separator</returns>
public static string StringJoin<T>(this IEnumerable<T> source, string separator)
{
return String.Join(separator, source);
}
}
} | mit | C# |
3f5dcadd200c01f9798ba3ca5df788f6187a7496 | Test was simplified | litichevskiydv/GfPolynoms,litichevskiydv/GfPolynoms | test/CodesResearchTools.Tests/MinimalSphereCoveringAnalyzerTests.cs | test/CodesResearchTools.Tests/MinimalSphereCoveringAnalyzerTests.cs | namespace AppliedAlgebra.CodesResearchTools.Tests
{
using System.Collections.Generic;
using Analyzers.CodeSpaceCovering;
using CodesAbstractions;
using GfPolynoms;
using GfPolynoms.Extensions;
using GfPolynoms.GaloisFields;
using Microsoft.Extensions.Logging;
using Moq;
using NoiseGenerator;
using Xunit;
public class MinimalSphereCoveringAnalyzerTests
{
private class FakeCode : ICode
{
private readonly PrimeOrderField _gf2 = new PrimeOrderField(2);
public GaloisField Field => _gf2;
public int CodewordLength => 3;
public int InformationWordLength => 2;
public int CodeDistance => 0;
public FieldElement[] Encode(FieldElement[] informationWord)
{
return new[] { informationWord[0], informationWord[1], informationWord[0] + informationWord[1] };
}
public FieldElement[] Decode(FieldElement[] noisyCodeword)
{
return new[] { _gf2.One(), _gf2.One() };
}
public IReadOnlyList<FieldElement[]> DecodeViaList(FieldElement[] noisyCodeword, int? listDecodingRadius = null)
{
var list = new List<FieldElement[]> { new[] { noisyCodeword[0], noisyCodeword[1] } };
if (Equals(noisyCodeword[0] + noisyCodeword[1], noisyCodeword[2]) == false || listDecodingRadius == 2)
{
list.Add(new[] { noisyCodeword[0] + _gf2.One(), noisyCodeword[1] });
list.Add(new[] { noisyCodeword[0], noisyCodeword[1] + _gf2.One() });
}
if (Equals(noisyCodeword[0] + noisyCodeword[1], noisyCodeword[2]) && listDecodingRadius == 2)
list.Add(new[] { noisyCodeword[0] + _gf2.One(), noisyCodeword[1] + _gf2.One() });
return list;
}
}
private readonly Mock<ILogger<MinimalSphereCoveringAnalyzer>> _mockLogger;
private readonly MinimalSphereCoveringAnalyzer _analyzer;
public MinimalSphereCoveringAnalyzerTests()
{
_mockLogger = new Mock<ILogger<MinimalSphereCoveringAnalyzer>>();
_analyzer = new MinimalSphereCoveringAnalyzer(new RecursiveGenerator(), _mockLogger.Object);
}
[Fact]
public void ShouldAnalyzeSphereCovering()
{
// Given
var code = new FakeCode();
// When
var actualMinimalRadius = _analyzer.Analyze(code);
// Then
const int expectedMinimalRadius = 1;
Assert.Equal(expectedMinimalRadius, actualMinimalRadius);
}
}
} | namespace AppliedAlgebra.CodesResearchTools.Tests
{
using System;
using Analyzers.CodeSpaceCovering;
using GolayCodesTools;
using Microsoft.Extensions.Logging;
using Moq;
using NoiseGenerator;
using Xunit;
public class MinimalSphereCoveringAnalyzerTests
{
private readonly Mock<ILogger<MinimalSphereCoveringAnalyzer>> _mockLogger;
private readonly MinimalSphereCoveringAnalyzer _analyzer;
public MinimalSphereCoveringAnalyzerTests()
{
_mockLogger = new Mock<ILogger<MinimalSphereCoveringAnalyzer>>();
_analyzer = new MinimalSphereCoveringAnalyzer(new RecursiveGenerator(), _mockLogger.Object);
}
[Fact]
public void ShouldAnalyzeSphereCovering()
{
// Given
var g11 = new G11GolayCode();
// When
var actualMinimalRadius = _analyzer.Analyze(g11);
// Then
const int expectedMinimalRadius = 2;
Assert.Equal(expectedMinimalRadius, actualMinimalRadius);
Assert.All(_mockLogger.Invocations, x => Assert.Equal(LogLevel.Information, x.Arguments[0]));
Assert.True(_mockLogger.Invocations.Count >= 1);
}
}
} | mit | C# |
b2252893adee194b846cff74715f9008f4976c04 | remove DiscoveryClient | IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4 | test/IdentityServer.IntegrationTests/Pipeline/ConfigurationTests.cs | test/IdentityServer.IntegrationTests/Pipeline/ConfigurationTests.cs | using System;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel.Client;
using IdentityServer4.Configuration;
using IdentityServer4.IntegrationTests.Common;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace IdentityServer.IntegrationTests.Pipeline
{
public class ConfigurationTests
{
private const string Category = "Configuration Tests";
private IdentityServerPipeline _pipeline = new IdentityServerPipeline();
[Fact]
public async Task empty_origin_should_be_ignored_in_discovery_document()
{
_pipeline.OnPostConfigureServices += s=>
{
s.Configure<IdentityServerOptions>(opts=>
{
opts.PublicOrigin = string.Empty;
});
};
_pipeline.Initialize();
var client = new HttpClient(_pipeline.Handler);
var result = await client.GetDiscoveryDocumentAsync(IdentityServerPipeline.BaseUrl);
result.Issuer.Should().Be(IdentityServerPipeline.BaseUrl);
}
[Fact]
public void invalid_origin_should_throw_at_load_time()
{
_pipeline.OnPostConfigureServices += s =>
{
s.Configure<IdentityServerOptions>(opts =>
{
opts.PublicOrigin = "invalid";
});
};
Action a = () => _pipeline.Initialize();
a.Should().Throw<InvalidOperationException>();
}
}
}
| using System;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel.Client;
using IdentityServer4.Configuration;
using IdentityServer4.IntegrationTests.Common;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace IdentityServer.IntegrationTests.Pipeline
{
public class ConfigurationTests
{
private const string Category = "Configuration Tests";
private IdentityServerPipeline _pipeline = new IdentityServerPipeline();
[Fact]
public async Task empty_origin_should_be_ignored_in_discovery_document()
{
_pipeline.OnPostConfigureServices += s=>
{
s.Configure<IdentityServerOptions>(opts=>
{
opts.PublicOrigin = string.Empty;
});
};
_pipeline.Initialize();
var discoClient = new DiscoveryClient(IdentityServerPipeline.BaseUrl, _pipeline.Handler);
var result = await discoClient.GetAsync();
result.Issuer.Should().Be(IdentityServerPipeline.BaseUrl);
}
[Fact]
public void invalid_origin_should_throw_at_load_time()
{
_pipeline.OnPostConfigureServices += s =>
{
s.Configure<IdentityServerOptions>(opts =>
{
opts.PublicOrigin = "invalid";
});
};
Action a = () => _pipeline.Initialize();
a.Should().Throw<InvalidOperationException>();
}
}
}
| apache-2.0 | C# |
9ed96e8b161cbb4dbdf21062da53d2f922e7dc33 | Add missing final validation pass (bytes read == 0) | brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync | projects/CommSample/source/CommSample.App/ValidatingReceiver.cs | projects/CommSample/source/CommSample.App/ValidatingReceiver.cs | //-----------------------------------------------------------------------
// <copyright file="ValidatingReceiver.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CommSample
{
using System;
using System.Threading.Tasks;
internal sealed class ValidatingReceiver
{
private readonly Receiver receiver;
private readonly DataOracle oracle;
private byte lastSeen;
private int lastCount;
public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle)
{
this.receiver = new Receiver(channel, logger, bufferSize);
this.oracle = oracle;
this.receiver.DataReceived += this.OnDataReceived;
}
public Task<long> RunAsync()
{
return this.receiver.RunAsync();
}
private void OnDataReceived(object sender, DataEventArgs e)
{
for (int i = 0; i < e.BytesRead; ++i)
{
if (this.lastSeen != e.Buffer[i])
{
if (this.lastSeen != 0)
{
this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount);
}
this.lastSeen = e.Buffer[i];
this.lastCount = 0;
}
++this.lastCount;
}
if (e.BytesRead == 0)
{
this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount);
}
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="ValidatingReceiver.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CommSample
{
using System;
using System.Threading.Tasks;
internal sealed class ValidatingReceiver
{
private readonly Receiver receiver;
private readonly DataOracle oracle;
private byte lastSeen;
private int lastCount;
public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle)
{
this.receiver = new Receiver(channel, logger, bufferSize);
this.oracle = oracle;
this.receiver.DataReceived += this.OnDataReceived;
}
public Task<long> RunAsync()
{
return this.receiver.RunAsync();
}
private void OnDataReceived(object sender, DataEventArgs e)
{
for (int i = 0; i < e.BytesRead; ++i)
{
if (this.lastSeen != e.Buffer[i])
{
if (this.lastSeen != 0)
{
this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount);
}
this.lastSeen = e.Buffer[i];
this.lastCount = 0;
}
++this.lastCount;
}
}
}
}
| unlicense | C# |
6d7e5de6d1bf7f598c7e22004c588cdaecf90dc4 | refactor main loop for policy extraction | Pondidum/Stronk,Pondidum/Stronk | src/Stronk/ConfigBuilder.cs | src/Stronk/ConfigBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Stronk.Policies;
using Stronk.PropertySelection;
using Stronk.SourceValueSelection;
using Stronk.ValueConversion;
namespace Stronk
{
public class ConfigBuilder
{
private readonly IStronkOptions _options;
public ConfigBuilder(IStronkOptions options)
{
_options = options;
}
public void Populate(object target, IConfigurationSource configSource)
{
var valueSelectors = _options.ValueSelectors.ToArray();
var availableConverters = _options.ValueConverters.ToArray();
var properties = _options
.PropertySelectors
.SelectMany(selector => selector.Select(target.GetType()));
var args = new ValueSelectorArgs(configSource);
foreach (var property in properties)
{
var value = GetValueFromSource(valueSelectors, args.With(property));
if (value == null && _options.ErrorPolicy.OnSourceValueNotFound == PolicyActions.ThrowException)
throw new SourceValueNotFoundException(valueSelectors, property);
if (value == null)
continue;
var converters = GetValueConverters(availableConverters, property);
if (converters.Any() == false && _options.ErrorPolicy.OnConverterNotFound == PolicyActions.ThrowException)
throw new ConverterNotFoundException(availableConverters, property);
if (converters.Any() == false)
continue;
ApplyConversion(availableConverters, converters, target, property, value);
}
}
private void ApplyConversion(IValueConverter[] availableConverters, IEnumerable<IValueConverter> chosenConverters, object target, PropertyDescriptor property, string value)
{
var conversionPolicy = _options.ErrorPolicy.ConversionPolicy;
conversionPolicy.BeforeConversion();
foreach (var converter in chosenConverters)
{
var vca = new ValueConverterArgs(
availableConverters.Where(x => x != converter),
property.Type,
value
);
try
{
var converted = converter.Map(vca);
property.Assign(target, converted);
return;
}
catch (Exception ex)
{
conversionPolicy.OnConversionException(ex);
}
}
conversionPolicy.AfterConversion();
}
private static IValueConverter[] GetValueConverters(IValueConverter[] converters, PropertyDescriptor property)
{
return converters
.Where(c => c.CanMap(property.Type))
.ToArray();
}
private static string GetValueFromSource(ISourceValueSelector[] sourceValueSelectors, ValueSelectorArgs args)
{
foreach (var filter in sourceValueSelectors)
{
var value = filter.Select(args);
if (value != null)
return value;
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Stronk.Policies;
using Stronk.PropertySelection;
using Stronk.SourceValueSelection;
using Stronk.ValueConversion;
namespace Stronk
{
public class ConfigBuilder
{
private readonly IStronkOptions _options;
public ConfigBuilder(IStronkOptions options)
{
_options = options;
}
public void Populate(object target, IConfigurationSource configSource)
{
var valueSelectors = _options.ValueSelectors.ToArray();
var availableConverters = _options.ValueConverters.ToArray();
var properties = _options
.PropertySelectors
.SelectMany(selector => selector.Select(target.GetType()));
var args = new ValueSelectorArgs(configSource);
foreach (var property in properties)
{
var value = GetValueFromSource(valueSelectors, args.With(property));
if (value == null)
if (_options.ErrorPolicy.OnSourceValueNotFound == PolicyActions.ThrowException)
throw new SourceValueNotFoundException(valueSelectors, property);
else
continue;
var converters = GetValueConverters(availableConverters, property);
if (converters.Any() == false)
if (_options.ErrorPolicy.OnConverterNotFound == PolicyActions.ThrowException)
throw new ConverterNotFoundException(availableConverters, property);
else
continue;
ApplyConversion(availableConverters, converters, target, property, value);
}
}
private void ApplyConversion(IValueConverter[] availableConverters, IEnumerable<IValueConverter> chosenConverters, object target, PropertyDescriptor property, string value)
{
var conversionPolicy = _options.ErrorPolicy.ConversionPolicy;
conversionPolicy.BeforeConversion();
foreach (var converter in chosenConverters)
{
var vca = new ValueConverterArgs(
availableConverters.Where(x => x != converter),
property.Type,
value
);
try
{
var converted = converter.Map(vca);
property.Assign(target, converted);
return;
}
catch (Exception ex)
{
conversionPolicy.OnConversionException(ex);
}
}
conversionPolicy.AfterConversion();
}
private static IValueConverter[] GetValueConverters(IValueConverter[] converters, PropertyDescriptor property)
{
return converters
.Where(c => c.CanMap(property.Type))
.ToArray();
}
private static string GetValueFromSource(ISourceValueSelector[] sourceValueSelectors, ValueSelectorArgs args)
{
foreach (var filter in sourceValueSelectors)
{
var value = filter.Select(args);
if (value != null)
return value;
}
return null;
}
}
}
| lgpl-2.1 | C# |
8664b2c2ffb7ebe8a5d36dd675e5583b3b9911e0 | Change Parser more nice | occar421/OpenTKAnalyzer | src/OpenTKAnalyzer/OpenTKAnalyzer/Utility/NumericValueParser.cs | src/OpenTKAnalyzer/OpenTKAnalyzer/Utility/NumericValueParser.cs | using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace OpenTKAnalyzer.Utility
{
static public class NumericValueParser
{
static public bool TryParseFromExpression(ExpressionSyntax expression, out double result)
{
var walker = new DoubleExpressWalker();
walker.Visit(expression);
result = walker.Value ?? double.NegativeInfinity;
return walker.Value.HasValue;
}
class DoubleExpressWalker : CSharpSyntaxWalker
{
internal double? Value { get; private set; } = null;
bool isValuePositive = true;
// fail
public override void DefaultVisit(SyntaxNode node)
{
return;
}
public override void VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node)
{
switch (node.OperatorToken.ValueText)
{
case "+":
break;
case "-":
isValuePositive = !isValuePositive;
break;
default:
return;
}
base.Visit(node.Operand);
}
public override void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node)
{
base.Visit(node.Expression);
}
public override void VisitLiteralExpression(LiteralExpressionSyntax node)
{
if (node.IsKind(SyntaxKind.NumericLiteralExpression))
{
Value = (isValuePositive ? 1 : -1) * double.Parse(node.Token.ValueText);
}
}
}
}
} | using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenTKAnalyzer.Utility
{
static public class NumericValueParser
{
static public bool TryParseFromExpression(ExpressionSyntax expression, out double result)
{
var literalString = string.Empty;
if (expression is PrefixUnaryExpressionSyntax)
{
var s = expression as PrefixUnaryExpressionSyntax;
literalString = s.OperatorToken.ValueText + (s.Operand as LiteralExpressionSyntax)?.Token.ValueText;
}
else if (expression is LiteralExpressionSyntax)
{
var s = expression as LiteralExpressionSyntax;
literalString = s.Token.ValueText;
}
return double.TryParse(literalString, out result);
}
}
} | mit | C# |
3cf9bdf805be021dea8787732013d1106e57d663 | Implement code making the previously failing unit test pass. | hackle/AutoFixture,sergeyshushlyapin/AutoFixture,dcastro/AutoFixture,AutoFixture/AutoFixture,sbrockway/AutoFixture,sbrockway/AutoFixture,sergeyshushlyapin/AutoFixture,Pvlerick/AutoFixture,dcastro/AutoFixture,hackle/AutoFixture,adamchester/AutoFixture,sean-gilliam/AutoFixture,adamchester/AutoFixture,zvirja/AutoFixture | Src/AutoFixture/IFixtureExtensions.cs | Src/AutoFixture/IFixtureExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ploeh.AutoFixture
{
public static class IFixtureExtensions
{
public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function)
{
if (fixture == null)
{
throw new ArgumentNullException("fixture");
}
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ploeh.AutoFixture
{
public static class IFixtureExtensions
{
public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
c6f74643f8e003d2508009f64da278622509b5a2 | add ToModel3DGroup(), ToModelVisual3D() | TakeAsh/cs-WpfUtility | WpfUtility/Model3DExtensionMethods.cs | WpfUtility/Model3DExtensionMethods.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media.Media3D;
namespace WpfUtility {
public static class Model3DExtensionMethods {
public static object GetTag(this Model3D model) {
return model.GetValue(FrameworkElement.TagProperty);
}
public static void SetTag(this Model3D model, object value) {
model.SetValue(FrameworkElement.TagProperty, value);
}
public static Model3DGroup ToModel3DGroup(
this IEnumerable<Model3D> source,
Transform3D transform = null
) {
if (source == null || source.Count() == 0) {
return null;
}
return new Model3DGroup() {
Children = new Model3DCollection(source),
Transform = transform,
};
}
public static ModelVisual3D ToModelVisual3D(
this Model3D model,
Transform3D transform = null
) {
if (model == null) {
return null;
}
return new ModelVisual3D() {
Content = model,
Transform = transform,
};
}
public static ModelVisual3D ToModelVisual3D(
this IEnumerable<Model3D> source,
Transform3D transform = null
) {
if (source == null || source.Count() == 0) {
return null;
}
return source.ToModel3DGroup()
.ToModelVisual3D(transform);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media.Media3D;
namespace WpfUtility {
public static class Model3DExtensionMethods {
public static object GetTag(this Model3D model) {
return model.GetValue(FrameworkElement.TagProperty);
}
public static void SetTag(this Model3D model, object value) {
model.SetValue(FrameworkElement.TagProperty, value);
}
}
}
| mit | C# |
924a6a34d2c056826ebee354bc1e54847b04cfe4 | add helpers for registering parsers and validators | MienDev/IdentityServer4,siyo-wang/IdentityServer4,chrisowhite/IdentityServer4,jbijlsma/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,chrisowhite/IdentityServer4,IdentityServer/IdentityServer4,chrisowhite/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,siyo-wang/IdentityServer4,jbijlsma/IdentityServer4,siyo-wang/IdentityServer4,IdentityServer/IdentityServer4 | src/IdentityServer4/Configuration/IdentityServerBuilderExtensions.cs | src/IdentityServer4/Configuration/IdentityServerBuilderExtensions.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 IdentityServer4.Core.Models;
using IdentityServer4.Core.Services;
using IdentityServer4.Core.Services.InMemory;
using IdentityServer4.Core.Validation;
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyInjection
{
public static class IdentityServerBuilderExtensions
{
public static IIdentityServerBuilder AddInMemoryUsers(this IIdentityServerBuilder builder, List<InMemoryUser> users)
{
var userService = new InMemoryUserService(users);
builder.Services.AddSingleton<IUserService>(prov => userService);
return builder;
}
public static IIdentityServerBuilder AddInMemoryClients(this IIdentityServerBuilder builder, IEnumerable<Client> clients)
{
var clientStore = new InMemoryClientStore(clients);
builder.Services.AddSingleton<IClientStore>(prov => clientStore);
return builder;
}
public static IIdentityServerBuilder AddInMemoryScopes(this IIdentityServerBuilder builder, IEnumerable<Scope> scopes)
{
var scopeStore = new InMemoryScopeStore(scopes);
builder.Services.AddSingleton<IScopeStore>(prov => scopeStore);
return builder;
}
public static IIdentityServerBuilder AddCustomGrantValidator<T>(this IIdentityServerBuilder builder)
where T : class, ICustomGrantValidator
{
builder.Services.AddTransient<ICustomGrantValidator, T>();
return builder;
}
public static IIdentityServerBuilder AddSecretParser<T>(this IIdentityServerBuilder builder)
where T : class, ISecretParser
{
builder.Services.AddTransient<ISecretParser, T>();
return builder;
}
public static IIdentityServerBuilder AddSecretValidator<T>(this IIdentityServerBuilder builder)
where T : class, ISecretValidator
{
builder.Services.AddTransient<ISecretValidator, T>();
return builder;
}
}
} | // 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 IdentityServer4.Core.Models;
using IdentityServer4.Core.Services;
using IdentityServer4.Core.Services.InMemory;
using IdentityServer4.Core.Validation;
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyInjection
{
public static class IdentityServerBuilderExtensions
{
public static IIdentityServerBuilder AddInMemoryUsers(this IIdentityServerBuilder builder, List<InMemoryUser> users)
{
var userService = new InMemoryUserService(users);
builder.Services.AddSingleton<IUserService>(prov => userService);
return builder;
}
public static IIdentityServerBuilder AddInMemoryClients(this IIdentityServerBuilder builder, IEnumerable<Client> clients)
{
var clientStore = new InMemoryClientStore(clients);
builder.Services.AddSingleton<IClientStore>(prov => clientStore);
return builder;
}
public static IIdentityServerBuilder AddInMemoryScopes(this IIdentityServerBuilder builder, IEnumerable<Scope> scopes)
{
var scopeStore = new InMemoryScopeStore(scopes);
builder.Services.AddSingleton<IScopeStore>(prov => scopeStore);
return builder;
}
public static IIdentityServerBuilder AddCustomGrantValidator<T>(this IIdentityServerBuilder builder)
where T : class, ICustomGrantValidator
{
builder.Services.AddTransient<ICustomGrantValidator, T>();
return builder;
}
}
} | apache-2.0 | C# |
921f3a6d6c9cbf76e43d0c77a5cf1ad8869fc561 | Update QuoteRepository.cs | Midnight-Myth/Mitternacht-NEW,powered-by-moe/MikuBot,ShadowNoire/NadekoBot,Nielk1/NadekoBot,ScarletKuro/NadekoBot,Midnight-Myth/Mitternacht-NEW,gfrewqpoiu/NadekoBot,Taknok/NadekoBot,miraai/NadekoBot,Blacnova/NadekoBot,PravEF/EFNadekoBot,halitalf/NadekoMods,WoodenGlaze/NadekoBot,shikhir-arora/NadekoBot,Midnight-Myth/Mitternacht-NEW,Youngsie1997/NadekoBot,Grinjr/NadekoBot,Midnight-Myth/Mitternacht-NEW | src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs | src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs | using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
return _set.Where(q => q.Text.Contains(text) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
| using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
}
}
| mit | C# |
a901fa4c4fd7dbd7eec78be95672cddbdaa9e416 | Update mock API | devkimchi/Testing-Serverless-Applications | src/Sample.FunctionApp/MockTemplateDirectoriesHttpTriggerNotFound.cs | src/Sample.FunctionApp/MockTemplateDirectoriesHttpTriggerNotFound.cs | using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Sample.FunctionApp
{
/// <summary>
/// This represents the HTTP trigger entity for the MockTemplateDirectories event returning <see cref="HttpStatusCode.NotFound"/>.
/// </summary>
public static class MockTemplateDirectoriesHttpTriggerNotFound
{
/// <summary>
/// Invokes the HTTP trigger.
/// </summary>
/// <param name="req"><see cref="HttpRequestMessage"/> instance.</param>
/// <param name="log"><see cref="ILogger"/> instance.</param>
/// <returns>Returns the <see cref="HttpResponseMessage"/> instance.</returns>
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
var models = new List<object>();
return req.CreateResponse(HttpStatusCode.OK, models);
}
}
} | using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Sample.FunctionApp
{
/// <summary>
/// This represents the HTTP trigger entity for the MockTemplateDirectories event returning <see cref="HttpStatusCode.NotFound"/>.
/// </summary>
public static class MockTemplateDirectoriesHttpTriggerNotFound
{
/// <summary>
/// Invokes the HTTP trigger.
/// </summary>
/// <param name="req"><see cref="HttpRequestMessage"/> instance.</param>
/// <param name="log"><see cref="ILogger"/> instance.</param>
/// <returns>Returns the <see cref="HttpResponseMessage"/> instance.</returns>
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
var models = new List<object>();
return req.CreateResponse(HttpStatusCode.NotFound, models);
}
}
} | mit | C# |
7ae208a33cb755d59b54a03943b98a835be6d0f3 | Update PowerShellTraceTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Analytics/Telemetry/PowerShellTraceTelemeter.cs | TIKSN.Framework.Core/Analytics/Telemetry/PowerShellTraceTelemeter.cs | using System;
using System.Management.Automation;
using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public class PowerShellTraceTelemeter : ITraceTelemeter
{
private readonly Cmdlet cmdlet;
public PowerShellTraceTelemeter(Cmdlet cmdlet) => this.cmdlet = cmdlet;
public Task TrackTrace(string message, TelemetrySeverityLevel severityLevel)
{
switch (severityLevel)
{
case TelemetrySeverityLevel.Critical:
case TelemetrySeverityLevel.Error:
this.cmdlet.WriteError(new ErrorRecord(new Exception(message), null, ErrorCategory.InvalidOperation,
null));
break;
case TelemetrySeverityLevel.Information:
this.cmdlet.WriteDebug(message);
break;
case TelemetrySeverityLevel.Verbose:
this.cmdlet.WriteVerbose(message);
break;
case TelemetrySeverityLevel.Warning:
this.cmdlet.WriteWarning(message);
break;
default:
throw new NotSupportedException();
}
return Task.FromResult<object>(null);
}
public Task TrackTrace(string message) => this.TrackTrace(message, TelemetrySeverityLevel.Verbose);
}
}
| using System;
using System.Management.Automation;
using System.Threading.Tasks;
namespace TIKSN.Analytics.Telemetry
{
public class PowerShellTraceTelemeter : ITraceTelemeter
{
private readonly Cmdlet cmdlet;
public PowerShellTraceTelemeter(Cmdlet cmdlet)
{
this.cmdlet = cmdlet;
}
public Task TrackTrace(string message, TelemetrySeverityLevel severityLevel)
{
switch (severityLevel)
{
case TelemetrySeverityLevel.Critical:
case TelemetrySeverityLevel.Error:
cmdlet.WriteError(new ErrorRecord(new Exception(message), null, ErrorCategory.InvalidOperation, null));
break;
case TelemetrySeverityLevel.Information:
this.cmdlet.WriteDebug(message);
break;
case TelemetrySeverityLevel.Verbose:
this.cmdlet.WriteVerbose(message);
break;
case TelemetrySeverityLevel.Warning:
this.cmdlet.WriteWarning(message);
break;
default:
throw new NotSupportedException();
}
return Task.FromResult<object>(null);
}
public Task TrackTrace(string message)
{
return TrackTrace(message, TelemetrySeverityLevel.Verbose);
}
}
} | mit | C# |
18e06a6b01c258b70a26f75809c6f5925fd57cca | Set implicit SDK version header while using Android release mode. | Kentico/delivery-sdk-net,Kentico/Deliver-.NET-SDK | KenticoCloud.Delivery/Extensions/HttpRequestHeadersExtensions.cs | KenticoCloud.Delivery/Extensions/HttpRequestHeadersExtensions.cs | using System;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Reflection;
namespace KenticoCloud.Delivery.Extensions
{
internal static class HttpRequestHeadersExtensions
{
private const string SdkTrackingHeaderName = "X-KC-SDKID";
private const string WaitForLoadingNewContentHeaderName = "X-KC-Wait-For-Loading-New-Content";
private const string PackageRepositoryHost = "nuget.org";
private static readonly Lazy<string> SdkVersion = new Lazy<String>(GetSdkVersion);
private static readonly Lazy<string> SdkPackageId = new Lazy<String>(GetSdkPackageId);
internal static void AddSdkTrackingHeader(this HttpRequestHeaders header)
{
header.Add(SdkTrackingHeaderName, $"{PackageRepositoryHost};{SdkPackageId.Value};{SdkVersion.Value}");
}
internal static void AddWaitForLoadingNewContentHeader(this HttpRequestHeaders header)
{
header.Add(WaitForLoadingNewContentHeaderName, "true");
}
internal static void AddAuthorizationHeader(this HttpRequestHeaders header, string scheme, string parameter)
{
header.Authorization = new AuthenticationHeaderValue(scheme, parameter);
}
private static string GetSdkVersion()
{
var assembly = Assembly.GetExecutingAssembly();
string sdkVersion;
try
{
var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
sdkVersion = fileVersionInfo.ProductVersion;
}
catch (System.IO.FileNotFoundException)
{
// Invalid Location path of assembly in Android's Xamarin release mode (unchecked "Use a shared runtime" flag)
// https://bugzilla.xamarin.com/show_bug.cgi?id=54678
sdkVersion = "0.0.0";
}
return sdkVersion;
}
private static string GetSdkPackageId()
{
var assembly = Assembly.GetExecutingAssembly();
var sdkPackageId = assembly.GetName().Name;
return sdkPackageId;
}
}
}
| using System;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Reflection;
namespace KenticoCloud.Delivery.Extensions
{
internal static class HttpRequestHeadersExtensions
{
private const string SdkTrackingHeaderName = "X-KC-SDKID";
private const string WaitForLoadingNewContentHeaderName = "X-KC-Wait-For-Loading-New-Content";
private const string PackageRepositoryHost = "nuget.org";
private static readonly Lazy<string> SdkVersion = new Lazy<String>(GetSdkVersion);
private static readonly Lazy<string> SdkPackageId = new Lazy<String>(GetSdkPackageId);
internal static void AddSdkTrackingHeader(this HttpRequestHeaders header)
{
header.Add(SdkTrackingHeaderName, $"{PackageRepositoryHost};{SdkPackageId.Value};{SdkVersion.Value}");
}
internal static void AddWaitForLoadingNewContentHeader(this HttpRequestHeaders header)
{
header.Add(WaitForLoadingNewContentHeaderName, "true");
}
internal static void AddAuthorizationHeader(this HttpRequestHeaders header, string scheme, string parameter)
{
header.Authorization = new AuthenticationHeaderValue(scheme, parameter);
}
private static string GetSdkVersion()
{
var assembly = Assembly.GetExecutingAssembly();
var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
var sdkVersion = fileVersionInfo.ProductVersion;
return sdkVersion;
}
private static string GetSdkPackageId()
{
var assembly = Assembly.GetExecutingAssembly();
var sdkPackageId = assembly.GetName().Name;
return sdkPackageId;
}
}
}
| mit | C# |
98bce57fd3de7debf1c16b4a953af310443345c0 | Add BigmodsPassword, BigmodsUsername to AutomationRunnerSettings | Willster419/RelhaxModpack,Willster419/RelicModManager,Willster419/RelhaxModpack | RelhaxModpack/RelhaxModpack/Settings/AutomationRunnerSettings.cs | RelhaxModpack/RelhaxModpack/Settings/AutomationRunnerSettings.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RelhaxModpack.Settings
{
/// <summary>
/// Defines settings used in the database automation runner window
/// </summary>
public class AutomationRunnerSettings : ISettingsFile
{
/// <summary>
/// The name of the xml file on disk
/// </summary>
public string Filename { get; } = "AutomationRunnerSettings.xml";
/// <summary>
/// A list of properties and fields to exclude from saving/loading to and from xml
/// </summary>
public string[] MembersToExclude { get { return new string[] { nameof(MembersToExclude), nameof(Filename), nameof(RepoDefaultBranch) }; } }
/// <summary>
/// The name of the branch on github that the user specifies to download the automation scripts from
/// </summary>
public string SelectedBranch { get; set; } = "master";
public const string RepoDefaultBranch = "master";
public bool OpenLogWindowOnStartup { get; set; } = true;
public string BigmodsUsername { get; set; } = string.Empty;
public string BigmodsPassword { get; set; } = string.Empty;
/// <summary>
/// Toggle to dump the parsed macros to the log file before every sequence run
/// </summary>
public bool DumpParsedMacrosPerSequenceRun { get; set; } = false;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RelhaxModpack.Settings
{
/// <summary>
/// Defines settings used in the database automation runner window
/// </summary>
public class AutomationRunnerSettings : ISettingsFile
{
/// <summary>
/// The name of the xml file on disk
/// </summary>
public string Filename { get; } = "AutomationRunnerSettings.xml";
/// <summary>
/// A list of properties and fields to exclude from saving/loading to and from xml
/// </summary>
public string[] MembersToExclude { get { return new string[] { nameof(MembersToExclude), nameof(Filename), nameof(RepoDefaultBranch) }; } }
/// <summary>
/// The name of the branch on github that the user specifies to download the automation scripts from
/// </summary>
public string SelectedBranch { get; set; } = "master";
public const string RepoDefaultBranch = "master";
public bool OpenLogWindowOnStartup { get; set; } = true;
/// <summary>
/// Toggle to dump the parsed macros to the log file before every sequence run
/// </summary>
public bool DumpParsedMacrosPerSequenceRun { get; set; } = false;
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.