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 |
|---|---|---|---|---|---|---|---|---|
a6a835a9768cf51083517405ea898b2dbfa83eb6 | add the template to IClient | kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,SparkPost/csharp-sparkpost | src/SparkPost/IClient.cs | src/SparkPost/IClient.cs | namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets access to the webhooks resource of the SparkPost API.
/// </summary>
IWebhooks Webhooks { get; }
/// <summary>
/// Gets access to the message events resource of the SparkPost API.
/// </summary>
IMessageEvents MessageEvents { get; }
/// <summary>
/// Gets access to the inbound domains resource of the SparkPost API.
/// </summary>
IInboundDomains InboundDomains { get; }
/// <summary>
/// Gets access to the relay webhooks resource of the SparkPost API.
/// </summary>
IRelayWebhooks RelayWebhooks { get; }
IRecipientLists RecipientLists { get; }
/// <summary>
/// Gets access to the Templates resource of the SparkPost API.
/// </summary>
ITemplates Templates { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
/// <summary>
/// Gets the sub account.
/// </summary>
long SubaccountId { get; }
}
}
| namespace SparkPost
{
/// <summary>
/// Provides access to the SparkPost API.
/// </summary>
public interface IClient
{
/// <summary>
/// Gets or sets the key used for requests to the SparkPost API.
/// </summary>
string ApiKey { get; set; }
/// <summary>
/// Gets or sets the base URL of the SparkPost API.
/// </summary>
string ApiHost { get; set; }
/// <summary>
/// Gets access to the transmissions resource of the SparkPost API.
/// </summary>
ITransmissions Transmissions { get; }
/// <summary>
/// Gets access to the suppressions resource of the SparkPost API.
/// </summary>
ISuppressions Suppressions { get; }
/// <summary>
/// Gets access to the subaccounts resource of the SparkPost API.
/// </summary>
ISubaccounts Subaccounts { get; }
/// <summary>
/// Gets access to the webhooks resource of the SparkPost API.
/// </summary>
IWebhooks Webhooks { get; }
/// <summary>
/// Gets access to the message events resource of the SparkPost API.
/// </summary>
IMessageEvents MessageEvents { get; }
/// <summary>
/// Gets access to the inbound domains resource of the SparkPost API.
/// </summary>
IInboundDomains InboundDomains { get; }
/// <summary>
/// Gets access to the relay webhooks resource of the SparkPost API.
/// </summary>
IRelayWebhooks RelayWebhooks { get; }
IRecipientLists RecipientLists { get; }
/// <summary>
/// Gets the API version supported by this client.
/// </summary>
string Version { get; }
/// <summary>
/// Get the custom settings for this client.
/// </summary>
Client.Settings CustomSettings { get; }
/// <summary>
/// Gets the sub account.
/// </summary>
long SubaccountId { get; }
}
}
| apache-2.0 | C# |
cb2cd4e93ffb7a845a1013f5949fb2dd727ebd0e | Add to source. Early/Unstable | stevefsp/critterai,stevefsp/critterai,stevefsp/critterai,stevefsp/critterai,stevefsp/critterai | nav/rcn-interop/Properties/AssemblyInfo.cs | nav/rcn-interop/Properties/AssemblyInfo.cs | /*
* Copyright (c) 2011 Stephen A. Pratt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("cai-nav-rcn-interop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CritterAI")]
[assembly: AssemblyProduct("cai-nav-rcn-interop")]
[assembly: AssemblyCopyright("Copyright © Stephen Pratt 2011")]
[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("137f5997-0d1c-4cb0-b00c-e6d5f68a5f0c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("cai-nav-rcn-interop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("CritterAI")]
[assembly: AssemblyProduct("cai-nav-rcn-interop")]
[assembly: AssemblyCopyright("Copyright © Stephen Pratt 2011")]
[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("137f5997-0d1c-4cb0-b00c-e6d5f68a5f0c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| mit | C# |
733b86eeb93ac7fdb2506318739919e8bba75cc2 | Implement non-abstract socket support | tmds/Tmds.DBus | UnixNativeTransport.cs | UnixNativeTransport.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using Mono.Unix;
using Mono.Unix.Native;
namespace NDesk.DBus
{
public class UnixSocket
{
//TODO: verify these
[DllImport ("libc")]
protected static extern int socket (int domain, int type, int protocol);
[DllImport ("libc")]
protected static extern int connect (int sockfd, byte[] serv_addr, uint addrlen);
public int Handle;
public UnixSocket ()
{
//AddressFamily family, SocketType type, ProtocolType proto
//Handle = socket ((int)AddressFamily.Unix, (int)SocketType.Stream, 0);
Handle = socket (1, (int)SocketType.Stream, 0);
}
//TODO: consider memory management
public void Connect (byte[] remote_end)
{
int ret = connect (Handle, remote_end, (uint)remote_end.Length);
//Console.Error.WriteLine ("connect ret: " + ret);
//FIXME: we need to get the errno or it will screw things up later?
}
}
public class UnixNativeTransport : Transport, IAuthenticator
{
protected UnixSocket socket;
public UnixNativeTransport (string path, bool @abstract)
{
if (@abstract)
socket = OpenAbstractUnix (path);
else
socket = OpenUnix (path);
//socket.Blocking = true;
SocketHandle = (long)socket.Handle;
Stream = new UnixStream ((int)socket.Handle);
}
public override string AuthString ()
{
long uid = UnixUserInfo.GetRealUserId ();
return uid.ToString ();
}
protected UnixSocket OpenAbstractUnix (string path)
{
byte[] p = System.Text.Encoding.Default.GetBytes (path);
byte[] sa = new byte[2 + 1 + p.Length];
//sa[0] = (byte)AddressFamily.Unix;
sa[0] = 1;
sa[1] = 0;
sa[2] = 0; //null prefix for abstract sockets, see unix(7)
for (int i = 0 ; i != p.Length ; i++)
sa[i+3] = p[i];
UnixSocket client = new UnixSocket ();
client.Connect (sa);
//Console.Error.WriteLine ("client Handle: " + client.Handle);
return client;
}
public UnixSocket OpenUnix (string path)
{
byte[] p = System.Text.Encoding.Default.GetBytes (path);
byte[] sa = new byte[2 + p.Length + 1];
//sa[0] = (byte)AddressFamily.Unix;
sa[0] = 1;
sa[1] = 0;
for (int i = 0 ; i != p.Length ; i++)
sa[i+2] = p[i];
sa[2 + p.Length] = 0; //null suffix for sockets, see unix(7)
UnixSocket client = new UnixSocket ();
client.Connect (sa);
//Console.Error.WriteLine ("client Handle: " + client.Handle);
return client;
}
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using Mono.Unix;
using Mono.Unix.Native;
namespace NDesk.DBus
{
public class UnixSocket
{
//TODO: verify these
[DllImport ("libc")]
protected static extern int socket (int domain, int type, int protocol);
[DllImport ("libc")]
protected static extern int connect (int sockfd, byte[] serv_addr, uint addrlen);
public int Handle;
public UnixSocket ()
{
//AddressFamily family, SocketType type, ProtocolType proto
//Handle = socket ((int)AddressFamily.Unix, (int)SocketType.Stream, 0);
Handle = socket (1, (int)SocketType.Stream, 0);
}
//TODO: consider memory management
public void Connect (byte[] remote_end)
{
int ret = connect (Handle, remote_end, (uint)remote_end.Length);
//Console.Error.WriteLine ("connect ret: " + ret);
//FIXME: we need to get the errno or it will screw things up later?
}
}
public class UnixNativeTransport : Transport, IAuthenticator
{
protected UnixSocket socket;
public UnixNativeTransport (string path, bool @abstract)
{
if (@abstract)
socket = OpenAbstractUnix (path);
else
socket = OpenUnix (path);
//socket.Blocking = true;
SocketHandle = (long)socket.Handle;
Stream = new UnixStream ((int)socket.Handle);
}
public override string AuthString ()
{
long uid = UnixUserInfo.GetRealUserId ();
return uid.ToString ();
}
protected UnixSocket OpenAbstractUnix (string path)
{
byte[] p = System.Text.Encoding.Default.GetBytes (path);
byte[] sa = new byte[2 + 1 + p.Length];
//sa[0] = (byte)AddressFamily.Unix;
sa[0] = 1;
sa[1] = 0;
sa[2] = 0; //null prefix for abstract sockets, see unix(7)
for (int i = 0 ; i != p.Length ; i++)
sa[i+3] = p[i];
UnixSocket client = new UnixSocket ();
client.Connect (sa);
//Console.Error.WriteLine ("client Handle: " + client.Handle);
return client;
}
public UnixSocket OpenUnix (string path)
{
//TODO
throw new Exception ("Not implemented yet");
}
}
}
| mit | C# |
5b264cf65cba866b04a34b4571b96f1e2d5630b6 | remove unused using | Microsoft/vscode-mono-debug,Microsoft/vscode-mono-debug | src/sdb/CommandLine.cs | src/sdb/CommandLine.cs | //
// The MIT License (MIT)
//
// Copyright (c) 2014 Alex Rønne Petersen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System.Threading;
namespace Mono.Debugger.Client
{
public static class CommandLine
{
internal static AutoResetEvent ResumeEvent { get; private set; }
internal static bool InferiorExecuting { get; set; }
static CommandLine()
{
ResumeEvent = new AutoResetEvent(false);
}
internal static void SetControlCHandler()
{
}
internal static void UnsetControlCHandler()
{
}
public static void WaitForSuspend() {
if (InferiorExecuting)
{
ResumeEvent.WaitOne();
InferiorExecuting = false;
}
}
}
}
| //
// The MIT License (MIT)
//
// Copyright (c) 2014 Alex Rønne Petersen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Threading;
namespace Mono.Debugger.Client
{
public static class CommandLine
{
internal static AutoResetEvent ResumeEvent { get; private set; }
internal static bool InferiorExecuting { get; set; }
static CommandLine()
{
ResumeEvent = new AutoResetEvent(false);
}
internal static void SetControlCHandler()
{
}
internal static void UnsetControlCHandler()
{
}
public static void WaitForSuspend() {
if (InferiorExecuting)
{
ResumeEvent.WaitOne();
InferiorExecuting = false;
}
}
}
}
| mit | C# |
e7c563fb671f8c2eee44de363e6c04971dad6cd3 | simplify `CreateTextFlow` in quote block | NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownQuoteBlock.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownQuoteBlock.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownQuoteBlock : MarkdownQuoteBlock
{
private Drawable background;
public OsuMarkdownQuoteBlock(QuoteBlock quoteBlock)
: base(quoteBlock)
{
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
background.Colour = colourProvider.Content2;
}
protected override Drawable CreateBackground()
{
background = base.CreateBackground();
background.Width = 2;
return background;
}
public override MarkdownTextFlowContainer CreateTextFlow()
{
return base.CreateTextFlow().With(f => f.Margin = new MarginPadding
{
Vertical = 10,
Horizontal = 20,
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownQuoteBlock : MarkdownQuoteBlock
{
private Drawable background;
public OsuMarkdownQuoteBlock(QuoteBlock quoteBlock)
: base(quoteBlock)
{
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
background.Colour = colourProvider.Content2;
}
protected override Drawable CreateBackground()
{
background = base.CreateBackground();
background.Width = 2;
return background;
}
public override MarkdownTextFlowContainer CreateTextFlow()
{
var textFlow = base.CreateTextFlow();
textFlow.Margin = new MarginPadding
{
Vertical = 10,
Horizontal = 20,
};
return textFlow;
}
}
}
| mit | C# |
22c8e134d28452f34dd4d57fab58a8dc27b5064c | Change "Sidebar" widget "ParseShortcutFiles" option default value | danielchalmers/DesktopWidgets | DesktopWidgets/Widgets/Sidebar/Settings.cs | DesktopWidgets/Widgets/Sidebar/Settings.cs | using System.Collections.ObjectModel;
using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.Sidebar
{
public class Settings : WidgetSettingsBase
{
[DisplayName("Shortcuts")]
public ObservableCollection<Shortcut> Shortcuts { get; set; }
[Category("Shortcut Style")]
[DisplayName("Icon Position")]
public IconPosition IconPosition { get; set; } = IconPosition.Left;
[Category("Shortcut Style")]
[DisplayName("Tooltip Type")]
public ToolTipType ToolTipType { get; set; } = ToolTipType.None;
[Category("Shortcut Style")]
[DisplayName("Shortcut Alignment")]
public ShortcutAlignment ButtonAlignment { get; set; } = ShortcutAlignment.Center;
[Category("Shortcut Style")]
[DisplayName("Icon Scaling Mode")]
public ImageScalingMode IconScalingMode { get; set; } = ImageScalingMode.LowQuality;
[Category("Shortcut Style")]
[DisplayName("Shortcut Content Mode")]
public ShortcutContentMode ShortcutContentMode { get; set; } = ShortcutContentMode.Both;
[Category("Style")]
[DisplayName("Shortcut Orientation")]
public ShortcutOrientation ShortcutOrientation { get; set; } = ShortcutOrientation.Auto;
[Category("Shortcut Style")]
[DisplayName("Shortcut Height")]
public int ButtonHeight { get; set; } = 32;
[Category("Behavior")]
[DisplayName("Hide on Shortcut Launch")]
public bool HideOnExecute { get; set; } = true;
[DisplayName("Allow Drag Drop Files")]
public bool AllowDropFiles { get; set; } = true;
[DisplayName("Default Shortcuts Mode")]
public DefaultShortcutsMode DefaultShortcutsMode { get; set; } = DefaultShortcutsMode.Preset;
[DisplayName("Parse Shortcut Files")]
public bool ParseShortcutFiles { get; set; } = false;
[DisplayName("Enable Icon Cache")]
public bool UseIconCache { get; set; } = true;
}
} | using System.Collections.ObjectModel;
using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.Sidebar
{
public class Settings : WidgetSettingsBase
{
[DisplayName("Shortcuts")]
public ObservableCollection<Shortcut> Shortcuts { get; set; }
[Category("Shortcut Style")]
[DisplayName("Icon Position")]
public IconPosition IconPosition { get; set; } = IconPosition.Left;
[Category("Shortcut Style")]
[DisplayName("Tooltip Type")]
public ToolTipType ToolTipType { get; set; } = ToolTipType.None;
[Category("Shortcut Style")]
[DisplayName("Shortcut Alignment")]
public ShortcutAlignment ButtonAlignment { get; set; } = ShortcutAlignment.Center;
[Category("Shortcut Style")]
[DisplayName("Icon Scaling Mode")]
public ImageScalingMode IconScalingMode { get; set; } = ImageScalingMode.LowQuality;
[Category("Shortcut Style")]
[DisplayName("Shortcut Content Mode")]
public ShortcutContentMode ShortcutContentMode { get; set; } = ShortcutContentMode.Both;
[Category("Style")]
[DisplayName("Shortcut Orientation")]
public ShortcutOrientation ShortcutOrientation { get; set; } = ShortcutOrientation.Auto;
[Category("Shortcut Style")]
[DisplayName("Shortcut Height")]
public int ButtonHeight { get; set; } = 32;
[Category("Behavior")]
[DisplayName("Hide on Shortcut Launch")]
public bool HideOnExecute { get; set; } = true;
[DisplayName("Allow Drag Drop Files")]
public bool AllowDropFiles { get; set; } = true;
[DisplayName("Default Shortcuts Mode")]
public DefaultShortcutsMode DefaultShortcutsMode { get; set; } = DefaultShortcutsMode.Preset;
[DisplayName("Parse Shortcut Files")]
public bool ParseShortcutFiles { get; set; } = true;
[DisplayName("Enable Icon Cache")]
public bool UseIconCache { get; set; } = true;
}
} | apache-2.0 | C# |
a9bf8c2bd9d6a4723dfdc963942e1a45918341e2 | fix for double rename | OmniSharp/omnisharp-vim,AndBicScadMedia/omnisharp-vim,nosami/omnisharp-vim,OmniSharp/omnisharp-vim,OmniSharp/omnisharp-vim,anurse/omnisharp-vim,den-mentiei/omnisharp-vim | OmniSharp/Solution/CSharpFile.cs | OmniSharp/Solution/CSharpFile.cs | using System;
using System.IO;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.NRefactory.TypeSystem;
namespace OmniSharp.Solution
{
public class CSharpFile
{
public string FileName;
public ITextSource Content;
public SyntaxTree SyntaxTree;
public IUnresolvedFile ParsedFile;
public StringBuilderDocument Document { get; set; }
public CSharpFile(IProject project, string fileName) : this(project, fileName, File.ReadAllText(fileName))
{
}
public CSharpFile(IProject project, string fileName, string source)
{
Parse(project, fileName, source);
}
private void Parse(IProject project, string fileName, string source)
{
Console.WriteLine("Loading " + fileName);
this.FileName = fileName;
this.Content = new StringTextSource(source);
this.Document = new StringBuilderDocument(this.Content);
this.Project = project;
CSharpParser p = project.CreateParser();
this.SyntaxTree = p.Parse(Content.CreateReader(), fileName);
if (p.HasErrors)
{
Console.WriteLine("Error parsing " + fileName + ":");
foreach (var error in p.Errors)
{
Console.WriteLine(" " + error.Region + " " + error.Message);
}
}
this.ParsedFile = this.SyntaxTree.ToTypeSystem();
if(this.Project.ProjectContent != null)
this.Project.ProjectContent.AddOrUpdateFiles(this.ParsedFile);
}
protected IProject Project { get; set; }
public void Update(string source)
{
this.Content = new StringTextSource(source);
Parse(Project, this.FileName, source);
}
}
} | using System;
using System.IO;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.NRefactory.TypeSystem;
namespace OmniSharp.Solution
{
public class CSharpFile
{
public string FileName;
public ITextSource Content;
public SyntaxTree SyntaxTree;
public IUnresolvedFile ParsedFile;
public StringBuilderDocument Document { get; set; }
public CSharpFile(IProject project, string fileName) : this(project, fileName, File.ReadAllText(fileName))
{
}
public CSharpFile(IProject project, string fileName, string source)
{
Parse(project, fileName, source);
}
private void Parse(IProject project, string fileName, string source)
{
Console.WriteLine("Loading " + fileName);
this.FileName = fileName;
this.Content = new StringTextSource(source);
this.Document = new StringBuilderDocument(this.Content);
this.Project = project;
CSharpParser p = project.CreateParser();
this.SyntaxTree = p.Parse(Content.CreateReader(), fileName);
if (p.HasErrors)
{
Console.WriteLine("Error parsing " + fileName + ":");
foreach (var error in p.Errors)
{
Console.WriteLine(" " + error.Region + " " + error.Message);
}
}
this.ParsedFile = this.SyntaxTree.ToTypeSystem();
if(this.Project.ProjectContent != null)
this.Project.ProjectContent.AddOrUpdateFiles(this.ParsedFile);
}
protected IProject Project { get; set; }
public void Update(string source)
{
Parse(Project, this.FileName, source);
}
}
} | mit | C# |
7ab63a4087e71007edecd0504de88b3fdf54dfcc | Set static member. | Appius/Algorithms-and-Data-Structures | Algorithms/Algorithms.Tests/SortingAlgorithms/QuickSortTests.cs | Algorithms/Algorithms.Tests/SortingAlgorithms/QuickSortTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SortingAlgorimths;
namespace Algorithms.Tests.SortingAlgorithms
{
[TestClass]
public class QuickSortTests
{
private static readonly Random Random = new Random();
[TestMethod]
public void QuickTest()
{
const int n = 1000000; // 1.000.000
var array = new int[n];
for (int i = 0; i < n; i++)
array[i] = Random.Next();
var newArray = new int[n];
array.CopyTo(newArray, 0);
array = SortingAlgorithms<int>.QuickSort(array);
Array.Sort(newArray);
for(int i=0;i<n;i++)
Assert.AreEqual(array[i], newArray[i], "Arrays aren't equals.");
}
}
} | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SortingAlgorimths;
namespace Algorithms.Tests.SortingAlgorithms
{
[TestClass]
public class QuickSortTests
{
private readonly Random _random = new Random();
[TestMethod]
public void QuickTest()
{
const int n = 1000000; // 1.000.000
var array = new int[n];
for (int i = 0; i < n; i++)
array[i] = _random.Next();
var newArray = new int[n];
array.CopyTo(newArray, 0);
array = SortingAlgorithms<int>.QuickSort(array);
Array.Sort(newArray);
for(int i=0;i<n;i++)
Assert.AreEqual(array[i], newArray[i], "Arrays aren't equals.");
}
}
} | apache-2.0 | C# |
285b6d6cd336c02a5ca1e75b1c9da8194af84f0a | Add reasoning in 'ZoneMarkerAndSetUpFixture.cs' | ulrichb/XmlDocInspections,ulrichb/XmlDocInspections,ulrichb/XmlDocInspections | Src/XmlDocInspections.Plugin.Tests/ZoneMarkerAndSetUpFixture.cs | Src/XmlDocInspections.Plugin.Tests/ZoneMarkerAndSetUpFixture.cs | using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
using XmlDocInspections.Plugin.Tests;
[assembly: RequiresSTA]
namespace XmlDocInspections.Plugin.Tests
{
[ZoneDefinition]
public interface IXmlDocInspectionsTestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<IXmlDocInspectionsTestEnvironmentZone>
{
}
}
// Note: Global namespace to workaround (or hide) https://youtrack.jetbrains.com/issue/RSRP-464493.
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<IXmlDocInspectionsTestEnvironmentZone>
{
}
| using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
using XmlDocInspections.Plugin.Tests;
[assembly: RequiresSTA]
namespace XmlDocInspections.Plugin.Tests
{
[ZoneDefinition]
public interface IXmlDocInspectionsTestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<IXmlDocInspectionsTestEnvironmentZone>
{
}
}
// ReSharper disable once CheckNamespace
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<IXmlDocInspectionsTestEnvironmentZone>
{
}
| mit | C# |
0915cef158cfb942ecbd12175c7ad045aa9dee6b | Use Expression body. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/LockScreen/LockScreenViewModelBase.cs | WalletWasabi.Gui/Controls/LockScreen/LockScreenViewModelBase.cs | using System;
using ReactiveUI;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.LockScreen
{
public abstract class LockScreenViewModelBase : ViewModelBase
{
private bool _isAnimating;
private bool _isLocked;
private bool _canSlide;
private volatile bool _disposedValue = false; // To detect redundant calls
public LockScreenViewModelBase()
{
IsLocked = true;
Disposables = new CompositeDisposable();
}
protected CompositeDisposable Disposables { get; }
public bool CanSlide
{
get => _canSlide;
set => this.RaiseAndSetIfChanged(ref _canSlide, value);
}
public bool IsLocked
{
get => _isLocked;
set => this.RaiseAndSetIfChanged(ref _isLocked, value);
}
public bool IsAnimating
{
get => _isAnimating;
set => this.RaiseAndSetIfChanged(ref _isAnimating, value);
}
public void Initialize()
{
OnInitialize(Disposables);
}
protected virtual void OnInitialize(CompositeDisposable disposables)
{
}
protected void Close()
{
IsLocked = false;
this.WhenAnyValue(x => x.IsAnimating)
.Where(x => !x)
.Take(1)
.Subscribe(x => MainWindowViewModel.Instance?.CloseLockScreen(this));
}
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
Disposables?.Dispose();
}
_disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable Support
}
}
| using System;
using ReactiveUI;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.LockScreen
{
public abstract class LockScreenViewModelBase : ViewModelBase
{
private bool _isAnimating;
private bool _isLocked;
private bool _canSlide;
private volatile bool _disposedValue = false; // To detect redundant calls
public LockScreenViewModelBase()
{
IsLocked = true;
Disposables = new CompositeDisposable();
}
protected CompositeDisposable Disposables { get; }
public bool CanSlide
{
get => _canSlide;
set => this.RaiseAndSetIfChanged(ref _canSlide, value);
}
public bool IsLocked
{
get => _isLocked;
set => this.RaiseAndSetIfChanged(ref _isLocked, value);
}
public bool IsAnimating
{
get { return _isAnimating; }
set { this.RaiseAndSetIfChanged(ref _isAnimating, value); }
}
public void Initialize()
{
OnInitialize(Disposables);
}
protected virtual void OnInitialize(CompositeDisposable disposables)
{
}
protected void Close()
{
IsLocked = false;
this.WhenAnyValue(x => x.IsAnimating)
.Where(x => !x)
.Take(1)
.Subscribe(x => MainWindowViewModel.Instance?.CloseLockScreen(this));
}
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
Disposables?.Dispose();
}
_disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable Support
}
}
| mit | C# |
bd69a71c3477f6f5a2c16f01192bef15e4222394 | add raven logo | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/Views/Shared/_Navigation.cshtml | WebAPI.API/Views/Shared/_Navigation.cshtml | <ul class="nav nav-pills nav-stacked">
<li class="nav-header">Web API's</li>
<li class="active"><a href="#home">Home</a></li>
<li><a href="#geocoding">Geocoding</a></li>
<li><a href="#search">Searching</a></li>
<li><a href="#info">SGID Information</a></li>
<li><a href="#network">Network Analysis</a></li>
<li class="nav-header">Resources</li>
<li>@Html.ActionLink("Console", "Dashboard", new
{
Controller = "Go"
})</li>
<li>@Html.ActionLink("Register", "Register", new
{
Controller = "Go"
})</li>
<li class="nav-header">Help</li>
<li>@Html.ActionLink("Getting Started Guide", "Startup", new
{
Controller = "Go"
})</li>
<li class="nav-header">About</li>
<li><a href="@Url.Action("Index", "ChangeLog")"><i class="icon-barcode"></i> @ViewContext.Controller.GetType().Assembly.GetName().Version.ToString()</a></li>
<li class="nav-header">© AGRC @DateTime.Now.Year</li>
</ul>
<p>
<img src="@Url.Content("~/Content/images/ravendb-small.png")" alt="ravendb logo" />
</p> | <ul class="nav nav-pills nav-stacked">
<li class="nav-header">Web API's</li>
<li class="active"><a href="#home">Home</a></li>
<li><a href="#geocoding">Geocoding</a></li>
<li><a href="#search">Searching</a></li>
<li><a href="#info">SGID Information</a></li>
<li><a href="#network">Network Analysis</a></li>
<li class="nav-header">Resources</li>
<li>@Html.ActionLink("Console", "Dashboard", new
{
Controller = "Go"
})</li>
<li>@Html.ActionLink("Register", "Register", new
{
Controller = "Go"
})</li>
<li class="nav-header">Help</li>
<li>@Html.ActionLink("Getting Started Guide", "Startup", new
{
Controller = "Go"
})</li>
<li class="nav-header">About</li>
<li><a href="@Url.Action("Index", "ChangeLog")"><i class="icon-book"></i> @ViewContext.Controller.GetType().Assembly.GetName().Version.ToString()</a></li>
<li class="nav-header">© AGRC @DateTime.Now.Year</li>
</ul> | mit | C# |
3f1cffd9786c0fdc1b8afdbe0904b06834243a73 | fix / on windows phone | mikebluestein/YetAnotherApp | YetAnotherAppWindowsPhone/MainPage.xaml.cs | YetAnotherAppWindowsPhone/MainPage.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using YetAnotherAppWindowsPhone.Resources;
using System.Collections.ObjectModel;
namespace YetAnotherAppWindowsPhone
{
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<string> Monkeys = new ObservableCollection<string>();
// Constructor
public MainPage()
{
InitializeComponent();
Monkeys.Add("Assets/a.jpg");
Monkeys.Add("Assets/b.jpg");
Monkeys.Add("Assets/c.jpg");
Monkeys.Add("Assets/d.jpg");
Monkeys.Add("Assets/e.jpg");
Monkeys.Add("Assets/f.jpg");
Monkeys.Add("Assets/g.jpg");
Monkeys.Add("Assets/h.jpg");
Monkeys.Add("Assets/i.jpg");
Monkeys.Add("Assets/j.jpg");
Monkeys.Add("Assets/k.jpg");
Monkeys.Add("Assets/l.jpg");
Monkeys.Add("Assets/m.jpg");
Monkeys.Add("Assets/n.jpg");
Monkeys.Add("Assets/o.jpg");
Monkeys.Add("Assets/p.jpg");
Monkeys.Add("Assets/q.jpg");
Monkeys.Add("Assets/r.jpg");
Monkeys.Add("Assets/s.jpg");
Monkeys.Add("Assets/t.jpg");
Monkeys.Add("Assets/u.jpg");
DataContext = Monkeys;
LongList.SelectionChanged += LongList_SelectionChanged;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
void LongList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var img = LongList.SelectedItem.ToString();
NavigationService.Navigate(new Uri("/FormsPage.xaml?img=" + img, UriKind.Relative));
}
// Sample code for building a localized ApplicationBar
//private void BuildLocalizedApplicationBar()
//{
// // Set the page's ApplicationBar to a new instance of ApplicationBar.
// ApplicationBar = new ApplicationBar();
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using YetAnotherAppWindowsPhone.Resources;
using System.Collections.ObjectModel;
namespace YetAnotherAppWindowsPhone
{
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<string> Monkeys = new ObservableCollection<string>();
// Constructor
public MainPage()
{
InitializeComponent();
Monkeys.Add("/Assets/a.jpg");
Monkeys.Add("/Assets/b.jpg");
Monkeys.Add("/Assets/c.jpg");
Monkeys.Add("/Assets/d.jpg");
Monkeys.Add("/Assets/e.jpg");
Monkeys.Add("/Assets/f.jpg");
Monkeys.Add("/Assets/g.jpg");
Monkeys.Add("/Assets/h.jpg");
Monkeys.Add("/Assets/i.jpg");
Monkeys.Add("/Assets/j.jpg");
Monkeys.Add("/Assets/k.jpg");
Monkeys.Add("/Assets/l.jpg");
Monkeys.Add("/Assets/m.jpg");
Monkeys.Add("/Assets/n.jpg");
Monkeys.Add("/Assets/o.jpg");
Monkeys.Add("/Assets/p.jpg");
Monkeys.Add("/Assets/q.jpg");
Monkeys.Add("/Assets/r.jpg");
Monkeys.Add("/Assets/s.jpg");
Monkeys.Add("/Assets/t.jpg");
Monkeys.Add("/Assets/u.jpg");
DataContext = Monkeys;
LongList.SelectionChanged += LongList_SelectionChanged;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
void LongList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var img = LongList.SelectedItem.ToString();
NavigationService.Navigate(new Uri("/FormsPage.xaml?img=" + img, UriKind.Relative));
}
// Sample code for building a localized ApplicationBar
//private void BuildLocalizedApplicationBar()
//{
// // Set the page's ApplicationBar to a new instance of ApplicationBar.
// ApplicationBar = new ApplicationBar();
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
} | mit | C# |
1980bed81b811358a1cd5579c90578493177b4b9 | Make StripeException suck less. | xamarin/XamarinStripe,haithemaraissia/XamarinStripe | XamarinStripe/StripeException.cs | XamarinStripe/StripeException.cs | /*
* Copyright 2011 Xamarin, Inc.
*
* Author(s):
* Gonzalo Paniagua Javier (gonzalo@xamarin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Net;
using Newtonsoft.Json;
namespace Xamarin.Payments.Stripe
{
[JsonObject(MemberSerialization.OptIn)]
public class StripeException : Exception
{
[JsonConstructor]
internal StripeException()
{
}
internal static StripeException GetFromJSON (HttpStatusCode code, string json)
{
var result = JsonConvert.DeserializeObject<StripeException> (json);
result.StatusCode = code;
return result;
}
public override string Message {
get {
return StripeError.Message;
}
}
[JsonProperty (PropertyName="error")]
public StripeError StripeError { get; internal set; }
public HttpStatusCode StatusCode { get; internal set; }
}
}
| /*
* Copyright 2011 Xamarin, Inc.
*
* Author(s):
* Gonzalo Paniagua Javier (gonzalo@xamarin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Net;
using Newtonsoft.Json;
namespace Xamarin.Payments.Stripe
{
[JsonObject(MemberSerialization.OptIn)]
public class StripeException : Exception
{
[JsonConstructor]
internal StripeException()
{
}
internal static StripeException GetFromJSON (HttpStatusCode code, string json)
{
var result = JsonConvert.DeserializeObject<StripeException> (json);
result.StatusCode = code;
return result;
}
[JsonProperty (PropertyName="error")]
public StripeError StripeError { get; internal set; }
public HttpStatusCode StatusCode { get; internal set; }
}
}
| apache-2.0 | C# |
2f777f0a562dbfc6dbcbaeba120d84f985d634aa | fix static cube object | Namone/SimpleScene,RealRui/SimpleScene,smoothdeveloper/SimpleScene,jeske/SimpleScene | SimpleScene/Objects/SSObjectCube.cs | SimpleScene/Objects/SSObjectCube.cs | // Copyright(C) David W. Jeske, 2013
// Released to the public domain. Use, modify and relicense at will.
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace SimpleScene
{
public class SSObjectCube : SSObject
{
private void drawQuadFace(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) {
GL.Vertex3(p0);
GL.Vertex3(p1);
GL.Vertex3(p2);
GL.Vertex3(p0);
GL.Vertex3(p2);
GL.Vertex3(p3);
}
public override void Render(ref SSRenderConfig renderConfig) {
base.Render (ref renderConfig);
var p0 = new Vector3 (-1, -1, 1);
var p1 = new Vector3 ( 1, -1, 1);
var p2 = new Vector3 ( 1, 1, 1);
var p3 = new Vector3 (-1, 1, 1);
var p4 = new Vector3 (-1, -1, -1);
var p5 = new Vector3 ( 1, -1, -1);
var p6 = new Vector3 ( 1, 1, -1);
var p7 = new Vector3 (-1, 1, -1);
GL.Begin(BeginMode.Triangles);
GL.Color3(0.5f, 0.5f, 0.5f);
drawQuadFace(p0, p1, p2, p3);
drawQuadFace(p7, p6, p5, p4);
drawQuadFace(p1, p0, p4, p5);
drawQuadFace(p2, p1, p5, p6);
drawQuadFace(p3, p2, p6, p7);
drawQuadFace(p0, p3, p7, p4);
GL.End();
}
public SSObjectCube () : base()
{
}
}
}
| // Copyright(C) David W. Jeske, 2013
// Released to the public domain. Use, modify and relicense at will.
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace SimpleScene
{
public class SSObjectCube : SSObject
{
public override void Render(ref SSRenderConfig renderConfig) {
base.Render (ref renderConfig);
GL.Begin(BeginMode.Triangles);
GL.Color3(0.5f, 0.5f, 0.5f);
var P0 = new Vector3 (0, 0, 0); // 0 origin
var P1 = new Vector3 (0, 1, 1); // 1 corner
var P2 = new Vector3 (0, 0, 1);
var P3 = new Vector3 (0, 1, 0);
var P4 = new Vector3 (1, 1, 1);
var P5 = new Vector3 (1, 0, 0);
var P6 = new Vector3 (1, 0, 1);
var P7 = new Vector3 (1, 1, 0);
// x-axis faces @ 0
GL.Vertex3(P0); GL.Vertex3(P2); GL.Vertex3(P1);
GL.Vertex3(P0); GL.Vertex3(P1); GL.Vertex3(P3);
// x-axis faces @ 1
GL.Vertex3(P4); GL.Vertex3(P5); GL.Vertex3(P6);
GL.Vertex3(P4); GL.Vertex3(P7); GL.Vertex3(P5);
// y-axis faces @ 0
GL.End();
}
public SSObjectCube () : base()
{
}
}
}
| apache-2.0 | C# |
046564d387df79e83345ee2f9b2d8daf8f17a420 | Configure ElasticSearch from config. | ExRam/ExRam.Gremlinq | src/ExRam.Gremlinq.Providers.Neptune.AspNet/GremlinqSetupExtensions.cs | src/ExRam.Gremlinq.Providers.Neptune.AspNet/GremlinqSetupExtensions.cs | using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ExRam.Gremlinq.Core.AspNet
{
public static class GremlinqSetupExtensions
{
private sealed class UseNeptuneGremlinQuerySourceTransformation : IGremlinQuerySourceTransformation
{
private readonly IConfiguration _configuration;
// ReSharper disable once SuggestBaseTypeForParameter
public UseNeptuneGremlinQuerySourceTransformation(IGremlinqConfiguration configuration)
{
_configuration = configuration
.GetSection("Neptune");
}
public IGremlinQuerySource Transform(IGremlinQuerySource source)
{
return source
.UseNeptune(builder =>
{
var builderWithUri = builder
.At(new Uri("ws://localhost:8182"));
var tranformation = (_configuration["ElasticSearchEndPoint"] is { } endPoint)
? builderWithUri.UseElasticSearch(new Uri(endPoint))
: builderWithUri;
return tranformation
.ConfigureWebSocket(_ => _
.Configure(_configuration));
});
}
}
public static GremlinqSetup UseNeptune(this GremlinqSetup setup)
{
return setup
.UseWebSocket()
.RegisterTypes(serviceCollection => serviceCollection.AddSingleton<IGremlinQuerySourceTransformation, UseNeptuneGremlinQuerySourceTransformation>());
}
public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup)
{
return setup
.UseNeptune()
.UseModel(GraphModel
.FromBaseTypes<TVertex, TEdge>(lookup => lookup
.IncludeAssembliesOfBaseTypes()));
}
}
}
| using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ExRam.Gremlinq.Core.AspNet
{
public static class GremlinqSetupExtensions
{
private sealed class UseNeptuneGremlinQuerySourceTransformation : IGremlinQuerySourceTransformation
{
private readonly IConfiguration _configuration;
// ReSharper disable once SuggestBaseTypeForParameter
public UseNeptuneGremlinQuerySourceTransformation(
IGremlinqConfiguration configuration)
{
_configuration = configuration
.GetSection("Neptune");
}
public IGremlinQuerySource Transform(IGremlinQuerySource source)
{
return source
.UseNeptune(builder => builder
.At(new Uri("ws://localhost:8182"))
.ConfigureWebSocket(_ => _
.Configure(_configuration)));
}
}
public static GremlinqSetup UseNeptune(this GremlinqSetup setup)
{
return setup
.UseWebSocket()
.RegisterTypes(serviceCollection => serviceCollection.AddSingleton<IGremlinQuerySourceTransformation, UseNeptuneGremlinQuerySourceTransformation>());
}
public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup)
{
return setup
.UseNeptune()
.UseModel(GraphModel
.FromBaseTypes<TVertex, TEdge>(lookup => lookup
.IncludeAssembliesOfBaseTypes()));
}
}
}
| mit | C# |
0232a8540edcdc5dc46390a374fc9e2006d74dda | Make BucketExtensions.Queryable internal | couchbaselabs/Linq2Couchbase,drGarbinsky/Linq2Couchbase,brantburnett/Linq2Couchbase | Src/Couchbase.Linq/Extensions/BucketExtensions.cs | Src/Couchbase.Linq/Extensions/BucketExtensions.cs | using System.Linq;
using Couchbase.Configuration.Client;
using Couchbase.Core;
using Couchbase.Linq.Filters;
namespace Couchbase.Linq.Extensions
{
public static class BucketExtensions
{
internal static IQueryable<T> Queryable<T>(this IBucket bucket)
{
//TODO refactor so ClientConfiguration is injectable
return EntityFilterManager.ApplyFilters(new BucketQueryable<T>(bucket, new ClientConfiguration()));
}
}
} | using System.Linq;
using Couchbase.Configuration.Client;
using Couchbase.Core;
using Couchbase.Linq.Filters;
namespace Couchbase.Linq.Extensions
{
public static class BucketExtensions
{
public static IQueryable<T> Queryable<T>(this IBucket bucket)
{
//TODO refactor so ClientConfiguration is injectable
return EntityFilterManager.ApplyFilters(new BucketQueryable<T>(bucket, new ClientConfiguration()));
}
}
} | apache-2.0 | C# |
127bcb27a6c71da6bb8ad06f973b71e416c13847 | Update ReverseString.cs | michaeljwebb/Algorithm-Practice | LeetCode/ReverseString.cs | LeetCode/ReverseString.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class ReverseString
{
public string Reverse_String(string s)
{
char[] sArray = s.ToCharArray();
string result = "";
for (int i = sArray.Length - 1; i >= 0; i--)
{
result += sArray[i];
s = result;
}
return s;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class ReverseString
{
public string Reverse_String(string s)
{
char[] sArray = s.ToCharArray();
string result = "";
for (int i = sArray.Length - 1; i >= 0; i--)
{
result += sArray[i];
s = result;
}
return s;
}
}
| mit | C# |
80b238dbe7ff90ee098a1486346b03caaa7deb53 | Remove hardcoded example key. | omise/omise-dotnet | Omise.Examples/Example.cs | Omise.Examples/Example.cs | using System;
using System.Threading.Tasks;
using Omise.Models;
namespace Omise.Examples
{
public abstract class Example
{
public const string OMISE_PKEY = "pkey_test_replaceme";
public const string OMISE_SKEY = "skey_test_replaceme";
protected Client Client { get; private set; }
public Example()
{
Client = new Client(OMISE_PKEY, OMISE_SKEY);
}
// actually creates a new token, named RetrieveToken() so merchant read
// this as an example call to get token from cient-side.
protected async Task<Token> RetrieveToken()
{
return await Client.Tokens.Create(new CreateTokenRequest
{
Name = "Somchai Prasert",
Number = "4242424242424242",
ExpirationMonth = DateTime.Now.Month,
ExpirationYear = DateTime.Now.Year + 10,
});
}
}
}
| using System;
using System.Threading.Tasks;
using Omise.Models;
namespace Omise.Examples
{
public abstract class Example
{
public const string OMISE_PKEY = "pkey_test_58fm89aq2ozrwm4ic5q";
public const string OMISE_SKEY = "skey_test_58fm89nzgfw698uyls3";
protected Client Client { get; private set; }
public Example()
{
Client = new Client(OMISE_PKEY, OMISE_SKEY);
}
// actually creates a new token, named RetrieveToken() so merchant read
// this as an example call to get token from cient-side.
protected async Task<Token> RetrieveToken()
{
return await Client.Tokens.Create(new CreateTokenRequest
{
Name = "Somchai Prasert",
Number = "4242424242424242",
ExpirationMonth = DateTime.Now.Month,
ExpirationYear = DateTime.Now.Year + 10,
});
}
}
}
| mit | C# |
35973db9c1b2f4e5ed3e5c9f4ae065ee293cfdd8 | Remove some bogus code | gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib.Tests/Expressions/t_ArrayExpressionParser.cs | LINQToTTree/LINQToTTreeLib.Tests/Expressions/t_ArrayExpressionParser.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using LINQToTTreeLib.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Remotion.Data.Linq;
using Remotion.Data.Linq.Clauses.Expressions;
using Remotion.Data.Linq.Parsing.Structure;
namespace LINQToTTreeLib.Tests
{
/// <summary>
///This is a test class for TestArrayExpressionParser and is intended
///to contain all TestArrayExpressionParser Unit Tests
///</summary>
[TestClass()]
public class TestArrayExpressionParser
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestForNonArray()
{
ArrayExpressionParser.ParseArrayExpression(Expression.Variable(typeof(int), "d"));
}
[TestMethod]
public void TestRunForNormalArray()
{
ArrayExpressionParser.ParseArrayExpression(Expression.Variable(typeof(int[]), "d"));
}
private QueryModel GetModel<T>(Expression<Func<T>> expr)
{
var parser = new QueryParser();
return parser.GetParsedQuery(expr.Body);
}
class dummyntup
{
public int run;
public int[] vals;
}
[TestMethod]
public void TestSubQueryExpression()
{
var q = new dummyntup();
q.vals = new int[] { 1, 2, 3, 4, 5 };
var model = GetModel(() => (from j in q.vals select j).Take(1));
var sq = new SubQueryExpression(model);
var result = ArrayExpressionParser.ParseArrayExpression(sq);
Assert.IsNotNull(result);
GeneratedCode gc = new GeneratedCode();
CodeContext cc = new CodeContext();
var indexVar = result.AddLoop(gc, cc);
Assert.IsNotNull(indexVar);
Assert.AreEqual(0, gc.CodeBody.Statements.Count(), "No statement should have been added");
}
}
}
| using System;
using System.Linq;
using System.Linq.Expressions;
using LINQToTTreeLib.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Remotion.Data.Linq;
using Remotion.Data.Linq.Parsing.Structure;
using Remotion.Data.Linq.Clauses.Expressions;
namespace LINQToTTreeLib.Tests
{
/// <summary>
///This is a test class for TestArrayExpressionParser and is intended
///to contain all TestArrayExpressionParser Unit Tests
///</summary>
[TestClass()]
public class TestArrayExpressionParser
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestForNonArray()
{
ArrayExpressionParser.ParseArrayExpression(Expression.Variable(typeof(int), "d"));
}
[TestMethod]
public void TestRunForNormalArray()
{
ArrayExpressionParser.ParseArrayExpression(Expression.Variable(typeof(int[]), "d"));
}
private QueryModel GetModel<T>(Expression<Func<T>> expr)
{
var parser = new QueryParser();
return parser.GetParsedQuery(expr.Body);
}
class dummyntup
{
public int run;
public int[] vals;
}
[TestMethod]
public void TestSubQueryExpression()
{
//var model = GetModel(() => (from q in new QueriableDummy<dummyntup>() from j in q.vals.Take(1) select j).Aggregate(0, (acc, va) => acc + 1));
var q = new dummyntup();
q.vals = new int[] { 1, 2, 3, 4, 5 };
var model = GetModel(() => (from j in q.vals select j).Take(1));
var sq = new SubQueryExpression(model);
var result = ArrayExpressionParser.ParseArrayExpression(sq);
Assert.IsNotNull(result);
GeneratedCode gc = new GeneratedCode();
CodeContext cc = new CodeContext();
var indexVar = result.AddLoop(gc, cc);
Assert.IsNotNull(indexVar);
Assert.AreEqual(0, gc.CodeBody.Statements.Count(), "No statement should have been added");
}
}
}
| lgpl-2.1 | C# |
ad9f728a9597c4d3cb26c965abe39709d6229eca | Fix App Version string | nikeee/HolzShots | src/HolzShots.Common/LibraryInformation.cs | src/HolzShots.Common/LibraryInformation.cs | using System;
namespace HolzShots.Common
{
public static class LibraryInformation
{
public const string Name = "HolzShots";
public const string PublisherName = "Niklas Mollenhauer";
public const string License = "GPL-3.0";
private const string ReleaseSuffix = "-beta"; // -beta
// 1.0.0-beta+exp.sha.5114f85
// 1.0.0-beta+2.deadbeef
// These info is filled by build script
public const string VersionFormal = "%VERSION%"; // 1.0.0
public const string CommitId = "%COMMIT-ID%"; // deadbeef
public const string CommitsSinceTag = "%COMMITS-SINCE-TAG%"; // 2
#if RELEASE && CI_BUILD
public static DateTime VersionDate = DateTime.ParseExact("%BUILD-DATE%", "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
#else
public static DateTime VersionDate = DateTime.Now;
#endif
public const string SemanticVersion = VersionFormal + ReleaseSuffix + "+" + CommitsSinceTag + "." + CommitId;
public const string SiteUrl = "https://holzshots.net";
public const string SourceUrl = "https://github.com/nikeee/HolzShots";
public const string IssuesUrl = SourceUrl + "/issues";
public const string FullVersionString = SemanticVersion;
public const string Copyright = PublisherName + " - " + License;
}
}
| using System;
namespace HolzShots.Common
{
public static class LibraryInformation
{
public const string Name = "HolzShots";
public const string PublisherName = "Niklas Mollenhauer";
public const string License = "GPL-3.0";
private const string ReleaseSuffix = "-beta"; // -beta
// 1.0.0-beta+exp.sha.5114f85
// 1.0.0-beta+2.deadbeef
// These info is filled by build script
public const string VersionFormal = "%VERSION%"; // 1.0.0
public const string CommitId = "%COMMIT-ID%"; // deadbeef
public const string CommitsSinceTag = "%COMMITS-SINCE-TAG%"; // 2
#if RELEASE && CI_BUILD
public static DateTime VersionDate = DateTime.ParseExact("%BUILD-DATE%", "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
#else
public static DateTime VersionDate = DateTime.Now;
#endif
public const string SemanticVersion = VersionFormal + ReleaseSuffix + "+" + CommitsSinceTag + "." + CommitId;
public const string SiteUrl = "https://holzshots.net";
public const string SourceUrl = "https://github.com/nikeee/HolzShots";
public const string IssuesUrl = SourceUrl + "/issues";
public const string FullVersionString = SemanticVersion + "+" + CommitId;
public const string Copyright = PublisherName + " - " + License;
}
}
| agpl-3.0 | C# |
5625457b233218abd17c4cf79df8375d2510e760 | Rename Double to DoubleField | laicasaane/VFW | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Doubles.cs | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Doubles.cs | using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public double DoubleField(double value)
{
return DoubleField(string.Empty, value);
}
public double DoubleField(string label, double value)
{
return DoubleField(label, value, null);
}
public double DoubleField(string label, string tooltip, double value)
{
return DoubleField(label, tooltip, value, null);
}
public double DoubleField(string label, double value, Layout option)
{
return DoubleField(label, string.Empty, value, option);
}
public double DoubleField(string label, string tooltip, double value, Layout option)
{
return DoubleField(GetContent(label, tooltip), value, option);
}
public abstract double DoubleField(GUIContent content, double value, Layout option);
}
}
| using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public double Double(double value)
{
return Double(string.Empty, value);
}
public double Double(string label, double value)
{
return Double(label, value, null);
}
public double Double(string label, string tooltip, double value)
{
return Double(label, tooltip, value, null);
}
public double Double(string label, double value, Layout option)
{
return Double(label, string.Empty, value, option);
}
public double Double(string label, string tooltip, double value, Layout option)
{
return Double(GetContent(label, tooltip), value, option);
}
public abstract double Double(GUIContent content, double value, Layout option);
}
} | mit | C# |
ce2d6175d2c9074c84c4a096ae110f68e0dd5cb6 | Handle MindComponent deletion: | space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/GameObjects/Components/Mobs/MindComponent.cs | Content.Server/GameObjects/Components/Mobs/MindComponent.cs | using Content.Server.GameObjects.Components.Observer;
using Content.Server.Mobs;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Mobs
{
/// <summary>
/// Stores a <see cref="Server.Mobs.Mind"/> on a mob.
/// </summary>
[RegisterComponent]
public class MindComponent : Component
{
/// <inheritdoc />
public override string Name => "Mind";
/// <summary>
/// The mind controlling this mob. Can be null.
/// </summary>
[ViewVariables]
public Mind Mind { get; private set; }
/// <summary>
/// True if we have a mind, false otherwise.
/// </summary>
[ViewVariables]
public bool HasMind => Mind != null;
/// <summary>
/// Don't call this unless you know what the hell you're doing.
/// Use <see cref="Mind.TransferTo(IEntity)"/> instead.
/// If that doesn't cover it, make something to cover it.
/// </summary>
public void InternalEjectMind()
{
Mind = null;
}
/// <summary>
/// Don't call this unless you know what the hell you're doing.
/// Use <see cref="Mind.TransferTo(IEntity)"/> instead.
/// If that doesn't cover it, make something to cover it.
/// </summary>
public void InternalAssignMind(Mind value)
{
Mind = value;
}
protected override void Shutdown()
{
base.Shutdown();
if (HasMind)
{
var visiting = Mind.VisitingEntity;
if (visiting != null)
{
if (visiting.TryGetComponent(out GhostComponent ghost))
{
ghost.CanReturnToBody = false;
}
Mind.TransferTo(visiting);
}
else
{
var ghost = Owner.EntityManager.SpawnEntity("MobObserver", Owner.Transform.GridPosition);
ghost.Name = Mind.CharacterName;
var ghostComponent = ghost.GetComponent<GhostComponent>();
ghostComponent.CanReturnToBody = false;
Mind.TransferTo(ghost);
}
}
}
}
}
| using Content.Server.Mobs;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Mobs
{
/// <summary>
/// Stores a <see cref="Server.Mobs.Mind"/> on a mob.
/// </summary>
[RegisterComponent]
public class MindComponent : Component
{
/// <inheritdoc />
public override string Name => "Mind";
/// <summary>
/// The mind controlling this mob. Can be null.
/// </summary>
[ViewVariables]
public Mind Mind { get; private set; }
/// <summary>
/// True if we have a mind, false otherwise.
/// </summary>
[ViewVariables]
public bool HasMind => Mind != null;
/// <summary>
/// Don't call this unless you know what the hell you're doing.
/// Use <see cref="Mind.TransferTo(IEntity)"/> instead.
/// If that doesn't cover it, make something to cover it.
/// </summary>
public void InternalEjectMind()
{
Mind = null;
}
/// <summary>
/// Don't call this unless you know what the hell you're doing.
/// Use <see cref="Mind.TransferTo(IEntity)"/> instead.
/// If that doesn't cover it, make something to cover it.
/// </summary>
public void InternalAssignMind(Mind value)
{
Mind = value;
}
public override void OnRemove()
{
base.OnRemove();
if (HasMind)
{
Mind.TransferTo(null);
}
}
}
}
| mit | C# |
b918349e51abbfd3d4208e8b23ecaf7e647a13f6 | set version number to 0.0.3 | wgross/Elementary.Hierarchy.Collections,wgross/Elementary.Hierarchy.Collections,wgross/Elementary.Hierarchy.Collections | Elementary.Hierarchy.Collections/Properties/AssemblyInfo.cs | Elementary.Hierarchy.Collections/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Elementary.Hierarchy.Collections")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Elementary.Hierarchy.Collections")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.3.0")]
[assembly: AssemblyFileVersion("0.0.3.0")] | using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Elementary.Hierarchy.Collections")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Elementary.Hierarchy.Collections")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | mit | C# |
cef86e7dfcb684c72f1bd496b4ae6c1213f424bb | Update CompositeAssemblyStringLocalizer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Localization/CompositeAssemblyStringLocalizer.cs | TIKSN.Core/Localization/CompositeAssemblyStringLocalizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Resources;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace TIKSN.Localization
{
public abstract class CompositeAssemblyStringLocalizer : CompositeStringLocalizer
{
private readonly ILogger<CompositeAssemblyStringLocalizer> _logger;
private readonly IResourceNamesCache resourceNamesCache;
private readonly Lazy<IEnumerable<IStringLocalizer>> localizers;
protected CompositeAssemblyStringLocalizer(IResourceNamesCache resourceNamesCache,
ILogger<CompositeAssemblyStringLocalizer> logger)
{
this.resourceNamesCache = resourceNamesCache;
this.localizers = new Lazy<IEnumerable<IStringLocalizer>>(this.CreateLocalizers, false);
this._logger = logger;
}
public override IEnumerable<IStringLocalizer> Localizers => this.localizers.Value;
protected virtual IEnumerable<Assembly> GetAssemblies()
{
yield return typeof(CompositeAssemblyStringLocalizer).GetTypeInfo().Assembly;
yield return typeof(LanguageLocalizationParameters).GetTypeInfo().Assembly;
yield return typeof(RegionLocalizationParameters).GetTypeInfo().Assembly;
}
private IEnumerable<IStringLocalizer> CreateLocalizers()
{
var result = new List<IStringLocalizer>();
var assemblies = this.GetAssemblies().ToArray();
foreach (var assembly in assemblies)
{
foreach (var manifestResourceName in assembly.GetManifestResourceNames())
{
if (manifestResourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
{
var resourceName = manifestResourceName.Substring(0, manifestResourceName.Length - 10);
var resourceManager = new ResourceManager(resourceName, assembly);
result.Add(new ResourceManagerStringLocalizer(resourceManager, assembly, resourceName,
this.resourceNamesCache, this._logger));
}
}
}
return result;
}
}
}
| using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Resources;
namespace TIKSN.Localization
{
public abstract class CompositeAssemblyStringLocalizer : CompositeStringLocalizer
{
private readonly IResourceNamesCache resourceNamesCache;
private Lazy<IEnumerable<IStringLocalizer>> localizers;
private readonly ILogger<CompositeAssemblyStringLocalizer> _logger;
protected CompositeAssemblyStringLocalizer(IResourceNamesCache resourceNamesCache, ILogger<CompositeAssemblyStringLocalizer> logger)
{
this.resourceNamesCache = resourceNamesCache;
localizers = new Lazy<IEnumerable<IStringLocalizer>>(CreateLocalizers, false);
_logger = logger;
}
public override IEnumerable<IStringLocalizer> Localizers
{
get
{
return localizers.Value;
}
}
protected virtual IEnumerable<Assembly> GetAssemblies()
{
yield return typeof(CompositeAssemblyStringLocalizer).GetTypeInfo().Assembly;
yield return typeof(LanguageLocalizationParameters).GetTypeInfo().Assembly;
yield return typeof(RegionLocalizationParameters).GetTypeInfo().Assembly;
}
private IEnumerable<IStringLocalizer> CreateLocalizers()
{
var result = new List<IStringLocalizer>();
var assemblies = GetAssemblies().ToArray();
foreach (var assembly in assemblies)
{
foreach (var manifestResourceName in assembly.GetManifestResourceNames())
{
if (manifestResourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
{
var resourceName = manifestResourceName.Substring(0, manifestResourceName.Length - 10);
var resourceManager = new ResourceManager(resourceName, assembly);
result.Add(new ResourceManagerStringLocalizer(resourceManager, assembly, resourceName, resourceNamesCache, _logger));
}
}
}
return result;
}
}
} | mit | C# |
32c12405357725e0d4ddf30009faf7b306083b47 | Fix failing R# code analysis | SeanFeldman/ServiceBus.AttachmentPlugin | src/ServiceBus.AttachmentPlugin.Tests/When_receiving_message.cs | src/ServiceBus.AttachmentPlugin.Tests/When_receiving_message.cs |
namespace ServiceBus.AttachmentPlugin.Tests
{
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;
using Xunit;
public class When_receiving_message : IClassFixture<AzureStorageEmulatorFixture>
{
[Fact]
public async Task Should_throw_exception_with_blob_path_for_found_that_cant_be_found()
{
var payload = "payload";
var bytes = Encoding.UTF8.GetBytes(payload);
var message = new Message(bytes)
{
MessageId = Guid.NewGuid().ToString(),
};
var sendingPlugin = new AzureStorageAttachment(new AzureStorageAttachmentConfiguration(
connectionString: "UseDevelopmentStorage=true", containerName: "attachments"));
await sendingPlugin.BeforeMessageSend(message);
var receivingPlugin = new AzureStorageAttachment(new AzureStorageAttachmentConfiguration(
connectionString: "UseDevelopmentStorage=true", containerName: "attachments-wrong-containers"));
var exception = await Assert.ThrowsAsync<Exception>(() => receivingPlugin.AfterMessageReceive(message));
Assert.Contains("attachments-wrong-containers", actualString: exception.Message);
Assert.Contains(message.UserProperties["$attachment.blob"].ToString(), actualString: exception.Message);
}
}
}
|
namespace ServiceBus.AttachmentPlugin.Tests
{
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;
using Xunit;
public class When_receiving_message : IClassFixture<AzureStorageEmulatorFixture>
{
[Fact]
public async Task Should_throw_exception_with_blob_path_for_found_that_cant_be_found()
{
var payload = "payload";
var bytes = Encoding.UTF8.GetBytes(payload);
var message = new Message(bytes)
{
MessageId = Guid.NewGuid().ToString(),
};
var sendingPlugin = new AzureStorageAttachment(new AzureStorageAttachmentConfiguration(
connectionString: "UseDevelopmentStorage=true", containerName: "attachments"));
await sendingPlugin.BeforeMessageSend(message);
var receivingPlugin = new AzureStorageAttachment(new AzureStorageAttachmentConfiguration(
connectionString: "UseDevelopmentStorage=true", containerName: "attachments-wrong-containers"));
var exception = await Assert.ThrowsAsync<Exception>(() => receivingPlugin.AfterMessageReceive(message));
Assert.Contains("attachments-wrong-containers", exception.Message);
Assert.Contains(message.UserProperties["$attachment.blob"].ToString(), exception.Message);
}
}
}
| mit | C# |
0ca4dd176ca35a9d43d0c4db292a7c2a99a90942 | Add some comments | marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS | src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginDto.cs | src/Umbraco.Infrastructure/Persistence/Dtos/ExternalLoginDto.cs | using System;
using NPoco;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Cms.Infrastructure.Persistence.Dtos
{
[TableName(TableName)]
[ExplicitColumns]
[PrimaryKey("Id")]
internal class ExternalLoginDto
{
public const string TableName = Cms.Core.Constants.DatabaseSchema.Tables.ExternalLogin;
[Column("id")]
[PrimaryKeyColumn]
public int Id { get; set; }
// TODO: This is completely missing a FK!!? ... IIRC that is because we want to change this to a GUID
// to support both members and users for external logins and that will not have any referential integrity
// This should be part of the members task for enabling external logins.
[Column("userId")]
[Index(IndexTypes.NonClustered)]
public int UserId { get; set; }
/// <summary>
/// Used to store the name of the provider (i.e. Facebook, Google)
/// </summary>
[Column("loginProvider")]
[Length(400)]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Index(IndexTypes.UniqueNonClustered, ForColumns = "loginProvider,userId", Name = "IX_" + TableName + "_LoginProvider")]
public string LoginProvider { get; set; }
/// <summary>
/// Stores the key the provider uses to lookup the login
/// </summary>
[Column("providerKey")]
[Length(4000)]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Index(IndexTypes.NonClustered, ForColumns = "loginProvider,providerKey", Name = "IX_" + TableName + "_ProviderKey")]
public string ProviderKey { get; set; }
[Column("createDate")]
[Constraint(Default = SystemMethods.CurrentDateTime)]
public DateTime CreateDate { get; set; }
/// <summary>
/// Used to store any arbitrary data for the user and external provider - like user tokens returned from the provider
/// </summary>
[Column("userData")]
[NullSetting(NullSetting = NullSettings.Null)]
[SpecialDbType(SpecialDbTypes.NTEXT)]
public string UserData { get; set; }
}
}
| using System;
using NPoco;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Cms.Infrastructure.Persistence.Dtos
{
[TableName(TableName)]
[ExplicitColumns]
[PrimaryKey("Id")]
internal class ExternalLoginDto
{
public const string TableName = Cms.Core.Constants.DatabaseSchema.Tables.ExternalLogin;
[Column("id")]
[PrimaryKeyColumn]
public int Id { get; set; }
// TODO: This is completely missing a FK!!? ... IIRC that is because we want to change this to a GUID
// to support both members and users for external logins and that will not have any referential integrity
// This should be part of the members task for enabling external logins.
[Column("userId")]
[Index(IndexTypes.NonClustered)]
public int UserId { get; set; }
[Column("loginProvider")]
[Length(400)]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Index(IndexTypes.UniqueNonClustered, ForColumns = "loginProvider,userId", Name = "IX_" + TableName + "_LoginProvider")]
public string LoginProvider { get; set; }
[Column("providerKey")]
[Length(4000)]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Index(IndexTypes.NonClustered, ForColumns = "loginProvider,providerKey", Name = "IX_" + TableName + "_ProviderKey")]
public string ProviderKey { get; set; }
[Column("createDate")]
[Constraint(Default = SystemMethods.CurrentDateTime)]
public DateTime CreateDate { get; set; }
/// <summary>
/// Used to store any arbitrary data for the user and external provider - like user tokens returned from the provider
/// </summary>
[Column("userData")]
[NullSetting(NullSetting = NullSettings.Null)]
[SpecialDbType(SpecialDbTypes.NTEXT)]
public string UserData { get; set; }
}
}
| mit | C# |
e961cd2b8428df9da68579a6448f2a272dae64c6 | Add FIXME note | arfbtwn/hyena,petejohanson/hyena,petejohanson/hyena,dufoli/hyena,arfbtwn/hyena,dufoli/hyena,GNOME/hyena,GNOME/hyena | Hyena/Hyena/DateTimeUtil.cs | Hyena/Hyena/DateTimeUtil.cs | //
// Utilities.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Hyena
{
public class DateTimeUtil
{
// FIXME I don't think having a local-unix-epoch makes any sense, I think we should be using
// all UTC values. Depending on the time of year in daylight savings timezones, the
// local-seconds-since-epoch value will differ, which will cause errors, no?
public static readonly DateTime LocalUnixEpoch = new DateTime (1970, 1, 1).ToLocalTime ();
public static DateTime ToDateTime (long time)
{
return FromTimeT (time);
}
public static long FromDateTime (DateTime time)
{
return ToTimeT (time);
}
private static long super_ugly_min_hack = -15768000000; // 500 yrs before epoch...ewww
public static DateTime FromTimeT (long time)
{
return (time <= super_ugly_min_hack) ? DateTime.MinValue : LocalUnixEpoch.AddSeconds (time);
}
public static long ToTimeT (DateTime time)
{
return (long)time.Subtract (LocalUnixEpoch).TotalSeconds;
}
public static string FormatDuration (long time) {
return FormatDuration (TimeSpan.FromSeconds (time));
}
public static string FormatDuration (TimeSpan time) {
return FormatDuration (time.Hours, time.Minutes, time.Seconds);
}
public static string FormatDuration (int hours, int minutes, int seconds) {
return (hours > 0 ?
String.Format ("{0}:{1:00}:{2:00}", hours, minutes, seconds) :
String.Format ("{0}:{1:00}", minutes, seconds));
}
}
}
| //
// Utilities.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Hyena
{
public class DateTimeUtil
{
public static readonly DateTime LocalUnixEpoch = new DateTime (1970, 1, 1).ToLocalTime ();
public static DateTime ToDateTime (long time)
{
return FromTimeT (time);
}
public static long FromDateTime (DateTime time)
{
return ToTimeT (time);
}
private static long super_ugly_min_hack = -15768000000; // 500 yrs before epoch...ewww
public static DateTime FromTimeT (long time)
{
return (time <= super_ugly_min_hack) ? DateTime.MinValue : LocalUnixEpoch.AddSeconds (time);
}
public static long ToTimeT (DateTime time)
{
return (long)time.Subtract (LocalUnixEpoch).TotalSeconds;
}
public static string FormatDuration (long time) {
return FormatDuration (TimeSpan.FromSeconds (time));
}
public static string FormatDuration (TimeSpan time) {
return FormatDuration (time.Hours, time.Minutes, time.Seconds);
}
public static string FormatDuration (int hours, int minutes, int seconds) {
return (hours > 0 ?
String.Format ("{0}:{1:00}:{2:00}", hours, minutes, seconds) :
String.Format ("{0}:{1:00}", minutes, seconds));
}
}
}
| mit | C# |
7852c9cf655681c6b2ec7ec38fa223b9b60428d2 | Fix bug with event placeholder image name that would make it not show on iOS | IrvingtonProgramming/InteractApp,IrvingtonProgramming/InteractApp,IrvingtonProgramming/InteractApp | InteractApp/Models/Event.cs | InteractApp/Models/Event.cs | using System;
using System.Linq;
using System.Collections.Generic;
using Parse;
namespace InteractApp
{
[ParseClassName ("Event")]
public class Event : ParseObject
{
public static readonly string DEFAULT_NAME = "An Error Has Occurred";
public static readonly string DEFAULT_LOCATION = "Hooli Headquarters";
public static readonly string DEFAULT_DESC = "If you are seeing this and you're a user, we probably screwed up. Please try again or contact Interact Club.";
public static readonly List<string> DEFAULT_TAGS = new List<string> () { "Error", "Event" };
[ParseFieldName ("ImageUri")]
public string ImageUri {
get {
if (String.IsNullOrEmpty (GetProperty<string> ())) {
return "event_placeholder.png";
}
return GetProperty<string> ();
}
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Name")]
public string Name {
get { return GetProperty<string> (); }
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Date")]
public DateTime Date {
get { return GetProperty<DateTime> (); }
private set { SetProperty<DateTime> (value); }
}
[ParseFieldName ("Location")]
public string Location {
get { return GetProperty<string> (); }
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Desc")]
public string Desc {
get { return GetProperty<string> (); }
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Tags")]
public IList<string> Tags {
get { return GetProperty<IList<string>> ().ToList (); }
private set { SetProperty<IList<string>> ((IList<string>)value); }
}
public string LocationDate { get { return string.Format ("{0} - {1}", this.Location, this.Date.ToShortDateString ()); } }
public Event ()
{
}
public Event (string EImageUri, string EName, DateTime EDate, string ELocation, string EDesc, List<string> ETags)
{
this.ImageUri = EImageUri;
this.Name = EName;
this.Date = EDate;
this.Location = ELocation;
this.Desc = EDesc;
this.Tags = ETags;
}
public static Event newEvent (string EImageUri, string EName, DateTime EDate, string ELocation, string EDesc, List<string> ETags)
{
Event e = new Event (EImageUri, EName, EDate, ELocation, EDesc, ETags);
// TODO: Add restrictions?
return e;
}
public static Event newErrorEvent (string ExceptionString)
{
if (ExceptionString != null) {
return new Event (null, DEFAULT_NAME, DateTime.Now, DEFAULT_LOCATION, ExceptionString, DEFAULT_TAGS);
}
return new Event (null, DEFAULT_NAME, DateTime.Now, DEFAULT_LOCATION, DEFAULT_DESC, DEFAULT_TAGS);
}
}
}
| using System;
using System.Linq;
using System.Collections.Generic;
using Parse;
namespace InteractApp
{
[ParseClassName ("Event")]
public class Event : ParseObject
{
public static readonly string DEFAULT_NAME = "An Error Has Occurred";
public static readonly string DEFAULT_LOCATION = "Hooli Headquarters";
public static readonly string DEFAULT_DESC = "If you are seeing this and you're a user, we probably screwed up. Please try again or contact Interact Club.";
public static readonly List<string> DEFAULT_TAGS = new List<string> () { "Error", "Event" };
[ParseFieldName ("ImageUri")]
public string ImageUri {
get {
if (String.IsNullOrEmpty (GetProperty<string> ())) {
return "event_placeholder.jpg";
}
return GetProperty<string> ();
}
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Name")]
public string Name {
get { return GetProperty<string> (); }
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Date")]
public DateTime Date {
get { return GetProperty<DateTime> (); }
private set { SetProperty<DateTime> (value); }
}
[ParseFieldName ("Location")]
public string Location {
get { return GetProperty<string> (); }
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Desc")]
public string Desc {
get { return GetProperty<string> (); }
private set { SetProperty<string> (value); }
}
[ParseFieldName ("Tags")]
public IList<string> Tags {
get { return GetProperty<IList<string>> ().ToList (); }
private set { SetProperty<IList<string>> ((IList<string>)value); }
}
public string LocationDate { get { return string.Format ("{0} - {1}", this.Location, this.Date.ToShortDateString ()); } }
public Event ()
{
}
public Event (string EImageUri, string EName, DateTime EDate, string ELocation, string EDesc, List<string> ETags)
{
this.ImageUri = EImageUri;
this.Name = EName;
this.Date = EDate;
this.Location = ELocation;
this.Desc = EDesc;
this.Tags = ETags;
}
public static Event newEvent (string EImageUri, string EName, DateTime EDate, string ELocation, string EDesc, List<string> ETags)
{
Event e = new Event (EImageUri, EName, EDate, ELocation, EDesc, ETags);
// TODO: Add restrictions?
return e;
}
public static Event newErrorEvent (string ExceptionString)
{
if (ExceptionString != null) {
return new Event (null, DEFAULT_NAME, DateTime.Now, DEFAULT_LOCATION, ExceptionString, DEFAULT_TAGS);
}
return new Event (null, DEFAULT_NAME, DateTime.Now, DEFAULT_LOCATION, DEFAULT_DESC, DEFAULT_TAGS);
}
}
}
| mit | C# |
359b180a76d3d470b75d2d77defada7a34a193ee | Remove InternalsVisibleTo because it causes tight coupling and type confliction. | msgpack/msgpack-cli,scopely/msgpack-cli,undeadlabs/msgpack-cli,modulexcite/msgpack-cli,modulexcite/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli,scopely/msgpack-cli | cli/src/MsgPack/Properties/AssemblyInfo.cs | cli/src/MsgPack/Properties/AssemblyInfo.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 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 --
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )]
[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library." )]
[assembly: AssemblyConfiguration( "Beta" )]
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010" )]
// TODO: use script. Major = Informational-Major, Minor = Informational-Minor, Build = Epoc days from 2010/1/1, Revision = Epoc minutes from 00:00:00
[assembly: AssemblyFileVersion( "0.2.0.0" )]
[assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )]
[assembly: AllowPartiallyTrustedCallers]
#if DEBUG || PERFORMANCE_TEST
[assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )]
#endif
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 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 --
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
[assembly: AssemblyTitle( "MessagePack for CLI(.NET/Mono)" )]
[assembly: AssemblyDescription( "MessagePack for CLI(.NET/Mono) packing/unpacking library." )]
[assembly: AssemblyConfiguration( "Beta" )]
[assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2010" )]
// TODO: use script. Major = Informational-Major, Minor = Informational-Minor, Build = Epoc days from 2010/1/1, Revision = Epoc minutes from 00:00:00
[assembly: AssemblyFileVersion( "0.2.0.0" )]
[assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )]
[assembly: AllowPartiallyTrustedCallers]
// For internal utilities related to emittions.
[assembly: InternalsVisibleTo( "MsgPack.Rpc.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )]
#if DEBUG || PERFORMANCE_TEST
[assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )]
#endif
| apache-2.0 | C# |
693b009372f3d90450065da0196c8c3818b3f93a | Fix error in test for Issue #172 | Thilas/commandline,Ehryk/commandline,Ehryk/commandline,Emergensys/commandline,anthonylangsworth/commandline,nausley/commandline,huoxudong125/commandline,Thilas/commandline,rmboggs/commandline,Emergensys/commandline,huoxudong125/commandline,rmboggs/commandline,kshanafelt/commandline,anthonylangsworth/commandline,nausley/commandline,kshanafelt/commandline | src/CommandLine.Tests/Fakes/FakeOptionsWithSequenceMinMaxEqual.cs | src/CommandLine.Tests/Fakes/FakeOptionsWithSequenceMinMaxEqual.cs | // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See doc/License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommandLine.Tests.Fakes
{
class FakeOptionsWithSequenceMinMaxEqual
{
[Value(0, Min=2, Max=2)]
public IEnumerable<string> StringSequence { get; set; }
}
}
| // Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See doc/License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommandLine.Tests.Fakes
{
class FakeOptionsWithSequenceMinMaxEqual
{
[Value(0, Min=2, Max=2)]
public IEnumerable<int> StringSequence { get; set; }
}
}
| mit | C# |
3282b4e0d545be6c5d8d230392a28eef22013776 | Improve readability and update link | Arcitectus/Sanderling | src/Sanderling/Sanderling.MemoryReading.Test/MemoryReadingDemo.cs | src/Sanderling/Sanderling.MemoryReading.Test/MemoryReadingDemo.cs | using Bib3;
using NUnit.Framework;
using Sanderling.ExploreProcessMeasurement;
using Sanderling.Parse;
using System;
using System.Linq;
namespace Sanderling.MemoryReading.Test
{
public class MemoryReadingDemo
{
[Test]
[Explicit("Do not include this method when running all tests. The only reason this is marked as a `Test` is to simplify execution from Visual Studio UI.")]
public void Demo_memory_reading_from_process_sample()
{
// To get a process sample of the EVE Online client to use with this reading approach,
// see the guide at https://forum.botengine.org/t/how-to-collect-samples-for-memory-reading-development/50
var windowsProcessMeasurementFilePath =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
.PathToFilesysChild("Sanderling.Process.Sample")
.PathToFilesysChild("my-eve-online-client-process-sample.zip");
var windowsProcessMeasurementZipArchive = System.IO.File.ReadAllBytes(windowsProcessMeasurementFilePath);
var windowsProcessMeasurement = BotEngine.Interface.Process.Snapshot.Extension.SnapshotFromZipArchive(windowsProcessMeasurementZipArchive);
var memoryReader = new BotEngine.Interface.Process.Snapshot.SnapshotReader(windowsProcessMeasurement?.ProcessSnapshot?.MemoryBaseAddressAndListOctet);
var parsedMemoryMeasurement = memoryReader.MemoryMeasurement().Parse();
// At this point, you will find in the "parsedMemoryMeasurement" variable the contents read from the process measurement as they would appear in the Sanderling API Explorer.
Console.WriteLine("Overview window read: " + (parsedMemoryMeasurement.WindowOverview?.Any() ?? false));
}
}
}
| using Bib3;
using NUnit.Framework;
using Sanderling.ExploreProcessMeasurement;
using Sanderling.Parse;
using System;
using System.Linq;
namespace Sanderling.MemoryReading.Test
{
public class MemoryReadingDemo
{
[Test]
[Explicit("Do not include this method when running all tests. The only reason this is marked as test is to simplify execution from Visual Studio UI.")]
public void Demo_memory_reading_from_process_sample()
{
// To obtain a process sample of the eve online client to use with this reading approach,
// see the guide at http://forum.botengine.org/t/collecting-samples-for-memory-reading-development/50
var sampleFilePath =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
.PathToFilesysChild("Sanderling.Process.Sample")
.PathToFilesysChild("my-eve-online-client-process-sample.zip");
var snapshotZipArchiv = Bib3.Glob.InhaltAusDataiMitPfaad(sampleFilePath);
var snapshot = BotEngine.Interface.Process.Snapshot.Extension.SnapshotFromZipArchive(snapshotZipArchiv);
var memoryReader = new BotEngine.Interface.Process.Snapshot.SnapshotReader(snapshot?.ProcessSnapshot?.MemoryBaseAddressAndListOctet);
var memoryMeasurement = memoryReader.MemoryMeasurement().Parse();
// At this point, you will find in the "memoryMeasurement" variable the contents read from the process sample as they would appear in the Sanderling API Explorer.
Console.WriteLine("Overview window read: " + (memoryMeasurement.WindowOverview?.Any() ?? false));
}
}
}
| apache-2.0 | C# |
5c95b9d312d2b75d785b398d8da2419edcf2ad88 | handle nulle | os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos | Core.ApplicationServices/Authorization/Policies/GlobalReadAccessPolicy.cs | Core.ApplicationServices/Authorization/Policies/GlobalReadAccessPolicy.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Core.DomainModel;
using Core.DomainModel.Advice;
using Core.DomainModel.AdviceSent;
using Core.DomainModel.Organization;
using Core.DomainServices.Extensions;
using Infrastructure.Services.Types;
namespace Core.ApplicationServices.Authorization.Policies
{
public class GlobalReadAccessPolicy : IAuthorizationPolicy<Type>
{
//NOTE: For types which cannot be bound to a scoped context (lack of knowledge) and has shared read access
private static readonly IReadOnlyDictionary<Type, bool> TypesWithGlobalReadAccess;
static GlobalReadAccessPolicy()
{
var typesWithGlobalRead =
new Dictionary<Type, bool>
{
{typeof(Advice),true},
{typeof(AdviceUserRelation),true},
{typeof(Text),true},
{typeof(HelpText),true},
{typeof(AdviceSent),true},
{typeof(GlobalConfig),true },
{typeof(ExternalReference),true },
{typeof(TaskRef),true }
};
//All base options are globally readable
typeof(Entity)
.Assembly
.GetTypes()
.Where(t => t.IsImplementationOfGenericType(typeof(OptionEntity<>)))
.Where(t => t.IsAbstract == false)
.Where(t => t.IsInterface == false)
.ToList()
.ForEach(t => typesWithGlobalRead.Add(t, true));
TypesWithGlobalReadAccess = new ReadOnlyDictionary<Type, bool>(typesWithGlobalRead);
}
public bool Allow(Type target)
{
return target
.FromNullable()
.Select(TypesWithGlobalReadAccess.ContainsKey)
.GetValueOrFallback(false);
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Core.DomainModel;
using Core.DomainModel.Advice;
using Core.DomainModel.AdviceSent;
using Core.DomainModel.Organization;
using Infrastructure.Services.Types;
namespace Core.ApplicationServices.Authorization.Policies
{
public class GlobalReadAccessPolicy : IAuthorizationPolicy<Type>
{
//NOTE: For types which cannot be bound to a scoped context (lack of knowledge) and has shared read access
private static readonly IReadOnlyDictionary<Type, bool> TypesWithGlobalReadAccess;
static GlobalReadAccessPolicy()
{
var typesWithGlobalRead =
new Dictionary<Type, bool>
{
{typeof(Advice),true},
{typeof(AdviceUserRelation),true},
{typeof(Text),true},
{typeof(HelpText),true},
{typeof(AdviceSent),true},
{typeof(GlobalConfig),true },
{typeof(ExternalReference),true },
{typeof(TaskRef),true }
};
//All base options are globally readable
typeof(Entity)
.Assembly
.GetTypes()
.Where(t => t.IsImplementationOfGenericType(typeof(OptionEntity<>)))
.Where(t => t.IsAbstract == false)
.Where(t => t.IsInterface == false)
.ToList()
.ForEach(t => typesWithGlobalRead.Add(t, true));
TypesWithGlobalReadAccess = new ReadOnlyDictionary<Type, bool>(typesWithGlobalRead);
}
public bool Allow(Type target)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
return TypesWithGlobalReadAccess.ContainsKey(target);
}
}
}
| mpl-2.0 | C# |
7fe94adca62e5431d86a5ef0245e567b31e341a3 | Update Oracle | sunkaixuan/SqlSugar | Src/Asp.Net/SqlSugar/Realization/Oracle/SqlBuilder/OracleInsertBuilder.cs | Src/Asp.Net/SqlSugar/Realization/Oracle/SqlBuilder/OracleInsertBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class OracleInsertBuilder : InsertBuilder
{
public override string SqlTemplate
{
get
{
return @"INSERT INTO {0}
({1})
VALUES
({2}) ;";
}
}
public override string ToSqlString()
{
var identities = this.EntityInfo.Columns.Where(it => it.OracleSequenceName.IsValuable()).ToList();
if (IsNoInsertNull)
{
DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).ToList();
}
var groupList = DbColumnInfoList.GroupBy(it => it.TableId).ToList();
var isSingle = groupList.Count() == 1;
string columnsString = string.Join(UtilConstants.Dot, groupList.First().Select(it => Builder.GetTranslationColumnName(it.DbColumnName)));
if (isSingle)
{
string columnParametersString = string.Join(UtilConstants.Dot, this.DbColumnInfoList.Select(it => Builder.SqlParameterKeyWord + it.DbColumnName));
if (identities.IsValuable()) {
columnsString = columnsString.TrimEnd(UtilConstants.DotChar) + UtilConstants.Dot + string.Join(UtilConstants.Dot, identities.Select(it=> Builder.GetTranslationColumnName(it.DbColumnName)));
columnParametersString = columnParametersString.TrimEnd(UtilConstants.DotChar) + UtilConstants.Dot + string.Join(UtilConstants.Dot, identities.Select(it => Builder.GetTranslationColumnName(it.OracleSequenceName)));
}
return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString);
}
else
{
StringBuilder batchInsetrSql = new StringBuilder();
int pageSize = 200;
int pageIndex = 1;
int totalRecord = groupList.Count;
int pageCount = (totalRecord + pageSize - 1) / pageSize;
while (pageCount >= pageIndex)
{
batchInsetrSql.AppendFormat(SqlTemplateBatch, GetTableNameString, columnsString);
int i = 0;
foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
{
var isFirst = i == 0;
if (!isFirst)
{
batchInsetrSql.Append(SqlTemplateBatchUnion);
}
batchInsetrSql.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value), Builder.GetTranslationColumnName(it.DbColumnName)))));
++i;
}
pageIndex++;
batchInsetrSql.Append("\r\n;\r\n");
}
return batchInsetrSql.ToString();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class OracleInsertBuilder : InsertBuilder
{
}
}
| apache-2.0 | C# |
7c2ab87dd34890faa3aa760d37877c1c3f269230 | Fix equality comparer failing | DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,peppy/osu-framework | osu.Framework/Localisation/LocalisationManager_LocalisedBindableString.cs | osu.Framework/Localisation/LocalisationManager_LocalisedBindableString.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;
namespace osu.Framework.Localisation
{
public partial class LocalisationManager
{
private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
{
private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();
private LocalisedString text;
public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
{
this.storage.BindTo(storage);
this.storage.BindValueChanged(_ => updateValue(), true);
}
private void updateValue()
{
string newText = text.Text;
if (text.ShouldLocalise && storage.Value != null)
newText = storage.Value.Get(newText);
if (text.Args != null && !string.IsNullOrEmpty(newText))
{
try
{
newText = string.Format(newText, text.Args);
}
catch (FormatException)
{
// Prevent crashes if the formatting fails. The string will be in a non-formatted state.
}
}
Value = newText;
}
public LocalisedString Original
{
set
{
if (text.Equals(value))
return;
text = value;
updateValue();
}
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;
namespace osu.Framework.Localisation
{
public partial class LocalisationManager
{
private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
{
private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();
private LocalisedString text;
public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
{
this.storage.BindTo(storage);
this.storage.BindValueChanged(_ => updateValue(), true);
}
private void updateValue()
{
string newText = text.Text;
if (text.ShouldLocalise && storage.Value != null)
newText = storage.Value.Get(newText);
if (text.Args != null && !string.IsNullOrEmpty(newText))
{
try
{
newText = string.Format(newText, text.Args);
}
catch (FormatException)
{
// Prevent crashes if the formatting fails. The string will be in a non-formatted state.
}
}
Value = newText;
}
public LocalisedString Original
{
set
{
if (text == value)
return;
text = value;
updateValue();
}
}
}
}
}
| mit | C# |
b2f2fced9a556fe4899c99397e2d795a2e46a1ae | Check IAllowAnonymousFilter in a simpler way. | SXTSOFT/aspnetboilerplate,4nonym0us/aspnetboilerplate,4nonym0us/aspnetboilerplate,ShiningRush/aspnetboilerplate,yuzukwok/aspnetboilerplate,zquans/aspnetboilerplate,zclmoon/aspnetboilerplate,andmattia/aspnetboilerplate,Nongzhsh/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ilyhacker/aspnetboilerplate,SXTSOFT/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,lemestrez/aspnetboilerplate,690486439/aspnetboilerplate,carldai0106/aspnetboilerplate,AlexGeller/aspnetboilerplate,jaq316/aspnetboilerplate,ilyhacker/aspnetboilerplate,lvjunlei/aspnetboilerplate,carldai0106/aspnetboilerplate,AlexGeller/aspnetboilerplate,ryancyq/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ZhaoRd/aspnetboilerplate,jaq316/aspnetboilerplate,carldai0106/aspnetboilerplate,ZhaoRd/aspnetboilerplate,4nonym0us/aspnetboilerplate,690486439/aspnetboilerplate,beratcarsi/aspnetboilerplate,lvjunlei/aspnetboilerplate,zquans/aspnetboilerplate,oceanho/aspnetboilerplate,berdankoca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,yuzukwok/aspnetboilerplate,oceanho/aspnetboilerplate,beratcarsi/aspnetboilerplate,zclmoon/aspnetboilerplate,virtualcca/aspnetboilerplate,lemestrez/aspnetboilerplate,ryancyq/aspnetboilerplate,berdankoca/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,Nongzhsh/aspnetboilerplate,SXTSOFT/aspnetboilerplate,ShiningRush/aspnetboilerplate,oceanho/aspnetboilerplate,690486439/aspnetboilerplate,zquans/aspnetboilerplate,jaq316/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,virtualcca/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,fengyeju/aspnetboilerplate,yuzukwok/aspnetboilerplate,fengyeju/aspnetboilerplate,lvjunlei/aspnetboilerplate,fengyeju/aspnetboilerplate,ShiningRush/aspnetboilerplate,ZhaoRd/aspnetboilerplate,s-takatsu/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,s-takatsu/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,virtualcca/aspnetboilerplate,andmattia/aspnetboilerplate,verdentk/aspnetboilerplate,luchaoshuai/aspnetboilerplate,verdentk/aspnetboilerplate,beratcarsi/aspnetboilerplate,s-takatsu/aspnetboilerplate,lemestrez/aspnetboilerplate,AlexGeller/aspnetboilerplate,verdentk/aspnetboilerplate,berdankoca/aspnetboilerplate,ilyhacker/aspnetboilerplate,andmattia/aspnetboilerplate | src/Abp.AspNetCore/AspNetCore/Mvc/Authorization/AbpAuthorizationFilter.cs | src/Abp.AspNetCore/AspNetCore/Mvc/Authorization/AbpAuthorizationFilter.cs | using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.Authorization;
using Abp.Dependency;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Abp.AspNetCore.Mvc.Authorization
{
//TODO: Register only actions which define AbpMvcAuthorizeAttribute..?
public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency
{
private readonly IAuthorizationHelper _authorizationHelper;
public AbpAuthorizationFilter(IAuthorizationHelper authorizationHelper)
{
_authorizationHelper = authorizationHelper;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
// Allow Anonymous skips all authorization
if (context.Filters.Any(item => item is IAllowAnonymousFilter))
{
return;
}
await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo());
}
}
} | using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.Authorization;
using Abp.Dependency;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Abp.AspNetCore.Mvc.Authorization
{
public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency
{
private readonly IAuthorizationHelper _authorizationHelper;
public AbpAuthorizationFilter(IAuthorizationHelper authorizationHelper)
{
_authorizationHelper = authorizationHelper;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
//Check IAllowAnonymous
if (context.ActionDescriptor
.GetMethodInfo()
.GetCustomAttributes(true)
.OfType<IAllowAnonymous>()
.Any())
{
return;
}
await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo());
}
}
} | mit | C# |
8c51dfc490426e12a9b000befcaecd50f77be504 | Use FCL instead of writing my own | Brightspace/D2L.Security.OAuth2 | D2L.Security.OAuth2/Provisioning/D2L.Security.AuthTokenProvisioning/Invocation/InvocationParameters.cs | D2L.Security.OAuth2/Provisioning/D2L.Security.AuthTokenProvisioning/Invocation/InvocationParameters.cs | using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace D2L.Security.AuthTokenProvisioning.Invocation {
/// <summary>
/// Configures an access token provision invocation
/// </summary>
internal sealed class InvocationParameters {
private readonly string m_authorization;
private readonly string m_scopes;
private readonly string m_assertionToken;
internal InvocationParameters(
string clientId,
string clientSecret,
IEnumerable<string> scopes,
string assertionToken
) {
m_authorization = WebUtility.UrlEncode( clientId ) + ":" + WebUtility.UrlEncode( clientSecret );
m_authorization = ToBase64( m_authorization );
m_authorization = "Basic " + m_authorization;
m_scopes = string.Join( " ", scopes );
m_scopes = WebUtility.UrlEncode( m_scopes );
m_assertionToken = assertionToken;
}
internal string Authorization {
get { return m_authorization; }
}
internal string Scope {
get { return m_scopes; }
}
internal string GrantType {
get { return Constants.AssertionGrant.GRANT_TYPE; }
}
internal string Assertion {
get { return m_assertionToken; }
}
private static string ToBase64( string me ) {
byte[] plainTextBytes = Encoding.UTF8.GetBytes( me );
return Convert.ToBase64String( plainTextBytes );
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace D2L.Security.AuthTokenProvisioning.Invocation {
/// <summary>
/// Configures an access token provision invocation
/// </summary>
internal sealed class InvocationParameters {
private readonly string m_authorization;
private readonly string m_scopes;
private readonly string m_assertionToken;
internal InvocationParameters(
string clientId,
string clientSecret,
IEnumerable<string> scopes,
string assertionToken
) {
m_authorization = WebUtility.UrlEncode( clientId ) + ":" + WebUtility.UrlEncode( clientSecret );
m_authorization = ToBase64( m_authorization );
m_authorization = "Basic " + m_authorization;
m_scopes = SerializeScopes( scopes );
m_scopes = WebUtility.UrlEncode( m_scopes );
m_assertionToken = assertionToken;
}
internal string Authorization {
get { return m_authorization; }
}
internal string Scope {
get { return m_scopes; }
}
internal string GrantType {
get { return Constants.AssertionGrant.GRANT_TYPE; }
}
internal string Assertion {
get { return m_assertionToken; }
}
private static string ToBase64( string me ) {
byte[] plainTextBytes = Encoding.UTF8.GetBytes( me );
return Convert.ToBase64String( plainTextBytes );
}
private static string SerializeScopes( IEnumerable<string> scopes ) {
const string separator = " ";
if( !scopes.Any() ) {
return string.Empty;
}
StringBuilder builder = new StringBuilder();
foreach( string scope in scopes ) {
builder.Append( scope );
builder.Append( separator );
}
string result = builder.ToString();
// remove last separator
result = result.Substring( 0, result.Length - separator.Length );
return result;
}
}
}
| apache-2.0 | C# |
682e7e8d1e8e3aa5a6952268c7b87c9332a73a59 | Change date inside assemblyinfo | mkoscielniak/SSMScripter | SSMScripter/AssemblyInfo.cs | SSMScripter/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
//
// 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("SSMScripter")]
[assembly: AssemblyDescription("SSMS Text Editor object scripter")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SSMScripter")]
[assembly: AssemblyCopyright("reVis (c) 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Revision
// Build Number
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.8")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified - the assembly cannot be signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine.
// (*) If the key file and a key name attributes are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP - that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the file is installed into the CSP and used.
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
//
// 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("SSMScripter")]
[assembly: AssemblyDescription("SSMS Text Editor object scripter")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SSMScripter")]
[assembly: AssemblyCopyright("reVis (c) 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Revision
// Build Number
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.8")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified - the assembly cannot be signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine.
// (*) If the key file and a key name attributes are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP - that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the file is installed into the CSP and used.
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
| mit | C# |
39c4c07d9797c539097366fd9d97f62382324329 | Add AsyncOperation.AsAsyncOperationObservable | TORISOUP/UniRx,ufcpp/UniRx,zillakot/UniRx,zhutaorun/UniRx,Useurmind/UniRx,cruwel/UniRx,cruwel/UniRx,ic-sys/UniRx,m-ishikawa/UniRx,zillakot/UniRx,juggernate/UniRx,InvertGames/UniRx,saruiwa/UniRx,endo0407/UniRx,juggernate/UniRx,cruwel/UniRx,OC-Leon/UniRx,OrangeCube/UniRx,neuecc/UniRx,Useurmind/UniRx,zillakot/UniRx,ppcuni/UniRx,ic-sys/UniRx,ataihei/UniRx,Useurmind/UniRx,ic-sys/UniRx,zhutaorun/UniRx,zhutaorun/UniRx,kimsama/UniRx,juggernate/UniRx | Assets/UniRx/Scripts/UnityEngineBridge/AsyncOperationExtensions.cs | Assets/UniRx/Scripts/UnityEngineBridge/AsyncOperationExtensions.cs | using System;
using System.Collections;
using UnityEngine;
namespace UniRx
{
public static partial class AsyncOperationExtensions
{
/// <summary>
/// If you needs return value, use AsAsyncOperationObservable instead.
/// </summary>
public static IObservable<AsyncOperation> AsObservable(this AsyncOperation asyncOperation, IProgress<float> progress = null)
{
return Observable.FromCoroutine<AsyncOperation>((observer, cancellation) => AsObservableCore(asyncOperation, observer, progress, cancellation));
}
// T: where T : AsyncOperation is ambigious with IObservable<T>.AsObservable
public static IObservable<T> AsAsyncOperationObservable<T>(this T asyncOperation, IProgress<float> progress = null)
where T : AsyncOperation
{
return Observable.FromCoroutine<T>((observer, cancellation) => AsObservableCore(asyncOperation, observer, progress, cancellation));
}
static IEnumerator AsObservableCore<T>(T asyncOperation, IObserver<T> observer, IProgress<float> reportProgress, CancellationToken cancel)
where T : AsyncOperation
{
while (!asyncOperation.isDone && !cancel.IsCancellationRequested)
{
if (reportProgress != null)
{
try
{
reportProgress.Report(asyncOperation.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
yield return null;
}
if (cancel.IsCancellationRequested) yield break;
observer.OnNext(asyncOperation);
observer.OnCompleted();
}
}
} | using System;
using System.Collections;
using UnityEngine;
namespace UniRx
{
public static partial class AsyncOperationExtensions
{
public static IObservable<AsyncOperation> AsObservable(this AsyncOperation asyncOperation, IProgress<float> progress = null)
{
return Observable.FromCoroutine<AsyncOperation>((observer, cancellation) => AsObservableCore(asyncOperation, observer, progress, cancellation));
}
static IEnumerator AsObservableCore(AsyncOperation asyncOperation, IObserver<AsyncOperation> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
while (!asyncOperation.isDone && !cancel.IsCancellationRequested)
{
if (reportProgress != null)
{
try
{
reportProgress.Report(asyncOperation.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
yield return null;
}
if (cancel.IsCancellationRequested) yield break;
observer.OnNext(asyncOperation);
observer.OnCompleted();
}
}
} | mit | C# |
c0e1e2c4efdd8ab6789cfa0dc78c8b453eff407f | make public | fandrei/AppMetrics,fandrei/AppMetrics | AgentService.PluginBase/Control.cs | AgentService.PluginBase/Control.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace AppMetrics.AgentService.PluginBase
{
public class Control
{
public static bool IsMasterRunning
{
get
{
var processFile = Process.GetCurrentProcess().MainModule.FileName.ToLower();
if (processFile.EndsWith(".vshost.exe"))
return true; // always true when running from VS
var masterProcesses = Process.GetProcesses("AppMetrics.AgentService.exe");
return (masterProcesses.Length > 0);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace AppMetrics.AgentService.PluginBase
{
class Control
{
public static bool IsMasterRunning
{
get
{
var processFile = Process.GetCurrentProcess().MainModule.FileName.ToLower();
if (processFile.EndsWith(".vshost.exe"))
return true; // always true when running from VS
var masterProcesses = Process.GetProcesses("AppMetrics.AgentService.exe");
return (masterProcesses.Length > 0);
}
}
}
}
| apache-2.0 | C# |
b8ac74946314c6dd5cb3da416b21c4cc57aebce5 | Remove Unused | kiyoaki/bitflyer-api-dotnet-client | BitFlyer.Apis/BitFlyerConstants.cs | BitFlyer.Apis/BitFlyerConstants.cs | using System;
namespace BitFlyer.Apis
{
internal static class BitFlyerConstants
{
internal static readonly Uri BaseUri = new Uri("https://api.bitflyer.jp/");
}
}
| using System;
namespace BitFlyer.Apis
{
internal static class BitFlyerConstants
{
internal static readonly Uri BaseUri = new Uri("https://api.bitflyer.jp/");
internal const string SubscribeKey = "sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f";
}
}
| mit | C# |
6d5d85a3c76715c7b5ad3a3fb89dc2f20db39ea0 | Build fix | OrleansContrib/Orleans.Providers.MongoDB | Orleans.Providers.MongoDB/StorageProviders/MongoStorageProvider.cs | Orleans.Providers.MongoDB/StorageProviders/MongoStorageProvider.cs | using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Providers.MongoDB.StorageProviders
{
public class MongoStorageProvider : BaseJSONStorageProvider
{
public const string ConnectionStringProperty = "ConnectionString";
public const string CollectionPrefixProperty = "CollectionPrefix";
public const string DatabaseNameProperty = "DatabaseProperty";
private string prefix;
public override Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
var mongoConnectionString = config.GetProperty(ConnectionStringProperty, string.Empty);
var mongoCollectionPrefix = config.GetProperty(CollectionPrefixProperty, string.Empty);
var mongoDatabaseName = config.GetProperty(DatabaseNameProperty, string.Empty);
prefix = mongoCollectionPrefix;
DataManager =
new MongoDataManager(
mongoConnectionString,
mongoDatabaseName);
return base.Init(name, providerRuntime, config);
}
protected override string ReturnGrainName(string grainType, GrainReference grainReference)
{
return prefix + base.ReturnGrainName(grainType, grainReference);
}
public virtual IJSONStateDataManager ReturnDataManager(string database, string connectionString)
{
return new MongoDataManager(connectionString, database);
}
}
} | using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Providers.MongoDB.StorageProviders
{
public class MongoStorageProvider : BaseJSONStorageProvider
{
public const string ConnectionStringProperty = "ConnectionString";
public const string CollectionPrefixProperty = "CollectionPrefix";
public const string DatabaseNameProperty = "DatabaseProperty";
private string prefix;
public override Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
var mongoConnectionString = config.GetProperty(ConnectionStringProperty, string.Empty);
var mongoCollectionPrefix = config.GetProperty(CollectionPrefixProperty, string.Empty);
var mongoDatabaseName = config.GetProperty(DatabaseNameProperty, string.Empty);
prefix = mongoCollectionPrefix;
DataManager =
new MongoDataManager(
mongoConnectionString,
mongoDatabaseName);
return base.Init(name, providerRuntime, config);
}
public override string ReturnGrainName(string grainType, GrainReference grainReference)
{
return prefix + base.ReturnGrainName(grainType, grainReference);
}
public virtual IJSONStateDataManager ReturnDataManager(string database, string connectionString)
{
return new MongoDataManager(connectionString, database);
}
}
} | mit | C# |
480bd7dbee0e2e24d7c46c6992eaea93aa5f4b2f | Update Program.cs | MShechtman/Test2 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//test 18.1
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//new test on master 2
}
}
}
| mit | C# |
aa2c56367acc0cbe2d5a42611809f55ac05f266a | Fix duplicate constructor | mstevenson/SeudoBuild | SeudoBuild.Modules/SeudoBuild.Modules.ZipArchive/ZipArchiveStep.cs | SeudoBuild.Modules/SeudoBuild.Modules.ZipArchive/ZipArchiveStep.cs | using System;
using System.IO;
using Ionic.Zip;
namespace SeudoBuild.Modules.ZipArchive
{
public class ZipArchiveStep : IArchiveStep
{
ZipArchiveConfig config;
Workspace workspace;
public string Type { get; } = "Zip File";
public ZipArchiveStep(ZipArchiveConfig config, Workspace workspace)
{
this.config = config;
this.workspace = workspace;
}
public ArchiveStepResults ExecuteStep(BuildSequenceResults buildInfo, Workspace workspace)
{
try
{
// Remove file extension in case it was accidentally included in the config data
string filename = Path.GetFileNameWithoutExtension(config.Filename);
// Replace in-line variables
filename = workspace.Macros.ReplaceVariablesInText(config.Filename);
// Sanitize
filename = filename.Replace(' ', '_');
filename = filename + ".zip";
string filepath = $"{workspace.ArchivesDirectory}/{filename}";
// Remove old file
if (File.Exists(filepath)) {
File.Delete(filepath);
}
BuildConsole.WriteLine($"Creating zip file {filename}");
// Save zip file
using (var zipFile = new ZipFile())
{
zipFile.AddDirectory(workspace.BuildOutputDirectory);
zipFile.Save(filepath);
}
BuildConsole.WriteLine("Zip file saved");
var results = new ArchiveStepResults { ArchiveFileName = filename, IsSuccess = true };
return results;
}
catch (Exception e)
{
return new ArchiveStepResults { IsSuccess = false, Exception = e };
}
}
}
}
| using System;
using System.IO;
using Ionic.Zip;
namespace SeudoBuild.Modules.ZipArchive
{
public class ZipArchiveStep : IArchiveStep
{
ZipArchiveConfig config;
Workspace workspace;
public ZipArchiveStep(ZipArchiveConfig config, Workspace workspace)
{
this.config = config;
}
public string Type { get; } = "Zip File";
public ZipArchiveStep(ZipArchiveConfig config, Workspace workspace)
{
this.config = config;
this.workspace = workspace;
}
public ArchiveStepResults ExecuteStep(BuildSequenceResults buildInfo, Workspace workspace)
{
try
{
// Remove file extension in case it was accidentally included in the config data
string filename = Path.GetFileNameWithoutExtension(config.Filename);
// Replace in-line variables
filename = workspace.Macros.ReplaceVariablesInText(config.Filename);
// Sanitize
filename = filename.Replace(' ', '_');
filename = filename + ".zip";
string filepath = $"{workspace.ArchivesDirectory}/{filename}";
// Remove old file
if (File.Exists(filepath)) {
File.Delete(filepath);
}
BuildConsole.WriteLine($"Creating zip file {filename}");
// Save zip file
using (var zipFile = new ZipFile())
{
zipFile.AddDirectory(workspace.BuildOutputDirectory);
zipFile.Save(filepath);
}
BuildConsole.WriteLine("Zip file saved");
var results = new ArchiveStepResults { ArchiveFileName = filename, IsSuccess = true };
return results;
}
catch (Exception e)
{
return new ArchiveStepResults { IsSuccess = false, Exception = e };
}
}
}
}
| mit | C# |
243d6242c99851a87d5e07c81eb6de6ce2c55e4d | Fix for initializing models from assembly. | monsterlabs/HumanRightsTracker,monsterlabs/HumanRightsTracker,monsterlabs/HumanRightsTracker,monsterlabs/HumanRightsTracker,monsterlabs/HumanRightsTracker | Main.cs | Main.cs | using System;
using System.Reflection;
using Gtk;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord;
using HumanRightsTracker.Models;
namespace HumanRightsTracker
{
class MainClass
{
public static void Main (string[] args)
{
XmlConfigurationSource config = new XmlConfigurationSource("Config/ARConfig.xml");
Assembly asm = Assembly.Load("Models");
ActiveRecordStarter.Initialize(asm, config);
Application.Init ();
LoginWindow win = new LoginWindow ();
win.Show ();
Application.Run ();
}
}
}
| using System;
using Gtk;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord;
using HumanRightsTracker.Models;
namespace HumanRightsTracker
{
class MainClass
{
public static void Main (string[] args)
{
XmlConfigurationSource config = new XmlConfigurationSource("Config/ARConfig.xml");
ActiveRecordStarter.Initialize(Models, config);
Application.Init ();
LoginWindow win = new LoginWindow ();
win.Show ();
Application.Run ();
}
}
}
| lgpl-2.1 | C# |
441934e5cbbfd3a93c0c5df5c5a2944b06c70a65 | Implement method to get version from CLI arguments #5 | Julien-Mialon/Cake.Storm,Julien-Mialon/Cake.Storm | fluent/src/Cake.Storm.Fluent/Extensions/ConfigurationExtensions.cs | fluent/src/Cake.Storm.Fluent/Extensions/ConfigurationExtensions.cs | using System.Collections.Generic;
using Cake.Common;
using Cake.Core;
using Cake.Storm.Fluent.Common;
using Cake.Storm.Fluent.DefaultTooling;
using Cake.Storm.Fluent.Interfaces;
using Cake.Storm.Fluent.Models;
namespace Cake.Storm.Fluent.Extensions
{
public static class ConfigurationExtensions
{
public static TConfiguration WithSolution<TConfiguration>(this TConfiguration configuration, string solutionPath)
where TConfiguration : IConfiguration
{
configuration.Add(ConfigurationConstants.SOLUTION_KEY, new SimpleConfigurationItem<string>(solutionPath));
return configuration;
}
public static TConfiguration WithBuildParameter<TConfiguration>(this TConfiguration configuration, string key, string value)
where TConfiguration : IConfiguration
{
if (configuration.TryGet<DictionaryOfListConfigurationItem<string, string>>(ConfigurationConstants.BUILD_PARAMETERS_KEY, out var configurationItem))
{
if(configurationItem.Values.TryGetValue(key, out var values))
{
values.Add(value);
}
else
{
configurationItem.Values.Add(key, new List<string>
{
value
});
}
}
else
{
configuration.Add(ConfigurationConstants.BUILD_PARAMETERS_KEY, new DictionaryOfListConfigurationItem<string, string>(key, value));
}
return configuration;
}
public static TConfiguration WithProject<TConfiguration>(this TConfiguration configuration, string projectPath)
where TConfiguration : IConfiguration
{
configuration.Add(ConfigurationConstants.PROJECT_KEY, new SimpleConfigurationItem<string>(projectPath));
return configuration;
}
public static TConfiguration WithVersion<TConfiguration>(this TConfiguration configuration, string version)
where TConfiguration : IConfiguration
{
configuration.Add(ConfigurationConstants.VERSION_KEY, new SimpleConfigurationItem<string>(version));
return configuration;
}
public static TConfiguration WithVersionFromArguments<TConfiguration>(this TConfiguration configuration, string argumentName = "args.version")
where TConfiguration : IConfiguration
{
if (configuration.Context.CakeContext.HasArgument(argumentName))
{
return configuration.WithVersion(configuration.Context.CakeContext.Argument<string>(argumentName));
}
configuration.LogAndThrow($"Missing parameter {argumentName} to get version from arguments");
return configuration;
}
public static TConfiguration UseDefaultTooling<TConfiguration>(this TConfiguration configuration) where TConfiguration : IConfiguration
{
configuration.AddStep(new CleanStep());
configuration.AddStep(new CreateBuildDirectoryStep());
configuration.AddStep(new CreateArtifactsDirectoryStep());
return configuration;
}
}
}
| using System.Collections.Generic;
using Cake.Storm.Fluent.Common;
using Cake.Storm.Fluent.DefaultTooling;
using Cake.Storm.Fluent.Interfaces;
using Cake.Storm.Fluent.Models;
namespace Cake.Storm.Fluent.Extensions
{
public static class ConfigurationExtensions
{
public static TConfiguration WithSolution<TConfiguration>(this TConfiguration configuration, string solutionPath)
where TConfiguration : IConfiguration
{
configuration.Add(ConfigurationConstants.SOLUTION_KEY, new SimpleConfigurationItem<string>(solutionPath));
return configuration;
}
public static TConfiguration WithBuildParameter<TConfiguration>(this TConfiguration configuration, string key, string value)
where TConfiguration : IConfiguration
{
if (configuration.TryGet<DictionaryOfListConfigurationItem<string, string>>(ConfigurationConstants.BUILD_PARAMETERS_KEY, out var configurationItem))
{
if(configurationItem.Values.TryGetValue(key, out var values))
{
values.Add(value);
}
else
{
configurationItem.Values.Add(key, new List<string>
{
value
});
}
}
else
{
configuration.Add(ConfigurationConstants.BUILD_PARAMETERS_KEY, new DictionaryOfListConfigurationItem<string, string>(key, value));
}
return configuration;
}
public static TConfiguration WithProject<TConfiguration>(this TConfiguration configuration, string projectPath)
where TConfiguration : IConfiguration
{
configuration.Add(ConfigurationConstants.PROJECT_KEY, new SimpleConfigurationItem<string>(projectPath));
return configuration;
}
public static TConfiguration WithVersion<TConfiguration>(this TConfiguration configuration, string version)
where TConfiguration : IConfiguration
{
configuration.Add(ConfigurationConstants.VERSION_KEY, new SimpleConfigurationItem<string>(version));
return configuration;
}
public static TConfiguration UseDefaultTooling<TConfiguration>(this TConfiguration configuration) where TConfiguration : IConfiguration
{
configuration.AddStep(new CleanStep());
configuration.AddStep(new CreateBuildDirectoryStep());
configuration.AddStep(new CreateArtifactsDirectoryStep());
return configuration;
}
}
}
| mit | C# |
cd532cde2d7852d94d8969dbed881c115baec6ae | Fix note masks not working | 2yangk23/osu,smoogipoo/osu,ZLima12/osu,ZLima12/osu,smoogipooo/osu,naoey/osu,DrabWeb/osu,peppy/osu,naoey/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,naoey/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu-new | osu.Game.Rulesets.Mania/Edit/Layers/Selection/Overlays/NoteMask.cs | osu.Game.Rulesets.Mania/Edit/Layers/Selection/Overlays/NoteMask.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.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class NoteMask : HitObjectMask
{
public NoteMask(DrawableNote note)
: base(note)
{
Scale = note.Scale;
AddInternal(new NotePiece());
note.HitObject.ColumnChanged += _ => Position = note.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
protected override void Update()
{
base.Update();
Size = HitObject.DrawSize;
Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.BottomLeft);
}
}
}
| // 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.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class NoteMask : HitObjectMask
{
public NoteMask(DrawableNote note)
: base(note)
{
Origin = Anchor.Centre;
Position = note.Position;
Size = note.Size;
Scale = note.Scale;
AddInternal(new NotePiece());
note.HitObject.ColumnChanged += _ => Position = note.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
}
}
| mit | C# |
7535d0f1a6e44abc74fe329b2d882ecea8e991e1 | update version info to 1.1.1 | HearthSim/HearthDb | HearthDb/Properties/AssemblyInfo.cs | HearthDb/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("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © Alexander Zeier 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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © Alexander Zeier 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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
6d55601a827fb0692271566995ad21c21dfa2c15 | Make SetDataAnnotationAttributeErrors only called once. | carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,andmattia/aspnetboilerplate,ilyhacker/aspnetboilerplate,zclmoon/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,Nongzhsh/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,zclmoon/aspnetboilerplate,beratcarsi/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,zclmoon/aspnetboilerplate,andmattia/aspnetboilerplate,andmattia/aspnetboilerplate,luchaoshuai/aspnetboilerplate,beratcarsi/aspnetboilerplate,virtualcca/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,Nongzhsh/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ilyhacker/aspnetboilerplate,virtualcca/aspnetboilerplate | src/Abp.Web.Common/Web/Validation/ActionInvocationValidatorBase.cs | src/Abp.Web.Common/Web/Validation/ActionInvocationValidatorBase.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Runtime.Validation.Interception;
namespace Abp.Web.Validation
{
public abstract class ActionInvocationValidatorBase : MethodInvocationValidator
{
private bool IsSetDataAnnotationAttributeErrors { get; set; }
protected IList<Type> ValidatorsToSkip => new List<Type>
{
typeof(DataAnnotationsValidator),
typeof(ValidatableObjectValidator)
};
protected ActionInvocationValidatorBase(IValidationConfiguration configuration, IIocResolver iocResolver)
: base(configuration, iocResolver)
{
}
public void Initialize(MethodInfo method)
{
base.Initialize(
method,
GetParameterValues(method)
);
}
protected override bool ShouldValidateUsingValidator(object validatingObject, Type validatorType)
{
// Skip DataAnnotations and IValidatableObject validation because MVC does this automatically
if (ValidatorsToSkip.Contains(validatorType))
{
return false;
}
return base.ShouldValidateUsingValidator(validatingObject, validatorType);
}
protected override void ValidateMethodParameter(ParameterInfo parameterInfo, object parameterValue)
{
// If action parameter value is null then set only ModelState errors
if (parameterValue != null)
{
base.ValidateMethodParameter(parameterInfo, parameterValue);
}
if (!IsSetDataAnnotationAttributeErrors)
{
SetDataAnnotationAttributeErrors();
IsSetDataAnnotationAttributeErrors = true;
}
}
protected virtual object[] GetParameterValues(MethodInfo method)
{
var parameters = method.GetParameters();
var parameterValues = new object[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
parameterValues[i] = GetParameterValue(parameters[i].Name);
}
return parameterValues;
}
protected abstract void SetDataAnnotationAttributeErrors();
protected abstract object GetParameterValue(string parameterName);
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Runtime.Validation.Interception;
namespace Abp.Web.Validation
{
public abstract class ActionInvocationValidatorBase : MethodInvocationValidator
{
protected IList<Type> ValidatorsToSkip => new List<Type>
{
typeof(DataAnnotationsValidator),
typeof(ValidatableObjectValidator)
};
protected ActionInvocationValidatorBase(IValidationConfiguration configuration, IIocResolver iocResolver)
: base(configuration, iocResolver)
{
}
public void Initialize(MethodInfo method)
{
base.Initialize(
method,
GetParameterValues(method)
);
}
protected override bool ShouldValidateUsingValidator(object validatingObject, Type validatorType)
{
// Skip DataAnnotations and IValidatableObject validation because MVC does this automatically
if (ValidatorsToSkip.Contains(validatorType))
{
return false;
}
return base.ShouldValidateUsingValidator(validatingObject, validatorType);
}
protected override void ValidateMethodParameter(ParameterInfo parameterInfo, object parameterValue)
{
// If action parameter value is null then set only ModelState errors
if (parameterValue != null)
{
base.ValidateMethodParameter(parameterInfo, parameterValue);
}
SetDataAnnotationAttributeErrors();
}
protected virtual object[] GetParameterValues(MethodInfo method)
{
var parameters = method.GetParameters();
var parameterValues = new object[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
parameterValues[i] = GetParameterValue(parameters[i].Name);
}
return parameterValues;
}
protected abstract void SetDataAnnotationAttributeErrors();
protected abstract object GetParameterValue(string parameterName);
}
}
| mit | C# |
bee03b39a1f180716587f18c261fb11333a5a51c | Update version number to 0.5.2. | beppler/trayleds | TrayLeds/Properties/AssemblyInfo.cs | TrayLeds/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrayLeds")]
[assembly: AssemblyDescription("Tray Notification Leds")]
[assembly: AssemblyProduct("TrayLeds")]
[assembly: AssemblyCopyright("Copyright © 2017 Carlos Alberto Costa Beppler")]
// 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("eecfb156-872b-498d-9a01-42d37066d3d4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.2.0")]
[assembly: AssemblyFileVersion("0.5.2.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrayLeds")]
[assembly: AssemblyDescription("Tray Notification Leds")]
[assembly: AssemblyProduct("TrayLeds")]
[assembly: AssemblyCopyright("Copyright © 2017 Carlos Alberto Costa Beppler")]
// 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("eecfb156-872b-498d-9a01-42d37066d3d4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.1.0")]
[assembly: AssemblyFileVersion("0.5.1.0")]
| mit | C# |
511509c6bef095b864399800a2159de544438e90 | Change client version | jvalladolid/recurly-client-net | Library/Properties/AssemblyInfo.cs | Library/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("Recurly Client Library")]
[assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recurly, Inc.")]
[assembly: AssemblyProduct("Recurly")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("25932cc0-45c7-4db4-b8d5-dd172555522c")]
// 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.0.3")]
[assembly: AssemblyFileVersion("1.4.0.3")]
| 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("Recurly Client Library")]
[assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recurly, Inc.")]
[assembly: AssemblyProduct("Recurly")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("25932cc0-45c7-4db4-b8d5-dd172555522c")]
// 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.0.2")]
[assembly: AssemblyFileVersion("1.4.0.2")]
| mit | C# |
7d32b4540def7a9cab3da8850540a334ec346aed | add functionality to hide second column if no items | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Views/stockportgov/Shared/TertiaryItems.cshtml | src/StockportWebapp/Views/stockportgov/Shared/TertiaryItems.cshtml | @using StockportWebapp.FeatureToggling
@model StockportWebapp.Models.Topic
@inject FeatureToggles FeatureToggles
<div class="subitems-tertiary-padding grid-100">
@{
var firstHalfOfItems = (int)Math.Ceiling((decimal)Model.TertiaryItems.Count() / 2);
}
<div class="subitems-tertiary-two-column">
<ul class="grid-50 mobile-grid-100 tablet-grid-100">
@foreach (var subItem in Model.TertiaryItems.Take(firstHalfOfItems)) {
<li>
<div class="subitem-tertiary">
<a href="@subItem.NavigationLink">
@subItem.Title
</a>
</div>
</li>
}
</ul>
@if (Model.TertiaryItems.Skip(firstHalfOfItems).Any()) {
<ul class="grid-50 mobile-grid-100 tablet-grid-100">
@foreach (var subItem in Model.TertiaryItems.Skip(firstHalfOfItems)) {
<li>
<div class="subitem-tertiary">
<a href="@subItem.NavigationLink">
@subItem.Title
</a>
</div>
</li>
}
@if (Model.TertiaryItems.Count() % 2 > 0) {
<li>
<div class="subitem-tertiary no-chevron">
</div>
</li>
}
</ul>
}
<div class="clearfix"></div>
</div>
</div> | @using StockportWebapp.FeatureToggling
@model StockportWebapp.Models.Topic
@inject FeatureToggles FeatureToggles
<div class="subitems-tertiary-padding grid-100">
@{
var firstHalfOfItems = (int)Math.Ceiling((decimal)Model.TertiaryItems.Count() / 2);
}
<div class="subitems-tertiary-two-column">
<ul class="grid-50 mobile-grid-100 tablet-grid-100">
@foreach (var subItem in Model.TertiaryItems.Take(firstHalfOfItems))
{
<li>
<div class="subitem-tertiary">
<a href="@subItem.NavigationLink">
@subItem.Title
</a>
</div>
</li>
}
</ul>
<ul class="grid-50 mobile-grid-100 tablet-grid-100">
@foreach (var subItem in Model.TertiaryItems.Skip(firstHalfOfItems))
{
<li>
<div class="subitem-tertiary">
<a href="@subItem.NavigationLink">
@subItem.Title
</a>
</div>
</li>
}
@if (Model.TertiaryItems.Skip(firstHalfOfItems).Any() && (Model.TertiaryItems.Count() % 2 > 0))
{
<li>
<div class="subitem-tertiary no-chevron">
</div>
</li>
}
</ul>
<div class="clearfix"></div>
</div>
</div> | mit | C# |
b8c66b23b2e1bbc88e1c9098221990f9694af77d | correct checkers sequence | Olorin71/RetreatCode,Olorin71/RetreatCode | c#/TexasHoldEmSolution/TexasHoldEm/Internals/HandInvestigator.cs | c#/TexasHoldEmSolution/TexasHoldEm/Internals/HandInvestigator.cs | using System;
using System.Collections.Generic;
using TexasHoldEm.Interfaces;
namespace TexasHoldEm.Internals
{
internal class HandInvestigator : IHandInvestigator
{
private IList<CheckerBase> checkers = new List<CheckerBase>();
private ComparerHelper comparer;
public HandInvestigator(ComparerHelper comparer)
{
this.comparer = comparer;
}
public IBestPossibleHand LocateBestHand(IEnumerable<ICard> theHoleCards, IEnumerable<ICard> theCommunityCards)
{
IList<ICard> cards = CreateCardsList(theHoleCards, theCommunityCards);
CheckerData data = new CheckerData(cards);
CreateCheckers(data);
IBestPossibleHand hand = null;
foreach (CheckerBase checker in checkers)
{
hand = checker.Check();
if (hand != null)
{
break; ;
}
}
return hand;
}
private void CreateCheckers(CheckerData data)
{
// The checkers are added sorted by hand value, most valuable first.
checkers.Add(new FourOfAKindChecker(data, comparer));
checkers.Add(new FullHouseChecker(data, comparer));
checkers.Add(new ThreeOfAKindChecker(data, comparer));
checkers.Add(new TwoPairsChecker(data, comparer));
checkers.Add(new PairChecker(data, comparer));
}
private IList<ICard> CreateCardsList(IEnumerable<ICard> theHoleCards, IEnumerable<ICard> theCommunityCards)
{
IList<ICard> cards = new List<ICard>();
foreach (ICard card in theHoleCards)
{
cards.Add(card);
}
foreach (ICard card in theCommunityCards)
{
cards.Add(card);
}
return cards;
}
}
} | using System;
using System.Collections.Generic;
using TexasHoldEm.Interfaces;
namespace TexasHoldEm.Internals
{
internal class HandInvestigator : IHandInvestigator
{
private IList<CheckerBase> checkers = new List<CheckerBase>();
private ComparerHelper comparer;
public HandInvestigator(ComparerHelper comparer)
{
this.comparer = comparer;
}
public IBestPossibleHand LocateBestHand(IEnumerable<ICard> theHoleCards, IEnumerable<ICard> theCommunityCards)
{
IList<ICard> cards = CreateCardsList(theHoleCards, theCommunityCards);
CheckerData data = new CheckerData(cards);
CreateCheckers(data);
IBestPossibleHand hand = null;
foreach (CheckerBase checker in checkers)
{
hand = checker.Check();
if (hand != null)
{
break; ;
}
}
return hand;
}
private void CreateCheckers(CheckerData data)
{
// The checkers are added sorted by hand value, most valuable first.
checkers.Add(new FullHouseChecker(data, comparer));
checkers.Add(new FourOfAKindChecker(data, comparer));
checkers.Add(new ThreeOfAKindChecker(data, comparer));
checkers.Add(new TwoPairsChecker(data, comparer));
checkers.Add(new PairChecker(data, comparer));
}
private IList<ICard> CreateCardsList(IEnumerable<ICard> theHoleCards, IEnumerable<ICard> theCommunityCards)
{
IList<ICard> cards = new List<ICard>();
foreach (ICard card in theHoleCards)
{
cards.Add(card);
}
foreach (ICard card in theCommunityCards)
{
cards.Add(card);
}
return cards;
}
}
} | mit | C# |
7fe68ca1ac163eea336fa44b3e1d3319988c1e50 | read nested yaml | aloneguid/config,jsobell/config | src/Config.Net.Tests/Stores/YamlFileConfigStoreTest.cs | src/Config.Net.Tests/Stores/YamlFileConfigStoreTest.cs | using Config.Net.Stores;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace Config.Net.Tests.Stores
{
public class YamlFileConfigStoreTest : AbstractTestFixture
{
private YamlFileConfigStore _yaml;
public YamlFileConfigStoreTest()
{
var testFile = Path.Combine(BuildDir.FullName, "..", "..", "..", "..", "..", "appveyor.yml");
_yaml = new YamlFileConfigStore(testFile);
}
[Fact]
public void Can_read_simple_property()
{
string image = _yaml.Read("image");
Assert.Equal("Visual Studio 2017", image);
}
[Fact]
public void Can_read_nested_node()
{
string project = _yaml.Read("build.project");
Assert.Equal("src/Config.Net.sln", project);
}
}
} | using Config.Net.Stores;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace Config.Net.Tests.Stores
{
public class YamlFileConfigStoreTest : AbstractTestFixture
{
private YamlFileConfigStore _yaml;
public YamlFileConfigStoreTest()
{
var testFile = Path.Combine(BuildDir.FullName, "..", "..", "..", "..", "..", "appveyor.yml");
_yaml = new YamlFileConfigStore(testFile);
}
[Fact]
public void Can_read_simple_property()
{
string image = _yaml.Read("image");
Assert.Equal("Visual Studio 2017", image);
}
}
} | mit | C# |
85c875757219da92b49e4d3582def1653ae2c8f6 | Return true on click | smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,peppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu | osu.Game/Overlays/Comments/Buttons/ShowRepliesButton.cs | osu.Game/Overlays/Comments/Buttons/ShowRepliesButton.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Humanizer;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
namespace osu.Game.Overlays.Comments.Buttons
{
public class ShowRepliesButton : CommentRepliesButton
{
public readonly BindableBool Expanded = new BindableBool(true);
public ShowRepliesButton(int count)
{
Text = "reply".ToQuantity(count);
}
protected override void LoadComplete()
{
base.LoadComplete();
Expanded.BindValueChanged(expanded => SetIconDirection(expanded.NewValue), true);
}
protected override bool OnClick(ClickEvent e)
{
Expanded.Toggle();
return true;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Humanizer;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
namespace osu.Game.Overlays.Comments.Buttons
{
public class ShowRepliesButton : CommentRepliesButton
{
public readonly BindableBool Expanded = new BindableBool(true);
public ShowRepliesButton(int count)
{
Text = "reply".ToQuantity(count);
}
protected override void LoadComplete()
{
base.LoadComplete();
Expanded.BindValueChanged(expanded => SetIconDirection(expanded.NewValue), true);
}
protected override bool OnClick(ClickEvent e)
{
Expanded.Toggle();
return base.OnClick(e);
}
}
}
| mit | C# |
7a28b098ad0645340d18f5d9ff0a2b8ca536237b | reconfigure data base context | ramzzzay/PhoneBook,ramzzzay/PhoneBook | PhoneBook.Domain/Concrete/DBcon.cs | PhoneBook.Domain/Concrete/DBcon.cs | using Microsoft.AspNet.Identity.EntityFramework;
using PhoneBook.Domain.Abstract;
using PhoneBook.Domain.Entities;
namespace PhoneBook.Domain.Concrete
{
public class DBcon : IdentityDbContext<User>, IRepository
{
public DBcon() : base("DBcon", true)
{
Configuration.ProxyCreationEnabled = true;
Configuration.LazyLoadingEnabled = true;
}
public static DBcon Create()
{
return new DBcon();
}
}
} | using Microsoft.AspNet.Identity.EntityFramework;
using PhoneBook.Domain.Abstract;
using PhoneBook.Domain.Entities;
namespace PhoneBook.Domain.Concrete
{
public class DBcon : IdentityDbContext<User>, IRepository
{
public DBcon() : base("DBcon", false)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public static DBcon Create()
{
return new DBcon();
}
}
} | apache-2.0 | C# |
0deaa863da0b52cf848abb9e330998ce7ce316f0 | Add badge rule test | wbsimms/PracticeTime,wbsimms/PracticeTime,wbsimms/PracticeTime,wbsimms/PracticeTime | src/Web/PracticeTime.Web.Lib.Test/BadgeRules/OneManBandRuleTest.cs | src/Web/PracticeTime.Web.Lib.Test/BadgeRules/OneManBandRuleTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using PracticeTime.Web.DataAccess.Models;
using PracticeTime.Web.DataAccess.Repositories;
using PracticeTime.Web.Lib.BadgeRules;
namespace PracticeTime.Web.Lib.Test.BadgeRules
{
[TestClass]
public class OneManBandRuleTest
{
[TestMethod]
public void ConstructorTest()
{
var sessionRepository = new Mock<ISessionRepository>();
sessionRepository.Setup(x => x.GetAllForUser(It.IsAny<string>())).Returns(() => { return new List<Session>(); });
var badgeAwardRepository = new Mock<IBadgeAwardRepository>();
badgeAwardRepository.Setup(x => x.Add(It.IsAny<BadgeAward>())).Returns(() => { return new BadgeAward() { BadgeAwardId = 1 }; });
OneManBandRule rule = new OneManBandRule(sessionRepository.Object,badgeAwardRepository.Object);
Assert.IsNotNull(rule);
}
[TestMethod]
public void RuleNoBadgeTest()
{
var sessionRepository = new Mock<ISessionRepository>();
sessionRepository.Setup(x => x.GetAllForUser(It.IsAny<string>()))
.Returns(() =>
{
return new List<Session>()
{
new Session(){SessionId = 1,C_InstrumentId = 1},
new Session(){SessionId = 2,C_InstrumentId = 2},
new Session(){SessionId = 2,C_InstrumentId = 1},
};
});
var badgeAwardRepository = new Mock<IBadgeAwardRepository>();
badgeAwardRepository.Setup(x => x.Add(It.IsAny<BadgeAward>())).Returns(() => { return new BadgeAward() { BadgeAwardId = 1 }; }).Verifiable();
OneManBandRule rule = new OneManBandRule(sessionRepository.Object, badgeAwardRepository.Object);
ResponseModel response = new ResponseModel();
rule.Rule(new Session(){SessionId = 4,C_InstrumentId = 2},response);
Assert.IsFalse(response.HasNewBadges);
Assert.AreEqual(0,response.NewBadges.Count);
}
[TestMethod]
public void RuleTest()
{
var sessionRepository = new Mock<ISessionRepository>();
sessionRepository.Setup(x => x.GetAllForUser(It.IsAny<string>()))
.Returns(() =>
{
return new List<Session>()
{
new Session(){SessionId = 1,C_InstrumentId = 1},
new Session(){SessionId = 2,C_InstrumentId = 2},
new Session(){SessionId = 3,C_InstrumentId = 3},
};
});
var badgeAwardRepository = new Mock<IBadgeAwardRepository>();
badgeAwardRepository.Setup(x => x.Add(It.IsAny<BadgeAward>())).Returns(() => { return new BadgeAward() { BadgeAwardId = 1 }; }).Verifiable();
OneManBandRule rule = new OneManBandRule(sessionRepository.Object, badgeAwardRepository.Object);
ResponseModel response = new ResponseModel();
rule.Rule(new Session() { SessionId = 4, C_InstrumentId = 2 }, response);
Assert.IsTrue(response.HasNewBadges);
Assert.AreEqual(1, response.NewBadges.Count);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using PracticeTime.Web.DataAccess.Models;
using PracticeTime.Web.DataAccess.Repositories;
using PracticeTime.Web.Lib.BadgeRules;
namespace PracticeTime.Web.Lib.Test.BadgeRules
{
[TestClass]
public class OneManBandRuleTest
{
[TestMethod]
public void ConstructorTest()
{
var sessionRepository = new Mock<ISessionRepository>();
sessionRepository.Setup(x => x.GetAllForUser(It.IsAny<string>())).Returns(() => { return new List<Session>(); });
var badgeAwardRepository = new Mock<IBadgeAwardRepository>();
badgeAwardRepository.Setup(x => x.Add(It.IsAny<BadgeAward>())).Returns(() => { return new BadgeAward() { BadgeAwardId = 1 }; });
OneManBandRule rule = new OneManBandRule(sessionRepository.Object,badgeAwardRepository.Object);
Assert.IsNotNull(rule);
}
}
}
| apache-2.0 | C# |
a249628cdc9170df4097ffa1b64f7643e128eec8 | add version comment | yasokada/unity-150905-dynamicDisplay | Assets/PanelDisplayControl.cs | Assets/PanelDisplayControl.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.1 2015/09/05
* - show/hide panels
*/
public class PanelDisplayControl : MonoBehaviour {
public GameObject PageSelect;
public GameObject PanelGroup;
private Vector2[] orgSize;
void Start() {
orgSize = new Vector2[4];
int idx=0;
foreach (Transform child in PanelGroup.transform) {
orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width;
orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height;
bool isOn = getIsOn (idx + 1);
DisplayPanel (idx + 1, isOn);
idx++;
}
}
bool getIsOn(int idx_st1) {
Toggle selected = null;
string name;
foreach (Transform child in PageSelect.transform) {
name = child.gameObject.name;
if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"...
selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle;
break;
}
}
return selected.isOn;
}
void DisplayPanel(int idx_st1, bool doShow)
{
GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ());
if (panel == null) {
return;
}
RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform;
Vector2 size = rect.sizeDelta;
if (doShow) {
size.x = orgSize[idx_st1 - 1].x;
size.y = orgSize[idx_st1 - 1].y;
} else {
size.x = 1;
size.y = 1;
}
rect.sizeDelta = size;
}
public void ToggleValueChanged(int idx_st1) {
bool isOn = getIsOn (idx_st1);
DisplayPanel (idx_st1, isOn);
Debug.Log (isOn.ToString ());
}
}
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PanelDisplayControl : MonoBehaviour {
public GameObject PageSelect;
public GameObject PanelGroup;
private Vector2[] orgSize;
void Start() {
orgSize = new Vector2[4];
int idx=0;
foreach (Transform child in PanelGroup.transform) {
orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width;
orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height;
idx++;
}
}
bool getIsOn(int idx_st1) {
Toggle selected = null;
string name;
foreach (Transform child in PageSelect.transform) {
name = child.gameObject.name;
if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"...
selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle;
break;
}
}
return selected.isOn;
}
void DisplayPanel(int idx_st1, bool doShow)
{
GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ());
if (panel == null) {
return;
}
RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform;
Vector2 size = rect.sizeDelta;
if (doShow) {
size.x = orgSize[idx_st1 - 1].x;
size.y = orgSize[idx_st1 - 1].y;
} else {
size.x = 1;
size.y = 1;
}
rect.sizeDelta = size;
}
public void ToggleValueChanged(int idx_st1) {
bool isOn = getIsOn (idx_st1);
DisplayPanel (idx_st1, isOn);
Debug.Log (isOn.ToString ());
}
}
| mit | C# |
1c03bfe9360e64ad52804c736288bb975941929d | Handle HighScore | yeonghoey/dotge | Assets/Scripts/GameManager.cs | Assets/Scripts/GameManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public GameObject titleCover;
public Text scoreText;
public GameObject prefabPlayer;
public GameObject prefabMaster;
public GameObject prefabScorer;
private float highScore;
private bool pressed;
private GameObject player;
private GameObject master;
private GameObject scorer;
void Start () {
highScore = 0.0f;
StartCoroutine (GameLoop ());
}
void Update () {
pressed = pressed || Input.anyKey;
}
IEnumerator GameLoop () {
while (true) {
yield return StartCoroutine (Wait ());
yield return StartCoroutine (Play ());
yield return StartCoroutine (End ());
}
}
IEnumerator Wait () {
titleCover.SetActive (true);
scoreText.text = Scorer.Format (highScore);
pressed = false;
while (!pressed) {
yield return null;
}
}
IEnumerator Play () {
titleCover.SetActive (false);
player = Instantiate (prefabPlayer);
master = Instantiate (prefabMaster);
scorer = Instantiate (prefabScorer);
scorer.GetComponent<Scorer> ().scoreText = scoreText;
yield return null;
while (player.activeInHierarchy) {
yield return null;
}
}
IEnumerator End () {
Destroy (player);
Destroy (master);
float lastScore = scorer.GetComponent<Scorer> ().Score;
Destroy (scorer);
if (lastScore > highScore) {
highScore = lastScore;
}
yield return new WaitForSeconds (3.0f);
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public GameObject titleCover;
public Text scoreText;
public GameObject prefabPlayer;
public GameObject prefabMaster;
public GameObject prefabScorer;
private float highScore;
private bool pressed;
private GameObject player;
private GameObject master;
private GameObject scorer;
void Start () {
highScore = 124;
StartCoroutine (GameLoop ());
}
void Update () {
pressed = pressed || Input.anyKey;
}
IEnumerator GameLoop () {
while (true) {
yield return StartCoroutine (Wait ());
yield return StartCoroutine (Play ());
yield return StartCoroutine (End ());
}
}
IEnumerator Wait () {
Reset ();
while (!pressed) {
yield return null;
}
}
IEnumerator Play () {
Init ();
Debug.Assert (player != null);
yield return null;
while (player.activeInHierarchy) {
yield return null;
}
}
IEnumerator End () {
Clear ();
yield return new WaitForSeconds (3.0f);
}
void Reset () {
pressed = false;
titleCover.SetActive (true);
scoreText.text = Scorer.Format (highScore);
}
void Init () {
titleCover.SetActive (false);
player = Instantiate (prefabPlayer);
master = Instantiate (prefabMaster);
scorer = Instantiate (prefabScorer);
scorer.GetComponent<Scorer> ().scoreText = scoreText;
}
void Clear () {
Destroy (player);
Destroy (master);
Destroy (scorer);
}
} | mit | C# |
ba134b2834480f770b10b506b7639a848015d38e | remove extra comment | ellisonch/CFGLib,ellisonch/CFGLib | CFGLibTest/RegressionTests.cs | CFGLibTest/RegressionTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using CFGLib;
namespace CFGLibTest {
[TestClass]
public class RegressionTests {
[TestMethod]
public void TestHugeWeights() {
var ntproductions = new List<BaseProduction> {
CFGParser.Production(@"<S> -> <A> <B> [3000000000]"),
CFGParser.Production(@"<S> -> <C> <A> [3000000000]"),
};
var tproductions = new List<BaseProduction> {
CFGParser.Production(@"<A> -> 'a'"),
CFGParser.Production(@"<B> -> 'b'"),
CFGParser.Production(@"<C> -> 'c'"),
};
var g = new CNFGrammar(ntproductions, tproductions, 3000000000, Nonterminal.Of("S"));
Helpers.AssertNear(1.0 / 3.0, g.Cyk(Sentence.FromLetters("")));
Helpers.AssertNear(1.0 / 3.0, g.Cyk(Sentence.FromLetters("ab")));
Helpers.AssertNear(1.0 / 3.0, g.Cyk(Sentence.FromLetters("ca")));
}
[TestMethod]
public void TestMissingStart() {
var productions = new List<BaseProduction> {
CFGParser.Production(@"<X_0> -> <X_0> <X_0>"),
CFGParser.Production(@"<X_0> -> 'a'"),
};
Grammar g = new Grammar(productions, Nonterminal.Of("S"));
CNFGrammar h = g.ToCNF();
}
[TestMethod]
public void TestFreshNames() {
var productions = new List<BaseProduction> {
CFGParser.Production(@"<S> -> 'a'"),
CFGParser.Production(@"<X_0> -> 'b'"),
};
Grammar g = new Grammar(productions, Nonterminal.Of("S"), false);
CNFGrammar h = g.ToCNF();
Assert.IsTrue(h.Accepts(Sentence.FromLetters("a")));
Assert.IsFalse(h.Accepts(Sentence.FromLetters("b")));
}
[TestMethod]
public void TestParserFailure() {
Helpers.AssertThrows<Exception>(() =>
CFGParser.Production(@"<X_0> -> X_0 X_0")
);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using CFGLib;
namespace CFGLibTest {
[TestClass]
public class RegressionTests {
[TestMethod]
public void TestHugeWeights() {
// S -> aSa | bSb | ε
var ntproductions = new List<BaseProduction> {
CFGParser.Production(@"<S> -> <A> <B> [3000000000]"),
CFGParser.Production(@"<S> -> <C> <A> [3000000000]"),
};
var tproductions = new List<BaseProduction> {
CFGParser.Production(@"<A> -> 'a'"),
CFGParser.Production(@"<B> -> 'b'"),
CFGParser.Production(@"<C> -> 'c'"),
};
var g = new CNFGrammar(ntproductions, tproductions, 3000000000, Nonterminal.Of("S"));
Helpers.AssertNear(1.0 / 3.0, g.Cyk(Sentence.FromLetters("")));
Helpers.AssertNear(1.0 / 3.0, g.Cyk(Sentence.FromLetters("ab")));
Helpers.AssertNear(1.0 / 3.0, g.Cyk(Sentence.FromLetters("ca")));
}
[TestMethod]
public void TestMissingStart() {
var productions = new List<BaseProduction> {
CFGParser.Production(@"<X_0> -> <X_0> <X_0>"),
CFGParser.Production(@"<X_0> -> 'a'"),
};
Grammar g = new Grammar(productions, Nonterminal.Of("S"));
CNFGrammar h = g.ToCNF();
}
[TestMethod]
public void TestFreshNames() {
var productions = new List<BaseProduction> {
CFGParser.Production(@"<S> -> 'a'"),
CFGParser.Production(@"<X_0> -> 'b'"),
};
Grammar g = new Grammar(productions, Nonterminal.Of("S"), false);
CNFGrammar h = g.ToCNF();
Assert.IsTrue(h.Accepts(Sentence.FromLetters("a")));
Assert.IsFalse(h.Accepts(Sentence.FromLetters("b")));
}
[TestMethod]
public void TestParserFailure() {
Helpers.AssertThrows<Exception>(() =>
CFGParser.Production(@"<X_0> -> X_0 X_0")
);
}
}
}
| mit | C# |
1ecb0b9668743215fd7b7227c97467ebdd189ccb | update xamarin sample | ABaboshin/FrequentDataMining | Xamarin/FrequentDataMining.XamarinSample/FrequentDataMining.XamarinSample/Controllers/AnalyzeViewController.cs | Xamarin/FrequentDataMining.XamarinSample/FrequentDataMining.XamarinSample/Controllers/AnalyzeViewController.cs | // MIT License.
// (c) 2015, Andrey Baboshin
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using FrequentDataMining.AgrawalFaster;
using FrequentDataMining.FPGrowth;
using SamplesCommon;
using UIKit;
namespace FrequentDataMining.XamarinSample
{
public partial class AnalyzeViewController : UIViewController
{
public AnalyzeViewController (IntPtr handle) : base (handle)
{
}
public List<List<BookAuthor>> Transactions {
get;
set;
}
public override void ViewDidLoad ()
{
FrequentDataMining.CommonюTypeRegister.Register<BookAuthor>(
(a, b) => a.Name.CompareTo(b.Name),
list => list.OrderBy(l => l.Name));
var fpGrowth = new FPGrowth<BookAuthor>();
var result = fpGrowth.ProcessTransactions((double)1/9, Transactions);
FrequentItemsTable.RegisterClassForCellReuse (typeof(FrequentItemTableViewCell), FrequentTableViewDelegate.CellIdentifier);
FrequentItemsTable.Source = new FrequentTableViewDelegate{
GetData = () => result.OrderByDescending(i=>i.Support).ToList()
};
var agrawal = new AgrawalFaster<BookAuthor>();
var ar = agrawal.Run(0.01, 0.01, result, Transactions.Count);
FrequentRulesTable.RegisterClassForCellReuse (typeof(FrequentRulesTableViewCell), FrequentRulesTableViewDelegate.CellIdentifier);
FrequentRulesTable.Source = new FrequentRulesTableViewDelegate{
GetData = () => ar.OrderByDescending(i=>i.Confidence).ToList()
};
}
}
}
| // MIT License.
// (c) 2015, Andrey Baboshin
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using FrequentDataMining.AgrawalFaster;
using FrequentDataMining.FPGrowth;
using SamplesCommon;
using UIKit;
namespace FrequentDataMining.XamarinSample
{
public partial class AnalyzeViewController : UIViewController
{
public AnalyzeViewController (IntPtr handle) : base (handle)
{
}
public List<List<BookAuthor>> Transactions {
get;
set;
}
public override void ViewDidLoad ()
{
var fpGrowth = new FPGrowth<BookAuthor>();
var result = fpGrowth.ProcessTransactions((double)1/9, Transactions);
FrequentItemsTable.RegisterClassForCellReuse (typeof(FrequentItemTableViewCell), FrequentTableViewDelegate.CellIdentifier);
FrequentItemsTable.Source = new FrequentTableViewDelegate{
GetData = () => result.OrderByDescending(i=>i.Support).ToList()
};
var agrawal = new AgrawalFaster<BookAuthor>();
var ar = agrawal.Run(0.01, 0.01, result, Transactions.Count);
FrequentRulesTable.RegisterClassForCellReuse (typeof(FrequentRulesTableViewCell), FrequentRulesTableViewDelegate.CellIdentifier);
FrequentRulesTable.Source = new FrequentRulesTableViewDelegate{
GetData = () => ar.OrderByDescending(i=>i.Confidence).ToList()
};
}
}
}
| mit | C# |
f2436f795d99ce3b6bb9275106a67167f70eee68 | Update Restaurant entity | IliaAnastassov/OdeToFood,IliaAnastassov/OdeToFood | OdeToFood/Entities/Restaurant.cs | OdeToFood/Entities/Restaurant.cs | using System.ComponentModel.DataAnnotations;
namespace OdeToFood.Entities
{
public enum CuisineType
{
None,
Italian,
Franch,
Japanese,
American
}
public class Restaurant
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter a name for the restaurant")]
[MaxLength(80)]
[Display(Name = "Restaurant Name")]
public string Name { get; set; }
public CuisineType Cuisine { get; set; }
}
}
| namespace OdeToFood.Entities
{
public enum CuisineType
{
None,
Italian,
Franch,
Japanese,
American
}
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public CuisineType Cuisine { get; set; }
}
}
| mit | C# |
e6008a2fa849d8c82d89144cc1c186cffb5f820e | tweak log | angeldnd/dap.core.csharp | Scripts/DapCore/core_/Factory.cs | Scripts/DapCore/core_/Factory.cs | using System;
namespace angeldnd.dap {
public static class Factory {
private static readonly Vars _Factories = new Vars(Env.Instance, "Factories");
public static bool Register<T>(string type) where T : class, IObject {
return Register(type, typeof(T));
}
public static bool Register(string type, Type newType) {
Type oldType = _Factories.GetValue<Type>(type);
if (oldType != null) {
if (oldType == newType) {
return true;
} else {
Log.Critical("Factory.Register: <{0}> Already Registered: {1} -> {2}",
type, oldType.FullName, newType.FullName);
return false;
}
}
return _Factories.AddVar(type, newType) != null;
}
public static Type GetDapType(string type) {
return _Factories.GetValue<Type>(type);
}
public static T New<T>(string type, params object[] values) where T : class, IObject {
Type oldType = _Factories.GetValue<Type>(type);
if (oldType != null) {
try {
object obj = Activator.CreateInstance(oldType, values);
if (obj is T) {
return (T)obj;
} else {
Log.Error("Factory.New: <{0}> Type Mismatched: {1} -> {2}",
type, typeof(T).FullName, obj.GetType().FullName);
}
} catch (Exception e) {
Log.Error("Factory.New: <{0}> {1} -> {2}", type, typeof(T).FullName, e);
}
} else {
Log.Error("Factory.New: <{0}> Unknown Type", type);
}
return null;
}
}
}
| using System;
namespace angeldnd.dap {
public static class Factory {
private static readonly Vars _Factories = new Vars(Env.Instance, "Factories");
public static bool Register<T>(string type) where T : class, IObject {
return Register(type, typeof(T));
}
public static bool Register(string type, Type newType) {
Type oldType = _Factories.GetValue<Type>(type);
if (oldType != null) {
if (oldType == newType) {
return true;
} else {
Log.Critical("Factory.Register: <{0}> Already Registered: {1} -> {2}",
type, oldType.FullName, newType.FullName);
return false;
}
}
return _Factories.AddVar(type, newType) != null;
}
public static Type GetDapType(string type) {
return _Factories.GetValue<Type>(type);
}
public static T New<T>(string type, params object[] values) where T : class, IObject {
Type oldType = _Factories.GetValue<Type>(type);
if (oldType != null) {
try {
object obj = Activator.CreateInstance(oldType, values);
if (obj is T) {
return (T)obj;
} else {
Log.Error("Factory.New: <{0}> Type Mismatched: {1} -> {2}",
type, typeof(T).FullName, obj.GetType().FullName);
}
} catch (Exception e) {
Log.Error("Factory.New: <{0}> {1} -> {2}", type, typeof(T).FullName, e);
}
} else {
Log.Error("Factory.New: {0} Unknown Type", type);
}
return null;
}
}
}
| mit | C# |
b787b57eb33f8dcf651bcc7968cb1ddd518210f2 | Revert "Minor performance improvement (cachine serialized objects)" | Siccity/UnityNodeEditorCore | Scripts/Editor/NodeEditorBase.cs | Scripts/Editor/NodeEditorBase.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEditor;
namespace XNodeEditor.Internal {
/// <summary> Handles caching of custom editor classes and their target types. Accessible with GetEditor(Type type) </summary>
public class NodeEditorBase<T, A, K> where A : Attribute, NodeEditorBase<T, A, K>.INodeEditorAttrib where T : NodeEditorBase<T,A,K> where K : ScriptableObject {
/// <summary> Custom editors defined with [CustomNodeEditor] </summary>
private static Dictionary<Type, T> editors;
public K target;
public SerializedObject serializedObject;
public static T GetEditor(K target) {
if (target == null) return null;
Type type = target.GetType();
T editor = GetEditor(type);
editor.target = target;
editor.serializedObject = new SerializedObject(target);
return editor;
}
private static T GetEditor(Type type) {
if (type == null) return null;
if (editors == null) CacheCustomEditors();
if (editors.ContainsKey(type)) return editors[type];
//If type isn't found, try base type
return GetEditor(type.BaseType);
}
private static void CacheCustomEditors() {
editors = new Dictionary<Type, T>();
//Get all classes deriving from NodeEditor via reflection
Type[] nodeEditors = XNodeEditor.NodeEditorWindow.GetDerivedTypes(typeof(T));
for (int i = 0; i < nodeEditors.Length; i++) {
var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false);
if (attribs == null || attribs.Length == 0) continue;
if (nodeEditors[i].IsAbstract) continue;
A attrib = attribs[0] as A;
editors.Add(attrib.GetInspectedType(), Activator.CreateInstance(nodeEditors[i]) as T);
}
}
public interface INodeEditorAttrib {
Type GetInspectedType();
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEditor;
namespace XNodeEditor.Internal {
/// <summary> Handles caching of custom editor classes and their target types. Accessible with GetEditor(Type type) </summary>
public class NodeEditorBase<T, A, K> where A : Attribute, NodeEditorBase<T, A, K>.INodeEditorAttrib where T : NodeEditorBase<T,A,K> where K : ScriptableObject {
/// <summary> Custom editors defined with [CustomNodeEditor] </summary>
private static Dictionary<Type, T> editors;
private static Dictionary<ScriptableObject, SerializedObject> serializeds;
public K target;
public SerializedObject serializedObject;
public static T GetEditor(K target) {
if (target == null) return null;
Type type = target.GetType();
T editor = GetEditor(type);
editor.target = target;
editor.serializedObject = GetSerialized(target);
return editor;
}
private static SerializedObject GetSerialized(K target) {
if (target == null) return null;
if (serializeds == null) serializeds = new Dictionary<ScriptableObject, SerializedObject>();
if (!serializeds.ContainsKey(target)) serializeds.Add(target, new SerializedObject(target));
return serializeds[target];
}
private static T GetEditor(Type type) {
if (type == null) return null;
if (editors == null) CacheCustomEditors();
if (editors.ContainsKey(type)) return editors[type];
//If type isn't found, try base type
return GetEditor(type.BaseType);
}
private static void CacheCustomEditors() {
editors = new Dictionary<Type, T>();
//Get all classes deriving from NodeEditor via reflection
Type[] nodeEditors = XNodeEditor.NodeEditorWindow.GetDerivedTypes(typeof(T));
for (int i = 0; i < nodeEditors.Length; i++) {
var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false);
if (attribs == null || attribs.Length == 0) continue;
if (nodeEditors[i].IsAbstract) continue;
A attrib = attribs[0] as A;
editors.Add(attrib.GetInspectedType(), Activator.CreateInstance(nodeEditors[i]) as T);
}
}
public interface INodeEditorAttrib {
Type GetInspectedType();
}
}
} | mit | C# |
a1d436afcfd931214646ebfa4fa5e42acb3c503e | Update SignIn.cshtml | Azure-Samples/active-directory-dotnet-demo-tdlr,Azure-Samples/active-directory-dotnet-demo-tdlr,AzureADSamples/azureroadshow-web,AzureADSamples/azureroadshow-web,AzureADSamples/azureroadshow-web,Azure-Samples/active-directory-dotnet-demo-tdlr | TDLR/Views/Account/SignIn.cshtml | TDLR/Views/Account/SignIn.cshtml |
@{
ViewBag.Title = "SignIn";
}
@Styles.Render("~/Content/signin")
<h2>SignIn</h2>
<div class="container-fluid">
<div class="row">
<center>
<div class="panel panel-default">
<div class="panel-body">
<p class="brand">tdlr;</p>
<form role="form">
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-sm" placeholder="Email Address">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">
</div>
<div class="form-group" id="aad-button">
<a class="btn btn-block btn-msft" href="/Account/SignIn/AAD?redirectUri=/tasks"><img src="~/img/microsoft-icon.png" class="msft-icon" />Sign in with your Work or School account</a>
</div>
<input type="submit" value="Sign in" class="btn btn-block btn-em">
<div class="form-group help container">
<div class="row">
<a class="help col-sm-5" href="/">Sign Up</a>
<a class="help col-sm-5" href="/Account/ForgotPassword">Forgot Password?</a>
</div>
</div>
</form>
</div>
</div>
</center>
</div>
</div>
|
@{
ViewBag.Title = "SignIn";
}
@Styles.Render("~/Content/signin")
<h2>SignIn</h2>
<div class="container-fluid">
<div class="row">
<center>
<div class="panel panel-default">
<div class="panel-body">
<p class="brand">tdlr;</p>
<form role="form">
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-sm" placeholder="Email Address">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">
</div>
<div class="form-group" id="aad-button">
<a class="btn btn-block btn-msft" href="/Account/SignIn/AAD?redirectUri=/tasks"><img src="~/img/microsoft-icon.png" class="msft-icon" />Sign in with your Work or School account</a>
</div>
<input type="submit" value="Sign in" class="btn btn-block btn-em">
<div class="form-group help container">
<div class="row">
<a class="help col-sm-5" href="/">Sign Up</a>
<a class="help col-sm-5" href="/Account/ForgotPassword">Forgot Pasword?</a>
</div>
</div>
</form>
</div>
</div>
</center>
</div>
</div>
| unknown | C# |
a6cc28d984f28fcda18c1ff25aaf9f6c87e58c5a | test compile module must specify parse options for langversion to work too | StackExchange/StackExchange.Precompilation,StackExchange/StackExchange.Precompilation | Test.Module/TestCompileModule.cs | Test.Module/TestCompileModule.cs | using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using StackExchange.Precompilation;
namespace Test.Module
{
public class TestCompileModule : ICompileModule
{
public void BeforeCompile(BeforeCompileContext context)
{
context.Diagnostics.Add(
Diagnostic.Create(
new DiagnosticDescriptor("TEST", "TEST", "Hello meta programming world!", "TEST", DiagnosticSeverity.Info, true),
Location.None));
context.Compilation = context.Compilation.AddSyntaxTrees(
SyntaxFactory.ParseSyntaxTree(@"
namespace Test.Module
{
public static class Extensions
{
public static T Dump<T>(this T i)
{
if (i != null)
{
System.Console.WriteLine(i);
}
return i;
}
}
}
", context.Arguments.ParseOptions));
}
public void AfterCompile(AfterCompileContext context)
{
}
}
}
| using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using StackExchange.Precompilation;
namespace Test.Module
{
public class TestCompileModule : ICompileModule
{
public void BeforeCompile(BeforeCompileContext context)
{
context.Diagnostics.Add(
Diagnostic.Create(
new DiagnosticDescriptor("TEST", "TEST", "Hello meta programming world!", "TEST", DiagnosticSeverity.Info, true),
Location.None));
context.Compilation = context.Compilation.AddSyntaxTrees(
SyntaxFactory.ParseSyntaxTree(@"
namespace Test.Module
{
public static class Extensions
{
public static T Dump<T>(this T i)
{
if (i != null)
{
System.Console.WriteLine(i);
}
return i;
}
}
}
"));
}
public void AfterCompile(AfterCompileContext context)
{
}
}
}
| mit | C# |
948fba37a213f43b341f5c06e8b3c5453c348544 | Clean up | ProfBird/CS295-Demos,ProfBird/CS295-Demos,ProfBird/CS295-Demos,ProfBird/CS295-Demos | Tic-Tac-Toe/TicTacToe/Startup.cs | Tic-Tac-Toe/TicTacToe/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Tic_Tac_Toe
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDistributedMemoryCache();
// Add services required for session state
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Tic_Tac_Toe
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDistributedMemoryCache();
// Add services required for session state
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
}
}
| mit | C# |
e53da8d5072aaf95913ad1da187aae8c43679e33 | Update App.xaml.cs | Althain2/CustomPrintScreen | CustomPrintScreen/App.xaml.cs | CustomPrintScreen/App.xaml.cs | using System.Windows;
namespace CustomPrintScreen
{
/// <summary>
/// Logika interakcji dla klasy App.xaml
/// </summary>
public partial class App : Application
{
}
}
| using System;
using System.Windows;
using System.Threading;
using System.Windows.Threading;
namespace CustomPrintScreen
{
public partial class App : Application
{
private MainWindow window;
public App(KeyboardHook keyboardHook)
{
if (keyboardHook == null)
throw new ArgumentNullException("keyboardHook");
keyboardHook.KeyCombinationPressed += KeyCombinationPressed;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
window = new MainWindow();
}
void KeyCombinationPressed(object sender, EventArgs e)
{
Dispatcher?.Invoke(DispatcherPriority.Normal, new ThreadStart(PrintScreenExe));
}
void PrintScreenExe()
{
Handler.CreateScreens();
MainWindow window = (MainWindow)Application.Current.MainWindow;
window.DrawApplication();
window.Show();
window.Activate();
}
}
}
| mit | C# |
2d59b5943b354ec5b0c23bb4f55e7cf4fe3f5c50 | Remove obsolete warning | clement911/ShopifySharp,nozzlegear/ShopifySharp | ShopifySharp/Entities/OrderRisk.cs | ShopifySharp/Entities/OrderRisk.cs | using Newtonsoft.Json;
using System;
namespace ShopifySharp
{
/// <summary>
/// An object representing a Shopify order risk.
/// </summary>
public class OrderRisk : ShopifyObject
{
/// <summary>
/// Use this flag when a fraud check is accompanied with a call to the Orders API to cancel the order. This will indicate to the merchant that this risk was severe enough to force cancellation of the order.
/// Note: Setting this parameter does not cancel the order. This must be done by the Orders API.
/// </summary>
[JsonProperty("cause_cancel")]
public bool? CauseCancel { get; set; }
/// <summary>
/// The ID of the checkout that the order risk belongs to.
/// </summary>
[JsonProperty("checkout_id")]
public long? CheckoutId { get; set; }
/// <summary>
/// States whether or not the risk is displayed. Valid values are "true" or "false".
/// </summary>
[JsonProperty("display")]
public bool? Display { get; set; }
/// <summary>
/// The id of the order the order risk belongs to
/// </summary>
[JsonProperty("order_id")]
public long? OrderId { get; set; }
/// <summary>
/// A message that should be displayed to the merchant to indicate the results of the fraud check.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// The recommended action given to the merchant. Known values are 'cancel', 'investigate' and 'accept'.
/// </summary>
[JsonProperty("recommendation")]
public string Recommendation { get; set; }
/// <summary>
/// A number between 0 and 1 indicating percentage likelihood of being fraud.
/// </summary>
[JsonProperty("score")]
public decimal? Score { get; set; }
/// <summary>
/// This indicates the source of the risk assessment. Known values are 'External', 'Internal' and 'Gateway'.
/// </summary>
[JsonProperty("source")]
public string Source { get; set; }
}
}
| using Newtonsoft.Json;
using System;
namespace ShopifySharp
{
/// <summary>
/// An object representing a Shopify order risk.
/// </summary>
public class OrderRisk : ShopifyObject
{
/// <summary>
/// Use this flag when a fraud check is accompanied with a call to the Orders API to cancel the order. This will indicate to the merchant that this risk was severe enough to force cancellation of the order.
/// Note: Setting this parameter does not cancel the order. This must be done by the Orders API.
/// </summary>
[JsonProperty("cause_cancel")]
public bool? CauseCancel { get; set; }
/// <summary>
/// WARNING: This is an undocumented value returned by the Shopify API. Use at your own risk.
/// </summary>
[JsonProperty("checkout_id"), Obsolete("This is an undocumented value returned by the Shopify API. Use at your own risk.")]
public long? CheckoutId { get; set; }
/// <summary>
/// States whether or not the risk is displayed. Valid values are "true" or "false".
/// </summary>
[JsonProperty("display")]
public bool? Display { get; set; }
/// <summary>
/// The id of the order the order risk belongs to
/// </summary>
[JsonProperty("order_id")]
public long? OrderId { get; set; }
/// <summary>
/// A message that should be displayed to the merchant to indicate the results of the fraud check.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// The recommended action given to the merchant. Known values are 'cancel', 'investigate' and 'accept'.
/// </summary>
[JsonProperty("recommendation")]
public string Recommendation { get; set; }
/// <summary>
/// A number between 0 and 1 indicating percentage likelihood of being fraud.
/// </summary>
[JsonProperty("score")]
public decimal? Score { get; set; }
/// <summary>
/// This indicates the source of the risk assessment. Known values are 'External', 'Internal' and 'Gateway'.
/// </summary>
[JsonProperty("source")]
public string Source { get; set; }
}
}
| mit | C# |
3ccf57accca0cbb4b5945ecdb8c7bf357515f180 | fix android bug | mgj/fetcher,mgj/fetcher | Fetcher.Droid/Services/FetcherWebService.cs | Fetcher.Droid/Services/FetcherWebService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using artm.Fetcher.Core.Services;
using Square.OkHttp;
using artm.Fetcher.Core.Models;
namespace artm.Fetcher.Droid.Services
{
public class FetcherWebService : IFetcherWebService
{
private OkHttpClient _client;
protected OkHttpClient Client
{
get
{
if (_client == null) _client = new OkHttpClient();
return _client;
}
}
public FetcherWebResponse DoPlatformWebRequest(Uri uri)
{
var request = new Request.Builder().Url(uri.OriginalString).Build();
var response = Client.NewCall(request).Execute();
if (response == null)
{
return new FetcherWebResponse()
{
IsSuccess = false,
Body = string.Empty
};
}
else
{
return new FetcherWebResponse()
{
IsSuccess = response.IsSuccessful,
Body = response.Body().String()
};
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using artm.Fetcher.Core.Services;
using Square.OkHttp;
using artm.Fetcher.Core.Models;
namespace artm.Fetcher.Droid.Services
{
public class FetcherWebService : IFetcherWebService
{
private OkHttpClient _client;
protected OkHttpClient Client
{
get
{
if (_client == null) _client = new OkHttpClient();
return _client;
}
}
public FetcherWebResponse DoPlatformWebRequest(Uri uri)
{
var request = new Request.Builder().Url(uri.OriginalString).Build();
var response = Client.NewCall(request).Execute();
return new FetcherWebResponse()
{
IsSuccess = response.IsSuccessful,
Body = response.Body().String()
};
}
}
} | apache-2.0 | C# |
bbbb04ce22bef3f83990bd11745774441426674e | fix unused var error on mono | Liwoj/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET | Src/Metrics.TestConsole/Program.cs | Src/Metrics.TestConsole/Program.cs |
using System;
using Metrics.Sampling;
using Metrics.Utils;
namespace Metrics.TestConsole
{
class Program
{
static void Main(string[] args)
{
Metric.Config.WithHttpEndpoint(@"http://localhost:1234/");
var maxValue = TimeUnit.Hours.Convert(TimeUnit.Nanoseconds, 1);
var histogram = new HdrHistogram.NET.Histogram(maxValue, 3);
Reservoir reservoir = new SyncronizedHdrReservoir(histogram);
var hdr = Metric.Advanced.Histogram("hdr", Unit.Calls, () => reservoir);
hdr.Update(1);
Console.WriteLine("press any key to exit");
Console.ReadKey();
}
}
}
|
using System;
using Metrics.Sampling;
using Metrics.Utils;
namespace Metrics.TestConsole
{
class Program
{
static void Main(string[] args)
{
Metric.Config.WithHttpEndpoint(@"http://localhost:1234/");
var maxValue = TimeUnit.Hours.Convert(TimeUnit.Nanoseconds, 1);
var histogram = new HdrHistogram.NET.Histogram(maxValue, 3);
var p5 = histogram.getValueAtPercentile(50);
Reservoir reservoir = new SyncronizedHdrReservoir(histogram);
var hdr = Metric.Advanced.Histogram("hdr", Unit.Calls, () => reservoir);
Console.WriteLine("press any key to exit");
Console.ReadKey();
}
}
}
| apache-2.0 | C# |
49ca2e558bca44548eef95aff42eab5d5c28c728 | Rename method | dirkrombauts/SpecLogLogoReplacer | UI/ViewModel/SpecLogTransformer.cs | UI/ViewModel/SpecLogTransformer.cs | using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Abstractions;
namespace SpecLogLogoReplacer.UI.ViewModel
{
public class SpecLogTransformer : ISpecLogTransformer
{
private readonly IFileSystem fileSystem;
public SpecLogTransformer()
: this (new FileSystem())
{
}
public SpecLogTransformer(IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void Transform(string pathToSpecLogFile, string pathToLogo)
{
if (pathToSpecLogFile == null)
{
throw new ArgumentNullException("pathToSpecLogFile");
}
if (pathToLogo == null)
{
throw new ArgumentNullException("pathToLogo");
}
pathToSpecLogFile = SanitizePath(pathToSpecLogFile);
pathToLogo = SanitizePath(pathToLogo);
var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile);
Image newLogo;
using (var stream = this.fileSystem.File.OpenRead(pathToLogo))
{
newLogo = Image.FromStream(stream);
}
var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png);
this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile);
}
private static string SanitizePath(string pathToSpecLogFile)
{
if (pathToSpecLogFile.StartsWith("\""))
{
pathToSpecLogFile = pathToSpecLogFile.Substring(1);
}
if (pathToSpecLogFile.EndsWith("\""))
{
pathToSpecLogFile = pathToSpecLogFile.Substring(0, pathToSpecLogFile.Length - 1);
}
return pathToSpecLogFile;
}
}
} | using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Abstractions;
namespace SpecLogLogoReplacer.UI.ViewModel
{
public class SpecLogTransformer : ISpecLogTransformer
{
private readonly IFileSystem fileSystem;
public SpecLogTransformer()
: this (new FileSystem())
{
}
public SpecLogTransformer(IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void Transform(string pathToSpecLogFile, string pathToLogo)
{
if (pathToSpecLogFile == null)
{
throw new ArgumentNullException("pathToSpecLogFile");
}
if (pathToLogo == null)
{
throw new ArgumentNullException("pathToLogo");
}
pathToSpecLogFile = SanitizePathToSpecLogFile(pathToSpecLogFile);
pathToLogo = SanitizePathToSpecLogFile(pathToLogo);
var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile);
Image newLogo;
using (var stream = this.fileSystem.File.OpenRead(pathToLogo))
{
newLogo = Image.FromStream(stream);
}
var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png);
this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile);
}
private static string SanitizePathToSpecLogFile(string pathToSpecLogFile)
{
if (pathToSpecLogFile.StartsWith("\""))
{
pathToSpecLogFile = pathToSpecLogFile.Substring(1);
}
if (pathToSpecLogFile.EndsWith("\""))
{
pathToSpecLogFile = pathToSpecLogFile.Substring(0, pathToSpecLogFile.Length - 1);
}
return pathToSpecLogFile;
}
}
} | isc | C# |
649d4093e0d278844f9f34b0fd3dbe7f1b2395ce | fix code style | AzureDay/2016-WebSite,AzureDay/2016-WebSite | TeamSpark.AzureDay.WebSite.Host/Views/Profile/My.cshtml | TeamSpark.AzureDay.WebSite.Host/Views/Profile/My.cshtml | @model TeamSpark.AzureDay.WebSite.Host.Models.Profile.MyProfileModel
<div class="boxedcontent">
@Html.Action("Header", "Layout")
<h1>Личный кабинет</h1>
<form method="POST" data-bind="submit: showModal">
<input name="email" readonly="readonly" disabled="disabled" value="@Model.Email"/>
<input name="firstName" data-bind="textInput: fName" placeholder="Имя" value="@Model.FirstName"/>
<input name="lastName" data-bind="textInput: lName" placeholder="Фамилия" value="@Model.LastName"/>
<input name="company" data-bind="textInput: company" placeholder="Компания" value="@Model.Company"/>
<button type="submit" data-bind="enable: isModelValid">Сохранить</button>
<div style="display: none;" data-bind="style: { display: isModelValid() ? 'none' : 'block' }">Все поля обязательны для заполнения</div>
</form>
@Html.Action("Footer", "Layout")
</div><!-- end boxedcontent -->
@Html.Partial("_ModalWait")
@section Scripts
{
@Scripts.Render("~/cdn/knockout/js")
<script>
$(document).ready(function() {
var profileModel = {
fName: ko.observable('@Model.FirstName'),
lName: ko.observable('@Model.LastName'),
company: ko.observable('@Model.Company')
};
profileModel.isModelValid = ko.computed(function() {
var fName = profileModel.fName();
var lName = profileModel.lName();
var company = profileModel.company();
return !!fName && !!lName && !!company;
});
profileModel.showModal = function() {
setTimeout(function () {
modal.showModal();
});
return true;
}
ko.applyBindings(profileModel);
});
</script>
} | @model TeamSpark.AzureDay.WebSite.Host.Models.Profile.MyProfileModel
<div class="boxedcontent">
@Html.Action("Header", "Layout")
<h1>Личный кабинет</h1>
<form method="POST" data-bind="submit: showModal">
<input name="email" readonly="readonly" disabled="disabled" value="@Model.Email" />
<input name="firstName" data-bind="textInput: fName" placeholder="Имя" value="@Model.FirstName" />
<input name="lastName" data-bind="textInput: lName" placeholder="Фамилия" value="@Model.LastName" />
<input name="company" data-bind="textInput: company" placeholder="Компания" value="@Model.Company" />
<button type="submit" data-bind="enable: isModelValid">Сохранить</button>
<div style="display: none;" data-bind="style: { display: isModelValid() ? 'none' : 'block' }">Все поля обязательны для заполнения</div>
</form>
@Html.Action("Footer", "Layout")
</div><!-- end boxedcontent -->
@Html.Partial("_ModalWait")
@section Scripts
{
@Scripts.Render("~/cdn/knockout/js")
<script>
$(document).ready(function() {
var profileModel = {
fName: ko.observable('@Model.FirstName'),
lName: ko.observable('@Model.LastName'),
company: ko.observable('@Model.Company')
};
profileModel.isModelValid = ko.computed(function() {
var fName = profileModel.fName();
var lName = profileModel.lName();
var company = profileModel.company();
return !!fName && !!lName && !!company;
});
profileModel.showModal = function() {
setTimeout(function () {
modal.showModal();
});
return true;
}
ko.applyBindings(profileModel);
});
</script>
} | mit | C# |
b1a3027edd578aaf986b328c9f2241fb4869d678 | set accurancy | atabaksahraei/ifn661 | healthbook/healthbook/xBeacon/Entity/xBeacon.cs | healthbook/healthbook/xBeacon/Entity/xBeacon.cs | using System;
namespace xBeacons
{
public class xBeacon
{
public string UUID { get; set; }
public int Major { get; set; }
public int Minor { get; set; }
public double Accuracy { get; private set; }
public ProximityType Proximity{ get; private set; }
public xBeacon ()
{
}
public xBeacon (string UUID, int major = 0, int minor = 0, double accuracy = 0.0d, ProximityType proximity = ProximityType.Unknow)
{
this.UUID = UUID;
this.Major = major;
this.Minor = minor;
this.Accuracy = accuracy;
this.Proximity = proximity;
}
public static xBeacon FromCLBeacon (CoreLocation.CLBeacon beacon)
{
ProximityType proximity = ProximityType.Unknow;
switch (beacon.Proximity) {
case CoreLocation.CLProximity.Immediate:
proximity = ProximityType.Immediate;
break;
case CoreLocation.CLProximity.Near:
proximity = ProximityType.Near;
break;
case CoreLocation.CLProximity.Far:
proximity = ProximityType.Far;
break;
}
return new xBeacon (beacon.ProximityUuid.AsString (), beacon.Major.Int32Value, beacon.Minor.Int32Value, beacon.Accuracy, proximity);
}
public override string ToString ()
{
return string.Format ("[xBeacon: UUID={0}, Major={1}, Minor={2}, Accuracy={3}, Proximity={4}]", UUID, Major, Minor, Accuracy, Proximity);
}
}
}
| using System;
namespace xBeacons
{
public class xBeacon
{
public string UUID { get; set; }
public int Major { get; set; }
public int Minor { get; set; }
public double Accuracy { get; private set; }
public ProximityType Proximity{ get; private set; }
public xBeacon ()
{
}
public xBeacon (string UUID, int major = 0, int minor = 0, double accuracy = 0.0d, ProximityType proximity = ProximityType.Unknow)
{
this.UUID = UUID;
this.Major = major;
this.Minor = minor;
this.Proximity = proximity;
}
public static xBeacon FromCLBeacon (CoreLocation.CLBeacon beacon)
{
ProximityType proximity = ProximityType.Unknow;
switch (beacon.Proximity) {
case CoreLocation.CLProximity.Immediate:
proximity = ProximityType.Immediate;
break;
case CoreLocation.CLProximity.Near:
proximity = ProximityType.Near;
break;
case CoreLocation.CLProximity.Far:
proximity = ProximityType.Far;
break;
}
return new xBeacon (beacon.ProximityUuid.AsString (), beacon.Major.Int32Value, beacon.Minor.Int32Value, beacon.Accuracy, proximity);
}
public override string ToString ()
{
return string.Format ("[xBeacon: UUID={0}, Major={1}, Minor={2}, Accuracy={3}, Proximity={4}]", UUID, Major, Minor, Accuracy, Proximity);
}
}
}
| mit | C# |
ad6b850652ca5c1e0dd8c944ea557287efdea130 | Update ETagComparerTests.cs | JonasSamuelsson/Handyman | src/Handyman.AspNetCore/test/Handyman.AspNetCore.Tests/ETagComparerTests.cs | src/Handyman.AspNetCore/test/Handyman.AspNetCore.Tests/ETagComparerTests.cs | using Shouldly;
using System.Collections.Generic;
using Xunit;
namespace Handyman.AspNetCore.Tests
{
public class ETagComparerTests
{
[Theory, MemberData(nameof(GetShouldCompareETagsParams))]
public void ShouldCompareETags(string eTag1, string eTag2, bool result)
{
ETagComparer.Instance.Equals(eTag1, eTag2).ShouldBe(result);
}
public static IEnumerable<object[]> GetShouldCompareETagsParams()
{
var eTags = new[] { "*", "W/\"01\"", "W/\"02\"", string.Empty, null };
for (var i = 0; i < eTags.Length; i++)
{
for (var j = 0; j < eTags.Length; j++)
{
var eTag1 = eTags[i];
var eTag2 = eTags[j];
var result = i == 0 || j == 0 || (i == j && (i == 1 || i == 2));
yield return new object[] { eTag1, eTag2, result };
}
}
}
[Theory, MemberData(nameof(GetShouldCompareETagToSqlServerRowVersionParams))]
public void ShouldCompareETagToSqlServerRowVersion(string eTag, byte[] rowVersion, bool result)
{
ETagComparer.Instance.EqualsSqlServerRowVersion(eTag, rowVersion).ShouldBe(result);
}
public static IEnumerable<object[]> GetShouldCompareETagToSqlServerRowVersionParams()
{
var rowVersion = ETagConverter.ToSqlServerRowVersion("W/\"01\"");
yield return new object[] { "*", rowVersion, true };
yield return new object[] { "W/\"01\"", rowVersion, true };
yield return new object[] { "W/\"02\"", rowVersion, false };
}
}
} | using Shouldly;
using System.Collections.Generic;
using Xunit;
namespace Handyman.AspNetCore.Tests
{
public class ETagComparerTests
{
[Theory, MemberData(nameof(GetShouldCompareETagsParams))]
public void ShouldCompareETags(string eTag1, string eTag2, bool result)
{
ETagComparer.Equals(eTag1, eTag2).ShouldBe(result);
}
public static IEnumerable<object[]> GetShouldCompareETagsParams()
{
var eTags = new[] { "*", "W/\"01\"", "W/\"02\"", string.Empty, null };
for (var i = 0; i < eTags.Length; i++)
{
for (var j = 0; j < eTags.Length; j++)
{
var eTag1 = eTags[i];
var eTag2 = eTags[j];
var result = i == 0 || j == 0 || (i == j && (i == 1 || i == 2));
yield return new object[] { eTag1, eTag2, result };
}
}
}
[Theory, MemberData(nameof(GetShouldCompareETagToSqlServerRowVersionParams))]
public void ShouldCompareETagToSqlServerRowVersion(string eTag, byte[] rowVersion, bool result)
{
ETagComparer.EqualsSqlServerRowVersion(eTag, rowVersion).ShouldBe(result);
}
public static IEnumerable<object[]> GetShouldCompareETagToSqlServerRowVersionParams()
{
var rowVersion = ETagConverter.ToSqlServerRowVersion("W/\"01\"");
yield return new object[] { "*", rowVersion, true };
yield return new object[] { "W/\"01\"", rowVersion, true };
yield return new object[] { "W/\"02\"", rowVersion, false };
}
}
} | mit | C# |
fa4777d568b864285aac5d9423914ee1b87a9e55 | Update RavenDB connection string name | jrusbatch/compilify,jrusbatch/compilify,vendettamit/compilify,vendettamit/compilify | Web/Infrastructure/DependencyInjection/RavenDbModule.cs | Web/Infrastructure/DependencyInjection/RavenDbModule.cs | using Autofac;
using Autofac.Integration.Mvc;
using Raven.Client;
using Raven.Client.Document;
namespace Compilify.Web.Infrastructure.DependencyInjection
{
public class RavenDbModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new DocumentStore { ConnectionStringName = "RAVENHQ_CONNECTION_STRING" }.Initialize())
.As<IDocumentStore>()
.SingleInstance();
builder.Register(x => x.Resolve<IDocumentStore>().OpenSession())
.As<IDocumentSession>()
.InstancePerHttpRequest();
builder.Register(x => x.Resolve<IDocumentStore>().OpenAsyncSession())
.As<IAsyncDocumentSession>()
.InstancePerHttpRequest();
}
}
} | using Autofac;
using Autofac.Integration.Mvc;
using Raven.Client;
using Raven.Client.Document;
namespace Compilify.Web.Infrastructure.DependencyInjection
{
public class RavenDbModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(c => new DocumentStore { ConnectionStringName = "RavenDB" }.Initialize())
.As<IDocumentStore>()
.SingleInstance();
builder.Register(x => x.Resolve<IDocumentStore>().OpenSession())
.As<IDocumentSession>()
.InstancePerHttpRequest();
builder.Register(x => x.Resolve<IDocumentStore>().OpenAsyncSession())
.As<IAsyncDocumentSession>()
.InstancePerHttpRequest();
}
}
} | mit | C# |
0829b19d3eafdfe4788019daf2713bf0d1a9f771 | Update src/lib/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingMemberInfo.cs | mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,Microsoft/dotnet-apiport,mjrousos/dotnet-apiport,Microsoft/dotnet-apiport | src/lib/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingMemberInfo.cs | src/lib/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingMemberInfo.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Fx.Portability.Reporting.ObjectModel
{
public class MissingMemberInfo : MissingInfo
{
private readonly HashSet<AssemblyInfo> _usedInAssemblies;
public IEnumerable<AssemblyInfo> UsedIn
{
get { return _usedInAssemblies.ToList().AsReadOnly(); }
}
public int Uses
{
get { return _usedInAssemblies.Count; }
}
public string MemberName { get; set; }
public IEnumerable<string> TargetStatus { get; set; }
public IEnumerable<Version> TargetVersionStatus { get; set; }
public void IncrementUsage(AssemblyInfo sourceAssembly)
{
_usedInAssemblies.Add(sourceAssembly);
}
public MissingMemberInfo(AssemblyInfo sourceAssembly, string docId, List<Version> targetStatus, string recommendedChanges)
: base(docId)
{
RecommendedChanges = recommendedChanges;
MemberName = docId;
TargetStatus = targetStatus?.Select(GenerateTargetStatusMessage).ToList() ?? Enumerable.Empty<string>();
TargetVersionStatus = new List<Version>(targetStatus ?? Enumerable.Empty<Version>());
_usedInAssemblies = new HashSet<AssemblyInfo>();
if (sourceAssembly != null)
{
_usedInAssemblies.Add(sourceAssembly);
}
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Fx.Portability.Reporting.ObjectModel
{
public class MissingMemberInfo : MissingInfo
{
private readonly HashSet<AssemblyInfo> _usedInAssemblies;
public IEnumerable<AssemblyInfo> UsedIn
{
get { return _usedInAssemblies; }
}
public int Uses
{
get { return _usedInAssemblies.Count; }
}
public string MemberName { get; set; }
public IEnumerable<string> TargetStatus { get; set; }
public IEnumerable<Version> TargetVersionStatus { get; set; }
public void IncrementUsage(AssemblyInfo sourceAssembly)
{
_usedInAssemblies.Add(sourceAssembly);
}
public MissingMemberInfo(AssemblyInfo sourceAssembly, string docId, List<Version> targetStatus, string recommendedChanges)
: base(docId)
{
RecommendedChanges = recommendedChanges;
MemberName = docId;
TargetStatus = targetStatus?.Select(GenerateTargetStatusMessage).ToList() ?? Enumerable.Empty<string>();
TargetVersionStatus = new List<Version>(targetStatus ?? Enumerable.Empty<Version>());
_usedInAssemblies = new HashSet<AssemblyInfo>();
if (sourceAssembly != null)
{
_usedInAssemblies.Add(sourceAssembly);
}
}
}
}
| mit | C# |
5d87d5c0449002611e59448d2353570a14e754c0 | Stop instructions on server example. | msoler8785/ExoMail | ExoMail.Smtp.Server/Program.cs | ExoMail.Smtp.Server/Program.cs | using ExoMail.Smtp.Server;
using ExoMail.Smtp.Interfaces;
using ExoMail.Smtp.Network;
using ExoMail.Smtp.Server.Authentication;
using ExoMail.Smtp.Server.IO;
using ExoMail.Smtp.Server.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Server
{
internal class Program
{
private static void Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var tasks = new List<Task>();
var servers = AppStart.InitializeServers();
foreach (var item in servers)
{
var task = Task.Run(async () =>
{
await item.Start(cancellationToken);
});
tasks.Add(task);
}
Console.WriteLine("Press any key to stop servers.");
Console.ReadLine();
Console.WriteLine("Server is shutting down...");
try
{
foreach (var item in servers)
{
Console.WriteLine("Attempting to stop server on port {0}", item.ServerConfig.Port);
cancellationTokenSource.Cancel();
}
// Wait 30 seconds for servers to stop or tear down the process.
Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(30));
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
foreach(var inner in ex.InnerExceptions)
{
if (inner.Message != null)
Console.WriteLine(inner.Message);
}
}
}
}
} | using ExoMail.Smtp.Server;
using ExoMail.Smtp.Interfaces;
using ExoMail.Smtp.Network;
using ExoMail.Smtp.Server.Authentication;
using ExoMail.Smtp.Server.IO;
using ExoMail.Smtp.Server.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Server
{
internal class Program
{
private static void Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var tasks = new List<Task>();
var servers = AppStart.InitializeServers();
foreach (var item in servers)
{
var task = Task.Run(async () =>
{
await item.Start(cancellationToken);
});
tasks.Add(task);
}
Console.ReadLine();
Console.WriteLine("Server is shutting down...");
try
{
foreach (var item in servers)
{
Console.WriteLine("Attempting to stop server on port {0}", item.ServerConfig.Port);
cancellationTokenSource.Cancel();
}
// Wait 30 seconds for servers to stop or tear down the process.
Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(30));
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
foreach(var inner in ex.InnerExceptions)
{
if (inner.Message != null)
Console.WriteLine(inner.Message);
}
}
}
}
} | mit | C# |
3f44f5c60e8fca9f82abbb37d03b359500214134 | Remove migration log output | NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,DrabWeb/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,2yangk23/osu,ZLima12/osu,EVAST9919/osu,NeoAdonis/osu,EVAST9919/osu,naoey/osu,johnneijzen/osu,naoey/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,DrabWeb/osu,naoey/osu,peppy/osu,johnneijzen/osu,ppy/osu,peppy/osu-new,UselessToucan/osu | osu.Game/Migrations/20180621044111_UpdateTaikoDefaultBindings.cs | osu.Game/Migrations/20180621044111_UpdateTaikoDefaultBindings.cs | using Microsoft.EntityFrameworkCore.Migrations;
using osu.Framework.Logging;
namespace osu.Game.Migrations
{
public partial class UpdateTaikoDefaultBindings : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM KeyBinding WHERE RulesetID = 1");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// we can't really tell if these should be restored or not, so let's just not do so.
}
}
}
| using Microsoft.EntityFrameworkCore.Migrations;
using osu.Framework.Logging;
namespace osu.Game.Migrations
{
public partial class UpdateTaikoDefaultBindings : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM KeyBinding WHERE RulesetID = 1");
Logger.Log("osu!taiko bindings have been reset due to new defaults", LoggingTarget.Runtime, LogLevel.Important);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// we can't really tell if these should be restored or not, so let's just not do so.
}
}
}
| mit | C# |
5dbe1e7fa25d21e431763e3b69ec0e7c3d943e81 | Update SuperReducedString.cs | shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms | hackerrank/SuperReducedString.cs | hackerrank/SuperReducedString.cs | /*Based on hackerrank question at https://www.hackerrank.com/challenges/reduced-string */
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
string s = Console.ReadLine();
Console.WriteLine(new Solution().reduce(s));
}
private string reduce(string s){
if(string.IsNullOrEmpty(s))
return("Empty String");
if(s.Length==1)
return(s);
if(s.Length==2)
if(s[0]==s[1])
return("Empty String");
else
return(s);
for(int i=0;i<s.Length-1;i++){
if(s[i]==s[i+1]){
string s2 = s.Remove(i,1);
return reduce(s2.Remove(i,1));
}
}
//Console.WriteLine("oops "+ s);
return s;
}
}
| /*Interim version, to be updated*/
/*Based on hackerrank question at https://www.hackerrank.com/challenges/reduced-string */
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
string s = Console.ReadLine();
Console.WriteLine(new Solution().reduce(s));
}
private string reduce(string s){
if(string.IsNullOrEmpty(s))
return("Empty String");
if(s.Length==1)
return(s);
if(s.Length==2)
if(s[0]==s[1])
return("Empty String");
else
return(s);
for(int i=0;i<s.Length-1;i++){
if(s[i]==s[i+1]){
string s2 = s.Remove(i,1);
return reduce(s2);
}
}
return "Empty String";
}
}
| mit | C# |
d5ab65a993b24ea1350082ce5fe43c6a3dc1a738 | add method to repository interface | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance/Data/IExpiredFundsRepository.cs | src/SFA.DAS.EmployerFinance/Data/IExpiredFundsRepository.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using SFA.DAS.EmployerFinance.Models.ExpiredFunds;
namespace SFA.DAS.EmployerFinance.Data
{
public interface IExpiredFundsRepository
{
Task Create(IEnumerable<ExpiredFund> expiredFunds);
}
}
|
namespace SFA.DAS.EmployerFinance.Data
{
public interface IExpiredFundsRepository
{
}
}
| mit | C# |
f7e2b5e355bde93fcac0fe33ae276bb8698243ba | Add cert-test action to help diagnose issues in azure | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Controllers/HomeController.cs | src/SFA.DAS.EmployerUsers.Web/Controllers/HomeController.cs | using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Mvc;
using Microsoft.Azure;
using SFA.DAS.EmployerUsers.WebClientComponents;
namespace SFA.DAS.EmployerUsers.Web.Controllers
{
public class HomeController : ControllerBase
{
public ActionResult Index()
{
return View();
}
public ActionResult CatchAll(string path)
{
return RedirectToAction("NotFound", "Error", new { path });
}
[AuthoriseActiveUser]
[Route("Login")]
public ActionResult Login()
{
return RedirectToAction("Index");
}
public ActionResult CertTest()
{
var certificatePath = string.Format(@"{0}\bin\DasIDPCert.pfx", AppDomain.CurrentDomain.BaseDirectory);
var codeCert = new X509Certificate2(certificatePath, "idsrv3test");
X509Certificate2 storeCert;
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
try
{
var thumbprint = CloudConfigurationManager.GetSetting("TokenCertificateThumbprint");
var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
storeCert = certificates.Count > 0 ? certificates[0] : null;
if (storeCert == null)
{
return Content($"Failed to load cert with thumbprint {thumbprint} from store");
}
}
finally
{
store.Close();
}
var details = new StringBuilder();
details.AppendLine("Code cert");
details.AppendLine("-------------------------");
details.AppendLine($"FriendlyName: {codeCert.FriendlyName}");
details.AppendLine($"PublicKey: {codeCert.GetPublicKeyString()}");
details.AppendLine($"HasPrivateKey: {codeCert.HasPrivateKey}");
details.AppendLine($"Thumbprint: {codeCert.Thumbprint}");
details.AppendLine();
details.AppendLine("Store cert");
details.AppendLine("-------------------------");
details.AppendLine($"FriendlyName: {storeCert.FriendlyName}");
details.AppendLine($"PublicKey: {storeCert.GetPublicKeyString()}");
details.AppendLine($"HasPrivateKey: {storeCert.HasPrivateKey}");
details.AppendLine($"Thumbprint: {storeCert.Thumbprint}");
return Content(details.ToString(), "text/plain");
}
}
} | using System.Web.Mvc;
using SFA.DAS.EmployerUsers.WebClientComponents;
namespace SFA.DAS.EmployerUsers.Web.Controllers
{
public class HomeController : ControllerBase
{
public ActionResult Index()
{
return View();
}
public ActionResult CatchAll(string path)
{
return RedirectToAction("NotFound", "Error", new {path});
}
[AuthoriseActiveUser]
[Route("Login")]
public ActionResult Login()
{
return RedirectToAction("Index");
}
}
} | mit | C# |
db3613461e7720a6a3c98c31f6ef745e28a322b5 | Fix compile bug in C# test. | timoc/scaliendb,timoc/scaliendb,timoc/scaliendb,scalien/scaliendb,timoc/scaliendb,scalien/scaliendb,timoc/scaliendb,scalien/scaliendb,scalien/scaliendb,scalien/scaliendb,timoc/scaliendb,timoc/scaliendb,timoc/scaliendb,scalien/scaliendb,timoc/scaliendb,scalien/scaliendb,scalien/scaliendb | src/Application/Client/CSharp/ScalienClientTest/Test.cs | src/Application/Client/CSharp/ScalienClientTest/Test.cs | using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
namespace Scalien
{
public class Test
{
// test entry point
public static void Main(string[] args)
{
//Client.SetTrace(true);
string[] controllers = { "127.0.0.1:7080" };
Client client = new Client(controllers);
Database db = client.GetDatabase("test");
Table table = db.GetTable("test");
//System.Random random = new System.Random();
//var value = "";
//while (value.Length < 10 * 1000)
// value += "" + random.Next();
//using (client.Begin())
//{
// for (var i = 0; i < 10*1000; i++)
// {
// var key = i.ToString("D9");
// table.Set(key, value);
// }
//}
StringRangeParams ps = new StringRangeParams().Prefix("00000006").StartKey("000000065").Backward();
foreach (string key in table.GetKeyIterator(ps))
{
System.Console.WriteLine(key);
}
var cnt = table.Count(ps);
System.Console.WriteLine(cnt);
System.Console.ReadLine();
}
public static void ListTest(Table table)
{
// create value
}
public static String GetString(uint length)
{
Random rnd = new System.Random();
var s = "";
while (s.Length < length)
s += "" + rnd.Next();
return s;
}
}
}
| using System;
using System.IO;
using System.Random;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
namespace Scalien
{
public class Test
{
// test entry point
public static void Main(string[] args)
{
//Client.SetTrace(true);
string[] controllers = { "127.0.0.1:7080" };
Client client = new Client(controllers);
Database db = client.GetDatabase("test");
Table table = db.GetTable("test");
//System.Random random = new System.Random();
//var value = "";
//while (value.Length < 10 * 1000)
// value += "" + random.Next();
//using (client.Begin())
//{
// for (var i = 0; i < 10*1000; i++)
// {
// var key = i.ToString("D9");
// table.Set(key, value);
// }
//}
StringRangeParams ps = new StringRangeParams().Prefix("00000006").StartKey("000000065").Backward();
foreach (string key in table.GetKeyIterator(ps))
{
System.Console.WriteLine(key);
}
var cnt = table.Count(ps);
System.Console.WriteLine(cnt);
System.Console.ReadLine();
}
public static void ListTest(Table table)
{
// create value
}
public static String GetString(uint length)
{
Random rnd = new System.Random();
var s = "";
while (s.Length < length)
s += "" + rnd.Next();
return s;
}
}
}
| agpl-3.0 | C# |
2b0a33b185f1a1babd7d57c8ec260c529206f851 | 优化参数集合的代码。 :pager: | Zongsoft/Zongsoft.Data | src/Common/Expressions/ParameterExpressionCollection.cs | src/Common/Expressions/ParameterExpressionCollection.cs | /*
* _____ ______
* /_ / ____ ____ ____ _________ / __/ /_
* / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/
* / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_
* /____/\____/_/ /_/\__ /____/\____/_/ \__/
* /____/
*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@qq.com>
*
* Copyright (C) 2015-2018 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.Data.
*
* Zongsoft.Data is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.Data is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.Data; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Data.Common.Expressions
{
public class ParameterExpressionCollection : Collections.NamedCollectionBase<ParameterExpression>
{
#region 私有变量
private int _index;
#endregion
#region 公共方法
public ParameterExpression Add(string name, System.Data.DbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input)
{
var parameter = Expression.Parameter(name, type, direction);
base.AddItem(parameter);
return parameter;
}
#endregion
#region 重写方法
protected override string GetKeyForItem(ParameterExpression item)
{
return item.Name;
}
protected override void AddItem(ParameterExpression item)
{
//处理下参数名为空或问号(?)的情况
if(string.IsNullOrEmpty(item.Name) || item.Name == ParameterExpression.Anonymous)
item.Name = "p" + System.Threading.Interlocked.Increment(ref _index).ToString();
//调用基类同名方法
base.AddItem(item);
}
#endregion
}
}
| /*
* _____ ______
* /_ / ____ ____ ____ _________ / __/ /_
* / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/
* / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_
* /____/\____/_/ /_/\__ /____/\____/_/ \__/
* /____/
*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@qq.com>
*
* Copyright (C) 2015-2018 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.Data.
*
* Zongsoft.Data is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.Data is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.Data; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Data.Common.Expressions
{
public class ParameterExpressionCollection : Collections.NamedCollectionBase<ParameterExpression>
{
#region 私有变量
private int _index;
#endregion
#region 公共方法
public ParameterExpression Add(string name, System.Data.DbType type, System.Data.ParameterDirection direction = System.Data.ParameterDirection.Input)
{
var parameter = Expression.Parameter(this.GetParameterName(name), type, direction);
base.AddItem(parameter);
return parameter;
}
#endregion
#region 重写方法
protected override string GetKeyForItem(ParameterExpression item)
{
return item.Name;
}
protected override void AddItem(ParameterExpression item)
{
//处理下参数名为空或问号(?)的情况
item.Name = this.GetParameterName(item.Name);
//调用基类同名方法
base.AddItem(item);
}
#endregion
#region 私有方法
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private string GetParameterName(string name)
{
if(string.IsNullOrEmpty(name) || name == ParameterExpression.Anonymous)
{
var index = System.Threading.Interlocked.Increment(ref _index);
return "p" + index.ToString();
}
return name;
}
#endregion
}
}
| lgpl-2.1 | C# |
13ca406f16b98551cc2613699fdb289d876be9fd | Test commit | optivem/optivem-commons-cs,optivem/immerest | src/Optivem.Commons.Parsing.Default/BaseNumberParser.cs | src/Optivem.Commons.Parsing.Default/BaseNumberParser.cs | using System;
using System.Globalization;
namespace Optivem.Commons.Parsing.Default
{
public abstract class BaseNumberParser<T> : BaseParser<T>
{
public BaseNumberParser(NumberStyles? numberStyles = null, IFormatProvider formatProvider = null)
{
NumberStyles = numberStyles;
FormatProvider = formatProvider;
}
public2 IFormatProvider FormatProvider { get; private set; }
public NumberStyles? NumberStyles { get; private set; }
protected override T ParseInner(string value)
{
if(NumberStyles != null && FormatProvider != null)
{
return ParseNumber(value, NumberStyles.Value, FormatProvider);
}
if(NumberStyles != null)
{
return ParseNumber(value, NumberStyles.Value);
}
if(FormatProvider != null)
{
return ParseNumber(value, FormatProvider);
}
return ParseNumber(value);
}
protected abstract T ParseNumber(string value);
protected abstract T ParseNumber(string value, IFormatProvider formatProvider);
protected abstract T ParseNumber(string value, NumberStyles numberStyles);
protected abstract T ParseNumber(string value, NumberStyles numberStyles, IFormatProvider formatProvider);
}
}
| using System;
using System.Globalization;
namespace Optivem.Commons.Parsing.Default
{
public abstract class BaseNumberParser<T> : BaseParser<T>
{
public BaseNumberParser(NumberStyles? numberStyles = null, IFormatProvider formatProvider = null)
{
NumberStyles = numberStyles;
FormatProvider = formatProvider;
}
public IFormatProvider FormatProvider { get; private set; }
public NumberStyles? NumberStyles { get; private set; }
protected override T ParseInner(string value)
{
if(NumberStyles != null && FormatProvider != null)
{
return ParseNumber(value, NumberStyles.Value, FormatProvider);
}
if(NumberStyles != null)
{
return ParseNumber(value, NumberStyles.Value);
}
if(FormatProvider != null)
{
return ParseNumber(value, FormatProvider);
}
return ParseNumber(value);
}
protected abstract T ParseNumber(string value);
protected abstract T ParseNumber(string value, IFormatProvider formatProvider);
protected abstract T ParseNumber(string value, NumberStyles numberStyles);
protected abstract T ParseNumber(string value, NumberStyles numberStyles, IFormatProvider formatProvider);
}
}
| apache-2.0 | C# |
5a490414c4483fc6065eaeefb31375a2f4d8d56c | Fix stack overflow in character | ethanmoffat/EndlessClient | EOLib/Data/BLL/Character.cs | EOLib/Data/BLL/Character.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 EOLib.Net.API;
namespace EOLib.Data.BLL
{
public class Character : ICharacter
{
public string Name { get; private set; }
public int ID { get; private set; }
public AdminLevel AdminLevel { get; private set; }
public ICharacterRenderProperties RenderProperties { get; private set; }
public ICharacterStats Stats { get; private set; }
public ICharacter WithName(string name)
{
var character = MakeCopy(this);
character.Name = name;
return character;
}
public ICharacter WithID(int id)
{
var character = MakeCopy(this);
character.ID = id;
return character;
}
public ICharacter WithAdminLevel(AdminLevel level)
{
var character = MakeCopy(this);
character.AdminLevel = level;
return character;
}
public ICharacter WithRenderProperties(ICharacterRenderProperties renderProperties)
{
var character = MakeCopy(this);
character.RenderProperties = renderProperties;
return character;
}
public ICharacter WithStats(ICharacterStats stats)
{
var character = MakeCopy(this);
character.Stats = stats;
return character;
}
private static Character MakeCopy(ICharacter source)
{
return new Character
{
Name = source.Name,
ID = source.ID,
AdminLevel = source.AdminLevel,
RenderProperties = source.RenderProperties,
Stats = source.Stats
};
}
}
} | // 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 EOLib.Net.API;
namespace EOLib.Data.BLL
{
public class Character : ICharacter
{
public string Name { get; private set; }
public int ID { get; private set; }
public AdminLevel AdminLevel { get; private set; }
public ICharacterRenderProperties RenderProperties { get; private set; }
public ICharacterStats Stats { get; private set; }
public ICharacter WithName(string name)
{
return new Character()
.WithName(name)
.WithID(ID)
.WithRenderProperties(RenderProperties)
.WithStats(Stats);
}
public ICharacter WithID(int id)
{
return new Character()
.WithName(Name)
.WithID(id)
.WithRenderProperties(RenderProperties)
.WithStats(Stats);
}
public ICharacter WithAdminLevel(AdminLevel level)
{
var character = MakeCopy(this);
character.AdminLevel = level;
return character;
}
public ICharacter WithRenderProperties(ICharacterRenderProperties renderProperties)
{
var character = MakeCopy(this);
character.RenderProperties = renderProperties;
return character;
}
public ICharacter WithStats(ICharacterStats stats)
{
var character = MakeCopy(this);
character.Stats = stats;
return character;
}
private static Character MakeCopy(ICharacter source)
{
return new Character
{
Name = source.Name,
ID = source.ID,
AdminLevel = source.AdminLevel,
RenderProperties = source.RenderProperties,
Stats = source.Stats
};
}
}
} | mit | C# |
76a3f3bffa07054032f6a7e07ab3b10281671bce | Remove GetResult(Task) | Tyrrrz/Extensions | Extensions/Ext.Threading.cs | Extensions/Ext.Threading.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using System.Threading.Tasks;
namespace Tyrrrz.Extensions
{
public static partial class Ext
{
/// <summary>
/// Continues execution without waiting for the task to complete
/// </summary>
public static void Forget(this Task task)
{
// #pragma 4014 workaround
}
/// <summary>
/// Executes a task asynchronously on all elements of a sequence in parallel
/// </summary>
public static async Task ParallelForEachAsync<T>([NotNull] this IEnumerable<T> enumerable, [NotNull] Func<T, Task> task)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
if (task == null)
throw new ArgumentNullException(nameof(task));
var tasks = enumerable.Select(async i => await task(i).ConfigureAwait(false));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>
/// Executes an action asynchronously on all elements of a sequence in parallel
/// </summary>
public static async Task ParallelForEachAsync<T>([NotNull] this IEnumerable<T> enumerable, [NotNull] Action<T> action)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
if (action == null)
throw new ArgumentNullException(nameof(action));
var tasks = enumerable.Select(async i => await Task.Run(() => action(i)).ConfigureAwait(false));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using System.Threading.Tasks;
namespace Tyrrrz.Extensions
{
public static partial class Ext
{
/// <summary>
/// Continues execution without waiting for the task to complete
/// </summary>
public static void Forget(this Task task)
{
// #pragma 4014 workaround
}
/// <summary>
/// Runs the task synchronously and returns the result
/// </summary>
public static T GetResult<T>([NotNull] this Task<T> task)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
return task.GetAwaiter().GetResult();
}
/// <summary>
/// Runs the task synchronously
/// </summary>
public static void GetResult([NotNull] this Task task)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
task.GetAwaiter().GetResult();
}
/// <summary>
/// Executes a task asynchronously on all elements of a sequence in parallel
/// </summary>
public static async Task ParallelForEachAsync<T>([NotNull] this IEnumerable<T> enumerable, [NotNull] Func<T, Task> task)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
if (task == null)
throw new ArgumentNullException(nameof(task));
var tasks = enumerable.Select(async i => await task(i));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>
/// Executes an action asynchronously on all elements of a sequence in parallel
/// </summary>
public static async Task ParallelForEachAsync<T>([NotNull] this IEnumerable<T> enumerable, [NotNull] Action<T> action)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
if (action == null)
throw new ArgumentNullException(nameof(action));
var tasks = enumerable.Select(async i => await Task.Run(() => action(i)));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
} | mit | C# |
740177c019a5552fdbb54140c8d2491b8efc839a | Implement get music | TentacleGuitar/Server,TentacleGuitar/Server | src/TentacleGuitar.Server/Controllers/HomeController.cs | src/TentacleGuitar.Server/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TentacleGuitar.Server.Models;
namespace TentacleGuitar.Server.Controllers
{
public class HomeController : BaseController
{
[HttpPost("/SignIn")]
public IActionResult SignIn(string Username, string Password)
{
var user = DB.Users.SingleOrDefault(x => x.UserName == Username && x.Password == Password);
if (user.Expire <= DateTime.Now)
{
user.Token = Guid.NewGuid().ToString();
user.Expire = DateTime.Now.AddDays(15);
DB.SaveChanges();
}
return Content(user?.Token ?? "Access Denied");
}
[HttpPost("/GetMusics")]
public IActionResult GetMusics()
{
return Json(DB.Musics.OrderBy(x => x.Level).ToList());
}
public IActionResult
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TentacleGuitar.Server.Models;
namespace TentacleGuitar.Server.Controllers
{
public class HomeController : BaseController
{
[HttpPost("/SignIn")]
public IActionResult SignIn(string Username, string Password)
{
var user = DB.Users.SingleOrDefault(x => x.UserName == Username && x.Password == Password);
if (user.Expire <= DateTime.Now)
{
user.Token = Guid.NewGuid().ToString();
user.Expire = DateTime.Now.AddDays(15);
DB.SaveChanges();
}
return Content(user?.Token ?? "Access Denied");
}
}
}
| mit | C# |
fc8c194f825b5ccb4785d4323891d56a3b42cfbe | Add roles | EmilMitev/ASP.NET-MVC-Course-Project,EmilMitev/ASP.NET-MVC-Course-Project,EmilMitev/ASP.NET-MVC-Course-Project | Source/StackFaceSystem/Data/StackFaceSystem.Data/Migrations/Configuration.cs | Source/StackFaceSystem/Data/StackFaceSystem.Data/Migrations/Configuration.cs | namespace StackFaceSystem.Data.Migrations
{
using System.Data.Entity.Migrations;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Models;
using StackFaceSystem.Common;
public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(ApplicationDbContext context)
{
if (!context.Roles.Any())
{
// For roles
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
IdentityRole role;
role = new IdentityRole { Name = GlobalConstants.AdministratorRoleName };
roleManager.Create(role);
role = new IdentityRole { Name = GlobalConstants.ModeratorRoleName };
roleManager.Create(role);
role = new IdentityRole { Name = GlobalConstants.UserRoleName };
roleManager.Create(role);
}
}
}
} | namespace StackFaceSystem.Data.Migrations
{
using System.Data.Entity.Migrations;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Models;
using StackFaceSystem.Common;
public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
}
}
| mit | C# |
a8f3ba6531d7ba85660da87b8a16756ad5b7af97 | add link to Brackey's tutorial in Attractor.cs | snackpackgames/Rubbley | Assets/Scripts/Attractor.cs | Assets/Scripts/Attractor.cs | // Adapted from https://github.com/Brackeys/Gravity-Simulation-Tutorial
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attractor : MonoBehaviour
{
public const float G = 667.4f;
public Rigidbody body;
public Rigidbody gravigaTarget;
public float gravigaMultiplier = 1.0f;
void FixedUpdate()
{
Attractor[] attractors = FindObjectsOfType<Attractor>();
foreach (Attractor attractor in attractors)
{
if (this != attractor)
{
if (gravigaTarget == attractor)
{
Attract(attractor, gravigaMultiplier);
}
else
{
Attract(attractor);
}
}
}
}
void Attract(Attractor other, float currentGravigaMultipler = 1.0f)
{
Rigidbody otherBody = other.body;
Vector3 direction = body.position - otherBody.position;
float distance = direction.magnitude;
Debug.Log(string.Format("distance: {0}", distance));
float forceMagnitude = ((body.mass * otherBody.mass) / Mathf.Pow(distance, 2));
Debug.Log(string.Format("forceMagnitude: {0}", forceMagnitude));
Debug.Log(string.Format("gravigaMultiplier: {0}", gravigaMultiplier));
Vector3 force = direction.normalized * (forceMagnitude * currentGravigaMultipler);
Debug.Log(string.Format("force: ({0}, {1}, {2})", force.x, force.y, force.z));
otherBody.AddForce(force);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attractor : MonoBehaviour
{
public const float G = 667.4f;
public Rigidbody body;
public Rigidbody gravigaTarget;
public float gravigaMultiplier = 1.0f;
void FixedUpdate()
{
Attractor[] attractors = FindObjectsOfType<Attractor>();
foreach (Attractor attractor in attractors)
{
if (this != attractor)
{
if (gravigaTarget == attractor)
{
Attract(attractor, gravigaMultiplier);
}
else
{
Attract(attractor);
}
}
}
}
void Attract(Attractor other, float currentGravigaMultipler = 1.0f)
{
Rigidbody otherBody = other.body;
Vector3 direction = body.position - otherBody.position;
float distance = direction.magnitude;
Debug.Log(string.Format("distance: {0}", distance));
float forceMagnitude = ((body.mass * otherBody.mass) / Mathf.Pow(distance, 2));
Debug.Log(string.Format("forceMagnitude: {0}", forceMagnitude));
Debug.Log(string.Format("gravigaMultiplier: {0}", gravigaMultiplier));
Vector3 force = direction.normalized * (forceMagnitude * currentGravigaMultipler);
Debug.Log(string.Format("force: ({0}, {1}, {2})", force.x, force.y, force.z));
otherBody.AddForce(force);
}
}
| mit | C# |
2919265456fcd51bb012545d306fb27fd406f4da | Remove an extra space. | CityofSantaMonica/Orchard.ParkingData | Models/SensorEventSettings.cs | Models/SensorEventSettings.cs | using Orchard.ContentManagement;
namespace CSM.ParkingData.Models
{
public class SensorEventsSettings : ContentPart
{
public double DefaultLifetimeLength
{
get { return this.Retrieve(x => x.DefaultLifetimeLength); }
set { this.Store(x => x.DefaultLifetimeLength, value); }
}
public TimeSpanUnits DefaultLifetimeUnits
{
get { return this.Retrieve(x => x.DefaultLifetimeUnits); }
set { this.Store(x => x.DefaultLifetimeUnits, value); }
}
public double MaxLifetimeLength
{
get { return this.Retrieve(x => x.MaxLifetimeLength, 3.0); }
set { this.Store(x => x.MaxLifetimeLength, value); }
}
public TimeSpanUnits MaxLifetimeUnits
{
get { return this.Retrieve(x => x.MaxLifetimeUnits, TimeSpanUnits.Hours); }
set { this.Store(x => x.MaxLifetimeUnits, value); }
}
}
}
| using Orchard.ContentManagement;
namespace CSM.ParkingData.Models
{
public class SensorEventsSettings : ContentPart
{
public double DefaultLifetimeLength
{
get { return this.Retrieve(x => x.DefaultLifetimeLength); }
set { this.Store(x => x.DefaultLifetimeLength, value); }
}
public TimeSpanUnits DefaultLifetimeUnits
{
get { return this.Retrieve(x => x.DefaultLifetimeUnits); }
set { this.Store(x => x.DefaultLifetimeUnits, value); }
}
public double MaxLifetimeLength
{
get { return this.Retrieve(x => x.MaxLifetimeLength, 3.0); }
set { this.Store(x => x.MaxLifetimeLength, value); }
}
public TimeSpanUnits MaxLifetimeUnits
{
get { return this.Retrieve(x => x.MaxLifetimeUnits, TimeSpanUnits.Hours); }
set { this.Store(x => x.MaxLifetimeUnits, value); }
}
}
}
| mit | C# |
c75becc72f3a470f97cf35047a75d0e4fd15d142 | fix build after API changes | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/CSharp/Daemon/Stages/PerformanceCriticalCodeAnalysis/CallGraph/StringBasedInvocationEdgeProvider.cs | resharper/resharper-unity/src/CSharp/Daemon/Stages/PerformanceCriticalCodeAnalysis/CallGraph/StringBasedInvocationEdgeProvider.cs | using JetBrains.Application;
using JetBrains.ReSharper.Daemon.CallGraph;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Resolve;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.CallGraph
{
[ShellComponent]
public class StringBasedInvocationEdgeProvider : ICallGraphEdgeProvider
{
public void FindEdges(ITreeNode treeNode, IDeclaredElement caller, ICallGraphEdgeConsumer consumer)
{
if (treeNode is IInvocationExpression invocationExpression)
{
var name = invocationExpression.Reference?.Resolve().DeclaredElement?.ShortName;
if (name != null && (name.Equals("Invoke") || name.Equals("InvokeRepeating")))
{
var implicitlyInvokeDeclaredElement = invocationExpression.Arguments.FirstOrDefault()?.Value
?.GetReferences<UnityEventFunctionReference>().FirstOrDefault()?.Resolve().DeclaredElement;
if (implicitlyInvokeDeclaredElement != null)
{
consumer.AddEdge(caller, implicitlyInvokeDeclaredElement);
}
}
}
}
}
} | using JetBrains.Application;
using JetBrains.ReSharper.Daemon.CallGraph;
using JetBrains.ReSharper.Daemon.CSharp.CallGraph;
using JetBrains.ReSharper.Daemon.UsageChecking;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Resolve;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.CallGraph
{
[ShellComponent]
public class StringBasedInvocationEdgeProvider : ICallGraphEdgeProvider
{
public void FindEdges(ITreeNode treeNode, IDeclaredElement caller, ICallGraphEdgeConsumer consumer, IElementIdProvider provider)
{
if (treeNode is IInvocationExpression invocationExpression)
{
var name = invocationExpression.Reference?.Resolve().DeclaredElement?.ShortName;
if (name != null && (name.Equals("Invoke") || name.Equals("InvokeRepeating")))
{
var implicitlyInvokeDeclaredElement = invocationExpression.Arguments.FirstOrDefault()?.Value
?.GetReferences<UnityEventFunctionReference>().FirstOrDefault()?.Resolve().DeclaredElement;
if (implicitlyInvokeDeclaredElement != null)
{
consumer.TryAddEdge(caller, implicitlyInvokeDeclaredElement, provider);
}
}
}
}
}
} | apache-2.0 | C# |
c08abbe3527fca16b55df53a596164fac97031d4 | Fix potential null ref in RuntimeInformation.FrameworkDescription (#40329) | wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx | src/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs | src/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.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.Reflection;
namespace System.Runtime.InteropServices
{
public static partial class RuntimeInformation
{
private const string FrameworkName = ".NET Core";
private static string s_frameworkDescription;
public static string FrameworkDescription
{
get
{
if (s_frameworkDescription == null)
{
string versionString = (string)AppContext.GetData("FX_PRODUCT_VERSION");
if (versionString == null)
{
// Use AssemblyInformationalVersionAttribute as fallback if the exact product version is not specified by the host
versionString = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
// Strip the git hash if there is one
if (versionString != null)
{
int plusIndex = versionString.IndexOf('+');
if (plusIndex != -1)
{
versionString = versionString.Substring(0, plusIndex);
}
}
}
s_frameworkDescription = !string.IsNullOrWhiteSpace(versionString) ? $"{FrameworkName} {versionString}" : FrameworkName;
}
return s_frameworkDescription;
}
}
}
}
| // 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.Reflection;
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
public static partial class RuntimeInformation
{
private const string FrameworkName = ".NET Core";
private static string s_frameworkDescription;
public static string FrameworkDescription
{
get
{
if (s_frameworkDescription == null)
{
string versionString = (string)AppContext.GetData("FX_PRODUCT_VERSION");
if (versionString == null)
{
// Use AssemblyInformationalVersionAttribute as fallback if the exact product version is not specified by the host
versionString = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
// Strip the git hash if there is one
int plusIndex = versionString.IndexOf('+');
if (plusIndex != -1)
versionString = versionString.Substring(0, plusIndex);
}
s_frameworkDescription = $"{FrameworkName} {versionString}";
}
return s_frameworkDescription;
}
}
}
}
| mit | C# |
781ae0b08d6301e46509d08e4617b1d304edb4c2 | extend extensions | ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate | src/Abp/DynamicEntityParameters/Extensions/EntityDynamicParameterManagerExtensions.cs | src/Abp/DynamicEntityParameters/Extensions/EntityDynamicParameterManagerExtensions.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Domain.Entities;
namespace Abp.DynamicEntityParameters.Extensions
{
public static class EntityDynamicParameterManagerExtensions
{
public static List<EntityDynamicParameter> GetAll<TEntity, TPrimaryKey>(this IEntityDynamicParameterManager manager)
where TEntity : IEntity<TPrimaryKey>
{
return manager.GetAll(entityFullName: typeof(TEntity).FullName);
}
public static List<EntityDynamicParameter> GetAll<TEntity>(this IEntityDynamicParameterManager manager)
where TEntity : IEntity<int>
{
return manager.GetAll<TEntity, int>();
}
public static Task<List<EntityDynamicParameter>> GetAllAsync<TEntity, TPrimaryKey>(this IEntityDynamicParameterManager manager)
where TEntity : IEntity<TPrimaryKey>
{
return manager.GetAllAsync(entityFullName: typeof(TEntity).FullName);
}
public static Task<List<EntityDynamicParameter>> GetAllAsync<TEntity>(this IEntityDynamicParameterManager manager)
where TEntity : IEntity<int>
{
return manager.GetAllAsync<TEntity, int>();
}
public static EntityDynamicParameter Add<TEntity>(this IEntityDynamicParameterManager manager, int dynamicParameterId, int? tenantId)
where TEntity : IEntity<int>
{
return manager.Add<TEntity, int>(dynamicParameterId, tenantId);
}
public static EntityDynamicParameter Add<TEntity, TPrimaryKey>(this IEntityDynamicParameterManager manager, int dynamicParameterId, int? tenantId)
where TEntity : IEntity<TPrimaryKey>
{
var entity = new EntityDynamicParameter()
{
DynamicParameterId = dynamicParameterId,
EntityFullName = typeof(TEntity).FullName,
TenantId = tenantId
};
manager.Add(entity);
return entity;
}
public static Task<EntityDynamicParameter> AddAsync<TEntity>(this IEntityDynamicParameterManager manager, int dynamicParameterId, int? tenantId)
where TEntity : IEntity<int>
{
return manager.AddAsync<TEntity, int>(dynamicParameterId, tenantId);
}
public static async Task<EntityDynamicParameter> AddAsync<TEntity, TPrimaryKey>(this IEntityDynamicParameterManager manager, int dynamicParameterId, int? tenantId)
where TEntity : IEntity<TPrimaryKey>
{
var entity = new EntityDynamicParameter()
{
DynamicParameterId = dynamicParameterId,
EntityFullName = typeof(TEntity).FullName,
TenantId = tenantId
};
await manager.AddAsync(entity);
return entity;
}
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Domain.Entities;
namespace Abp.DynamicEntityParameters.Extensions
{
public static class EntityDynamicParameterManagerExtensions
{
public static List<EntityDynamicParameter> GetAll<TEntity, TPrimaryKey>(this EntityDynamicParameterManager manager)
where TEntity : IEntity<TPrimaryKey>
{
return manager.GetAll(entityFullName: typeof(TEntity).FullName);
}
public static List<EntityDynamicParameter> GetAll<TEntity>(this EntityDynamicParameterManager manager)
where TEntity : IEntity<int>
{
return manager.GetAll<TEntity, int>();
}
public static Task<List<EntityDynamicParameter>> GetAllAsync<TEntity, TPrimaryKey>(this EntityDynamicParameterManager manager)
where TEntity : IEntity<TPrimaryKey>
{
return manager.GetAllAsync(entityFullName: typeof(TEntity).FullName);
}
public static Task<List<EntityDynamicParameter>> GetAllAsync<TEntity>(this EntityDynamicParameterManager manager)
where TEntity : IEntity<int>
{
return manager.GetAllAsync<TEntity, int>();
}
}
}
| mit | C# |
526016f07b4000e35e64501962d614a2c6074481 | Add a parameterless constructor to InteractableOnClickReceiver | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/SDK/Features/UX/Interactable/Scripts/Events/InteractableOnClickReceiver.cs | Assets/MRTK/SDK/Features/UX/Interactable/Scripts/Events/InteractableOnClickReceiver.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine.Events;
namespace Microsoft.MixedReality.Toolkit.UI
{
/// <summary>
/// A basic receiver for detecting clicks
/// </summary>
public class InteractableOnClickReceiver : ReceiverBase
{
/// <summary>
/// Invoked on pointer clicked
/// </summary>
public UnityEvent OnClicked => uEvent;
/// <summary>
/// Creates receiver for raising OnClick events
/// </summary>
public InteractableOnClickReceiver(UnityEvent ev) : base(ev, "OnClick") { }
/// <summary>
/// Creates receiver for raising OnClick events
/// </summary>
public InteractableOnClickReceiver() : this(new UnityEvent()) { }
/// <inheritdoc />
public override void OnUpdate(InteractableStates state, Interactable source)
{
// using onClick
}
/// <inheritdoc />
public override void OnClick(InteractableStates state, Interactable source, IMixedRealityPointer pointer = null)
{
uEvent.Invoke();
}
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine.Events;
namespace Microsoft.MixedReality.Toolkit.UI
{
/// <summary>
/// A basic receiver for detecting clicks
/// </summary>
public class InteractableOnClickReceiver : ReceiverBase
{
/// <summary>
/// Invoked on pointer clicked
/// </summary>
public UnityEvent OnClicked => uEvent;
/// <summary>
/// Creates receiver for raising OnClick events
/// </summary>
public InteractableOnClickReceiver(UnityEvent ev) : base(ev, "OnClick") { }
/// <inheritdoc />
public override void OnUpdate(InteractableStates state, Interactable source)
{
// using onClick
}
/// <inheritdoc />
public override void OnClick(InteractableStates state, Interactable source, IMixedRealityPointer pointer = null)
{
uEvent.Invoke();
}
}
}
| mit | C# |
3718277e10f8fff0b98e7081ac486586f9c5d67f | Add basic hello server version | avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors | csharp/Hello/HelloServer/Program.cs | csharp/Hello/HelloServer/Program.cs | using System;
using System.Threading.Tasks;
using Grpc.Core;
using Hello;
namespace HelloServer
{
class HelloServerImpl : HelloService.HelloServiceBase
{
// Server side handler of the SayHello RPC
public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context)
{
return Task.FromResult(new HelloResp { Result = "Hello " + request.Name });
}
}
class Program
{
const int Port = 50051;
public static void Main(string[] args)
{
Server server = new Server
{
Services = { HelloService.BindService(new HelloServerImpl()) },
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();
Console.WriteLine("Greeter server listening on port " + Port);
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
}
| using System;
namespace HelloServer
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| mit | C# |
3377b0144bf46a01503dfeac7552aec0b58cd4c5 | Fix Bug #886512, from "Open Images" to "Images" | jakeclawson/Pinta,PintaProject/Pinta,PintaProject/Pinta,Fenex/Pinta,PintaProject/Pinta,Fenex/Pinta,jakeclawson/Pinta,Mailaender/Pinta,Mailaender/Pinta | Pinta/Pads/OpenImagesPad.cs | Pinta/Pads/OpenImagesPad.cs | //
// OpenImagesPad.cs
//
// Author:
// Cameron White <cameronwhite91@gmail.com>
//
// Copyright (c) 2011 2011
//
// 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 MonoDevelop.Components.Docking;
using Mono.Unix;
using Gtk;
using Pinta.Core;
using Pinta.Gui.Widgets;
namespace Pinta
{
public class OpenImagesPad : IDockPad
{
public void Initialize (DockFrame workspace, Menu padMenu)
{
const string pad_name = "Images";
DockItem open_images_item = workspace.AddItem (pad_name);
open_images_item.Label = Catalog.GetString (pad_name);
open_images_item.Content = new OpenImagesListWidget ();
ToggleAction show_open_images = padMenu.AppendToggleAction (pad_name, Catalog.GetString (pad_name), null, null);
show_open_images.Activated += delegate {
open_images_item.Visible = show_open_images.Active;
};
open_images_item.VisibleChanged += delegate {
show_open_images.Active = open_images_item.Visible;
};
show_open_images.Active = open_images_item.Visible;
}
}
}
| //
// OpenImagesPad.cs
//
// Author:
// Cameron White <cameronwhite91@gmail.com>
//
// Copyright (c) 2011 2011
//
// 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 MonoDevelop.Components.Docking;
using Mono.Unix;
using Gtk;
using Pinta.Core;
using Pinta.Gui.Widgets;
namespace Pinta
{
public class OpenImagesPad : IDockPad
{
public void Initialize (DockFrame workspace, Menu padMenu)
{
const string pad_name = "Open Images";
DockItem open_images_item = workspace.AddItem (pad_name);
open_images_item.Label = Catalog.GetString (pad_name);
open_images_item.Content = new OpenImagesListWidget ();
ToggleAction show_open_images = padMenu.AppendToggleAction (pad_name, Catalog.GetString (pad_name), null, null);
show_open_images.Activated += delegate {
open_images_item.Visible = show_open_images.Active;
};
open_images_item.VisibleChanged += delegate {
show_open_images.Active = open_images_item.Visible;
};
show_open_images.Active = open_images_item.Visible;
}
}
}
| mit | C# |
dc5ee4c5a7b6f248685241e79c816a856863bbd5 | Update test cases | ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp | source/Htc.Vita.Core.Tests/TestCase.UsbManager.cs | source/Htc.Vita.Core.Tests/TestCase.UsbManager.cs | using System;
using Htc.Vita.Core.IO;
using Htc.Vita.Core.Runtime;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public partial class TestCase
{
[Fact]
public void UsbManager_Default_0_GetDevices()
{
if (!Platform.IsWindows)
{
return;
}
var deviceInfos = UsbManager.GetHidDevices();
foreach (var deviceInfo in deviceInfos) {
Console.WriteLine("deviceInfo.Path: " + deviceInfo.Path);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Path));
Assert.True(string.IsNullOrEmpty(deviceInfo.ProductId) || deviceInfo.ProductId.Length == 4);
Assert.True(string.IsNullOrEmpty(deviceInfo.VendorId) || deviceInfo.VendorId.Length == 4);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Description));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Manufecturer));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Optional["type"]));
}
}
}
}
| using System;
using Htc.Vita.Core.IO;
using Htc.Vita.Core.Runtime;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public partial class TestCase
{
[Fact]
public void UsbManager_Default_0_GetDevices()
{
if (!Platform.IsWindows)
{
return;
}
var deviceInfos = UsbManager.GetHidDevices();
foreach (var deviceInfo in deviceInfos) {
Console.WriteLine("deviceInfo.Path: " + deviceInfo.Path);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Path));
Assert.True(deviceInfo.ProductId.Length == 4);
Assert.True(deviceInfo.VendorId.Length == 4);
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Description));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Manufecturer));
Assert.False(string.IsNullOrWhiteSpace(deviceInfo.Optional["type"]));
}
}
}
}
| mit | C# |
6231e5838393071f30a62db12c4f32c66b777190 | Fix issue with delete query | dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu | src/Our.Umbraco.Nexu.Core/Repositories/NexuRelationRepository.cs | src/Our.Umbraco.Nexu.Core/Repositories/NexuRelationRepository.cs | namespace Our.Umbraco.Nexu.Core.Repositories
{
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using global::Umbraco.Core;
using global::Umbraco.Core.Persistence;
using global::Umbraco.Core.Scoping;
using NPoco;
using Our.Umbraco.Nexu.Common.Interfaces.Repositories;
using Our.Umbraco.Nexu.Common.Models;
/// <summary>
/// Represents nexu relation repository.
/// </summary>
internal class NexuRelationRepository : IRelationRepository
{
/// <summary>
/// The scope provider.
/// </summary>
private readonly IScopeProvider scopeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="NexuRelationRepository"/> class.
/// </summary>
/// <param name="scopeProvider">
/// The scope provider.
/// </param>
public NexuRelationRepository(IScopeProvider scopeProvider)
{
this.scopeProvider = scopeProvider;
}
/// <inheritdoc />
public void PersistRelationsForContentItem(Udi contentItemUdi, IEnumerable<NexuRelation> relations)
{
using (var scope = this.scopeProvider.CreateScope())
{
var db = scope.Database;
var udiString = contentItemUdi.ToString();
var deleteSql = new Sql<ISqlContext>(scope.SqlContext);
deleteSql.Where<NexuRelation>(x => x.ParentUdi == udiString);
db.Delete<NexuRelation>(deleteSql);
db.InsertBulk(relations);
scope.Complete();
}
}
}
}
| namespace Our.Umbraco.Nexu.Core.Repositories
{
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using global::Umbraco.Core;
using global::Umbraco.Core.Persistence;
using global::Umbraco.Core.Scoping;
using NPoco;
using Our.Umbraco.Nexu.Common.Interfaces.Repositories;
using Our.Umbraco.Nexu.Common.Models;
/// <summary>
/// Represents nexu relation repository.
/// </summary>
internal class NexuRelationRepository : IRelationRepository
{
/// <summary>
/// The scope provider.
/// </summary>
private readonly IScopeProvider scopeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="NexuRelationRepository"/> class.
/// </summary>
/// <param name="scopeProvider">
/// The scope provider.
/// </param>
public NexuRelationRepository(IScopeProvider scopeProvider)
{
this.scopeProvider = scopeProvider;
}
/// <inheritdoc />
public void PersistRelationsForContentItem(Udi contentItemUdi, IEnumerable<NexuRelation> relations)
{
using (var scope = this.scopeProvider.CreateScope())
{
var db = scope.Database;
var deleteSql = new Sql<ISqlContext>(scope.SqlContext);
deleteSql.From<NexuRelation>().Where<NexuRelation>(x => x.ParentUdi == contentItemUdi.ToString());
db.Delete<NexuRelation>(deleteSql);
db.InsertBulk(relations);
scope.Complete();
}
}
}
}
| mit | C# |
14b6c043d417eda094457873f90430afb88adcff | Remove forgotten not needed line | xabikos/aspnet-webpack | src/Webpack/WebpackExtenstions.cs | src/Webpack/WebpackExtenstions.cs | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using System;
using System.Diagnostics;
using System.IO;
namespace Webpack {
public static class WebpackExtensions {
private const string webpack = "webpack";
private const string webpacDevServer = "webpack-dev-server";
public static IApplicationBuilder UseWebpack(this IApplicationBuilder app, IHostingEnvironment env, WebpackOptions options) {
EnsuereNodeModluesInstalled(options);
Process process = new Process();
process.StartInfo = new ProcessStartInfo() {
FileName = GetNodeExecutable(webpack),
Arguments = ArgumentsHelper.GetWebpackArguments(env.WebRootPath, options),
UseShellExecute = false
};
process.Start();
app.UseMiddleware<WebpackMiddleware>(options);
return app;
}
private static void EnsuereNodeModluesInstalled(WebpackOptions options) {
if (!File.Exists(GetNodeExecutable(webpack))) {
throw new InvalidOperationException("webpack is not installed");
}
if (options.UseDevelopmentServer && !File.Exists(GetNodeExecutable(webpacDevServer))) {
throw new InvalidOperationException("webpack dev server is not installed");
}
}
private static string GetNodeExecutable(string module) {
var executable = Path.Combine(Directory.GetCurrentDirectory(), "node_modules", ".bin", module);
var osEnVariable = Environment.GetEnvironmentVariable("OS");
if (!string.IsNullOrEmpty(osEnVariable) && string.Equals(osEnVariable, "Windows_NT", StringComparison.OrdinalIgnoreCase)) {
executable += ".cmd";
}
return executable;
}
}
}
| using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using System;
using System.Diagnostics;
using System.IO;
namespace Webpack {
public static class WebpackExtensions {
private const string webpack = "webpack";
private const string webpacDevServer = "webpack-dev-server";
public static IApplicationBuilder UseWebpack(this IApplicationBuilder app, IHostingEnvironment env, WebpackOptions options) {
EnsuereNodeModluesInstalled(options);
Process process = new Process();
var temp = ArgumentsHelper.GetWebpackArguments(env.WebRootPath, options);
process.StartInfo = new ProcessStartInfo() {
FileName = GetNodeExecutable(webpack),
Arguments = ArgumentsHelper.GetWebpackArguments(env.WebRootPath, options),
UseShellExecute = false
};
process.Start();
app.UseMiddleware<WebpackMiddleware>(options);
return app;
}
private static void EnsuereNodeModluesInstalled(WebpackOptions options) {
if (!File.Exists(GetNodeExecutable(webpack))) {
throw new InvalidOperationException("webpack is not installed");
}
if (options.UseDevelopmentServer && !File.Exists(GetNodeExecutable(webpacDevServer))) {
throw new InvalidOperationException("webpack dev server is not installed");
}
}
private static string GetNodeExecutable(string module) {
var executable = Path.Combine(Directory.GetCurrentDirectory(), "node_modules", ".bin", module);
var osEnVariable = Environment.GetEnvironmentVariable("OS");
if (!string.IsNullOrEmpty(osEnVariable) && string.Equals(osEnVariable, "Windows_NT", StringComparison.OrdinalIgnoreCase)) {
executable += ".cmd";
}
return executable;
}
}
}
| mit | C# |
74f445dac91d9089788068c228613444b8573340 | fix model path | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/Components/TextComponent.cs | Dashen/Components/TextComponent.cs | namespace Dashen.Components
{
public class TextModel : Model
{
public string Text { get; set; }
}
public class TextComponent : Component<TextModel>
{
public override string GetJsx()
{
return @"{
render: function() {
return (
<p>Test: {this.props.model.Text} :End</p>
);
}
}";
}
}
}
| namespace Dashen.Components
{
public class TextModel : Model
{
public string Text { get; set; }
}
public class TextComponent : Component<TextModel>
{
public override string GetJsx()
{
return @"{
render: function() {
return (
<p>{this.props.Text}</p>
);
}
}";
}
}
}
| lgpl-2.1 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.