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 |
|---|---|---|---|---|---|---|---|---|
fd2b501a7811ef0c2c3d0d2018c54d1d4bebbae2 | Add backward compatible constructor to ServiceFieldInfo. | FacilityApi/Facility | src/Facility.Definition/ServiceFieldInfo.cs | src/Facility.Definition/ServiceFieldInfo.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Facility.Definition
{
/// <summary>
/// A field of a DTO.
/// </summary>
public sealed class ServiceFieldInfo : IServiceElementInfo, IValidatable
{
/// <summary>
/// Creates a field.
/// </summary>
public ServiceFieldInfo(string name, string typeName, IEnumerable<ServiceAttributeInfo> attributes, string summary, NamedTextPosition position)
: this(name, typeName, attributes, summary, position, null, ValidationMode.Throw)
{
}
/// <summary>
/// Creates a field.
/// </summary>
public ServiceFieldInfo(string name, string typeName, IEnumerable<ServiceAttributeInfo> attributes, string summary, NamedTextPosition position, NamedTextPosition typeNamePosition)
: this(name, typeName, attributes, summary, position, typeNamePosition, ValidationMode.Throw)
{
}
/// <summary>
/// Creates a field.
/// </summary>
public ServiceFieldInfo(string name, string typeName, IEnumerable<ServiceAttributeInfo> attributes = null, string summary = null, NamedTextPosition position = null, NamedTextPosition typeNamePosition = null, ValidationMode validationMode = ValidationMode.Throw)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
Name = name;
TypeName = typeName;
Attributes = attributes.ToReadOnlyList();
Summary = summary ?? "";
Position = position;
TypeNamePosition = typeNamePosition ?? position;
this.Validate(validationMode);
}
IEnumerable<ServiceDefinitionError> IValidatable.Validate()
{
return ServiceDefinitionUtility.ValidateName(Name, Position)
.Concat(ServiceDefinitionUtility.ValidateTypeName(TypeName, TypeNamePosition));
}
/// <summary>
/// The name of the field.
/// </summary>
public string Name { get; }
/// <summary>
/// The name of the type of the field.
/// </summary>
public string TypeName { get; }
/// <summary>
/// The attributes of the field.
/// </summary>
public IReadOnlyList<ServiceAttributeInfo> Attributes { get; }
/// <summary>
/// The summary of the field.
/// </summary>
public string Summary { get; }
/// <summary>
/// The position of the field in the definition.
/// </summary>
public NamedTextPosition Position { get; }
/// <summary>
/// The position of the field type name in the definition.
/// </summary>
public NamedTextPosition TypeNamePosition { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Facility.Definition
{
/// <summary>
/// A field of a DTO.
/// </summary>
public sealed class ServiceFieldInfo : IServiceElementInfo, IValidatable
{
/// <summary>
/// Creates a field.
/// </summary>
public ServiceFieldInfo(string name, string typeName, IEnumerable<ServiceAttributeInfo> attributes, string summary, NamedTextPosition position, NamedTextPosition typeNamePosition)
: this(name, typeName, attributes, summary, position, typeNamePosition, ValidationMode.Throw)
{
}
/// <summary>
/// Creates a field.
/// </summary>
public ServiceFieldInfo(string name, string typeName, IEnumerable<ServiceAttributeInfo> attributes = null, string summary = null, NamedTextPosition position = null, NamedTextPosition typeNamePosition = null, ValidationMode validationMode = ValidationMode.Throw)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
Name = name;
TypeName = typeName;
Attributes = attributes.ToReadOnlyList();
Summary = summary ?? "";
Position = position;
TypeNamePosition = typeNamePosition ?? position;
this.Validate(validationMode);
}
IEnumerable<ServiceDefinitionError> IValidatable.Validate()
{
return ServiceDefinitionUtility.ValidateName(Name, Position)
.Concat(ServiceDefinitionUtility.ValidateTypeName(TypeName, TypeNamePosition));
}
/// <summary>
/// The name of the field.
/// </summary>
public string Name { get; }
/// <summary>
/// The name of the type of the field.
/// </summary>
public string TypeName { get; }
/// <summary>
/// The attributes of the field.
/// </summary>
public IReadOnlyList<ServiceAttributeInfo> Attributes { get; }
/// <summary>
/// The summary of the field.
/// </summary>
public string Summary { get; }
/// <summary>
/// The position of the field in the definition.
/// </summary>
public NamedTextPosition Position { get; }
/// <summary>
/// The position of the field type name in the definition.
/// </summary>
public NamedTextPosition TypeNamePosition { get; set; }
}
}
| mit | C# |
e7aaf4a054dc9cc22f71947cfbdc4078275e7461 | add substitution tag with unicode | sumeshthomas/sendgrid-csharp,sendgrid/sendgrid-csharp,sendgrid/sendgrid-csharp,FriskyLingo/sendgrid-csharp,sendgrid/sendgrid-csharp,sumeshthomas/sendgrid-csharp,kenlefeb/sendgrid-csharp,pandeysoni/sendgrid-csharp,pandeysoni/sendgrid-csharp,brcaswell/sendgrid-csharp,brcaswell/sendgrid-csharp,dubrovkinmaxim/sendgrid-csharp,kenlefeb/sendgrid-csharp,FriskyLingo/sendgrid-csharp,dubrovkinmaxim/sendgrid-csharp | SendGrid/Example/Program.cs | SendGrid/Example/Program.cs | using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using SendGrid;
namespace Example
{
internal class Program
{
// this code is used for the SMTPAPI examples
private static void Main()
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World! %tag%";
var subs = new List<String> { "私はラーメンが大好き" };
myMessage.AddSubstitution("%tag%",subs);
SendAsync(myMessage);
Console.ReadLine();
}
private static async void SendAsync(SendGridMessage message)
{
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("username", "password");
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
try
{
await transportWeb.DeliverAsync(message);
Console.WriteLine("Sent!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
} | using System;
using System.Net;
using System.Net.Mail;
using SendGrid;
namespace Example
{
internal class Program
{
// this code is used for the SMTPAPI examples
private static void Main()
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
SendAsync(myMessage);
Console.ReadLine();
}
private static async void SendAsync(SendGridMessage message)
{
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("username", "password");
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
try
{
await transportWeb.DeliverAsync(message);
Console.WriteLine("Sent!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
} | mit | C# |
bd6d819533440f028f6a14fc6ceaeaa966d7045b | Swap BoundBinaryExpression.Result and OperatorKind | terrajobst/nquery-vnext | src/NQuery/Binding/BoundBinaryExpression.cs | src/NQuery/Binding/BoundBinaryExpression.cs | using System;
using System.Linq;
namespace NQuery.Binding
{
internal sealed class BoundBinaryExpression : BoundExpression
{
private readonly BoundExpression _left;
private readonly BinaryOperatorKind _operatorKind;
private readonly OverloadResolutionResult<BinaryOperatorSignature> _result;
private readonly BoundExpression _right;
public BoundBinaryExpression(BoundExpression left, BinaryOperatorKind operatorKind, OverloadResolutionResult<BinaryOperatorSignature> result, BoundExpression right)
{
_left = left;
_operatorKind = operatorKind;
_result = result;
_right = right;
}
public override BoundNodeKind Kind
{
get { return BoundNodeKind.BinaryExpression; }
}
public override Type Type
{
get
{
return _result.Selected == null
? TypeFacts.Unknown
: _result.Selected.Signature.ReturnType;
}
}
public BoundExpression Left
{
get { return _left; }
}
public BinaryOperatorKind OperatorKind
{
get { return _operatorKind; }
}
public OverloadResolutionResult<BinaryOperatorSignature> Result
{
get { return _result; }
}
public BoundExpression Right
{
get { return _right; }
}
public BoundBinaryExpression Update(BoundExpression left, BinaryOperatorKind operatorKind, OverloadResolutionResult<BinaryOperatorSignature> result, BoundExpression right)
{
if (left == _left && operatorKind == _operatorKind && result == _result && right == _right)
return this;
return new BoundBinaryExpression(left, operatorKind, result, right);
}
public override string ToString()
{
var kind = _result.Candidates.First().Signature.Kind;
return $"({_left} {kind.ToDisplayName()} {_right})";
}
}
} | using System;
using System.Linq;
namespace NQuery.Binding
{
internal sealed class BoundBinaryExpression : BoundExpression
{
private readonly BoundExpression _left;
private readonly BinaryOperatorKind _operatorKind;
private readonly OverloadResolutionResult<BinaryOperatorSignature> _result;
private readonly BoundExpression _right;
public BoundBinaryExpression(BoundExpression left, BinaryOperatorKind operatorKind, OverloadResolutionResult<BinaryOperatorSignature> result, BoundExpression right)
{
_left = left;
_operatorKind = operatorKind;
_result = result;
_right = right;
}
public override BoundNodeKind Kind
{
get { return BoundNodeKind.BinaryExpression; }
}
public override Type Type
{
get
{
return _result.Selected == null
? TypeFacts.Unknown
: _result.Selected.Signature.ReturnType;
}
}
public BoundExpression Left
{
get { return _left; }
}
public OverloadResolutionResult<BinaryOperatorSignature> Result
{
get { return _result; }
}
public BinaryOperatorKind OperatorKind
{
get { return _operatorKind; }
}
public BoundExpression Right
{
get { return _right; }
}
public BoundBinaryExpression Update(BoundExpression left, BinaryOperatorKind operatorKind, OverloadResolutionResult<BinaryOperatorSignature> result, BoundExpression right)
{
if (left == _left && operatorKind == _operatorKind && result == _result && right == _right)
return this;
return new BoundBinaryExpression(left, operatorKind, result, right);
}
public override string ToString()
{
var kind = _result.Candidates.First().Signature.Kind;
return $"({_left} {kind.ToDisplayName()} {_right})";
}
}
} | mit | C# |
f2b10d58e6f65f28b1a0b699e285b9e8b04917b7 | Add comments | sakapon/KLibrary-Labs | UILab/UI/UI/ScreenHelper.cs | UILab/UI/UI/ScreenHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
namespace KLibrary.Labs.UI
{
/// <summary>
/// Provides the helper methods for screen.
/// </summary>
public static class ScreenHelper
{
/// <summary>
/// Gets the bounds of all screens.
/// </summary>
/// <value>The bounds of all screens.</value>
public static Int32Rect AllScreensBounds
{
get { return _AllScreensBounds.Value; }
}
static readonly Lazy<Int32Rect> _AllScreensBounds = new Lazy<Int32Rect>(() => SystemInformation.VirtualScreen.ToInt32Rect());
/// <summary>
/// Gets the bounds of the primary screen.
/// </summary>
/// <value>The bounds of the primary screen.</value>
public static Int32Rect PrimaryScreenBounds
{
get { return _PrimaryScreenBounds.Value; }
}
static readonly Lazy<Int32Rect> _PrimaryScreenBounds = new Lazy<Int32Rect>(() => Screen.PrimaryScreen.Bounds.ToInt32Rect());
public static Point GetLeftTop(this Int32Rect rect)
{
return new Point(rect.X, rect.Y);
}
public static Point GetLeftBottom(this Int32Rect rect)
{
return new Point(rect.X, rect.Y + rect.Height - 1);
}
public static Point GetRightTop(this Int32Rect rect)
{
return new Point(rect.X + rect.Width - 1, rect.Y);
}
public static Point GetRightBottom(this Int32Rect rect)
{
return new Point(rect.X + rect.Width - 1, rect.Y + rect.Height - 1);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
namespace KLibrary.Labs.UI
{
public static class ScreenHelper
{
public static Int32Rect AllScreensBounds
{
get { return _AllScreensBounds.Value; }
}
static readonly Lazy<Int32Rect> _AllScreensBounds = new Lazy<Int32Rect>(() => SystemInformation.VirtualScreen.ToInt32Rect());
public static Int32Rect PrimaryScreenBounds
{
get { return _PrimaryScreenBounds.Value; }
}
static readonly Lazy<Int32Rect> _PrimaryScreenBounds = new Lazy<Int32Rect>(() => Screen.PrimaryScreen.Bounds.ToInt32Rect());
public static Point GetLeftTop(this Int32Rect rect)
{
return new Point(rect.X, rect.Y);
}
public static Point GetLeftBottom(this Int32Rect rect)
{
return new Point(rect.X, rect.Y + rect.Height - 1);
}
public static Point GetRightTop(this Int32Rect rect)
{
return new Point(rect.X + rect.Width - 1, rect.Y);
}
public static Point GetRightBottom(this Int32Rect rect)
{
return new Point(rect.X + rect.Width - 1, rect.Y + rect.Height - 1);
}
}
}
| mit | C# |
d73ba9061fbcf18bd8206f97fa92744537c61958 | Make TagCloudViewComponent synchronous | bradygaster/downr,bradygaster/downr,spboyer/downr,spboyer/downr,bradygaster/downr | src/ViewComponents/TagCloudViewComponent.cs | src/ViewComponents/TagCloudViewComponent.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using downr.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using downr.Models.TagCloud;
namespace downr.ViewComponents
{
public class TagCloudViewComponent : ViewComponent
{
protected IYamlIndexer _indexer;
public TagCloudViewComponent(IYamlIndexer indexer)
{
_indexer = indexer;
}
public ViewViewComponentResult Invoke()
{
var tags = _indexer.Metadata
.SelectMany(p => p.Categories) // flatten post categories
.GroupBy(c => c)
.Select(g => new Tag { Name = g.Key, Count = g.Count() })
.OrderBy(t=>t.Name)
.ToArray();
var model = new TagCloudModel
{
Tags = tags
};
return View(model);
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using downr.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using downr.Models.TagCloud;
namespace downr.ViewComponents
{
public class TagCloudViewComponent : ViewComponent
{
protected IYamlIndexer _indexer;
public TagCloudViewComponent(IYamlIndexer indexer)
{
_indexer = indexer;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var tags = _indexer.Metadata
.SelectMany(p => p.Categories) // flatten post categories
.GroupBy(c => c)
.Select(g => new Tag { Name = g.Key, Count = g.Count() })
.OrderBy(t=>t.Name)
.ToArray();
var model = new TagCloudModel
{
Tags = tags
};
return View(model);
}
}
} | apache-2.0 | C# |
ab0daeccce39bd9e3abb02c0872bddfdff403bdb | Change header size in HTML generation. | gilles-leblanc/Sniptaculous | SnippetsToMarkdown/SnippetsToMarkdown/Commands/WriteHeaderHtmlCommand.cs | SnippetsToMarkdown/SnippetsToMarkdown/Commands/WriteHeaderHtmlCommand.cs | using System.Text;
namespace SnippetsToMarkdown.Commands
{
class WriteHeaderHtmlCommand : ICommand
{
private string directory;
public WriteHeaderHtmlCommand(string directory)
{
this.directory = directory;
}
public void WriteToOutput(StringBuilder output)
{
output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>");
output.AppendLine("<br />");
output.AppendLine("<table>");
output.AppendLine("<thead>");
output.AppendLine("<tr>");
output.AppendLine("<td>Shortcut</td>");
output.AppendLine("<td>Name</td>");
output.AppendLine("</tr>");
output.AppendLine("</thead>");
output.AppendLine("<tbody>");
}
}
}
| using System.Text;
namespace SnippetsToMarkdown.Commands
{
class WriteHeaderHtmlCommand : ICommand
{
private string directory;
public WriteHeaderHtmlCommand(string directory)
{
this.directory = directory;
}
public void WriteToOutput(StringBuilder output)
{
output.AppendLine("<h3>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h3>");
output.AppendLine("<br />");
output.AppendLine("<table>");
output.AppendLine("<thead>");
output.AppendLine("<tr>");
output.AppendLine("<td>Shortcut</td>");
output.AppendLine("<td>Name</td>");
output.AppendLine("</tr>");
output.AppendLine("</thead>");
output.AppendLine("<tbody>");
}
}
}
| mit | C# |
4fcecd93b3dd439be3270578e3e17ab0cde644a8 | Switch to version 1.4.1 | biarne-a/Zebus,Abc-Arbitrage/Zebus | src/SharedVersionInfo.cs | src/SharedVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.4.1")]
[assembly: AssemblyFileVersion("1.4.1")]
[assembly: AssemblyInformationalVersion("1.4.1")]
| using System.Reflection;
[assembly: AssemblyVersion("1.4.0")]
[assembly: AssemblyFileVersion("1.4.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
| mit | C# |
c521b3d669d46b9c38fc5845359dd2643087386a | Add ignores for testing | rprouse/nunit-tests,rprouse/nunit-tests,rprouse/nunit-tests | nunit-v3/IgnoreTests.cs | nunit-v3/IgnoreTests.cs | using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace nunit.v3
{
[TestFixture]
public class IgnoreTests
{
[Ignore("NUnit Issue #1762")]
[Test]
public void IgnoreBeforeTest()
{
Assert.Fail("This test should be ignored");
}
[Test]
[Ignore("NUnit Issue #1762")]
public void IgnoreAfterTest()
{
Assert.Fail("This test should be ignored");
}
[Ignore("NUnit Issue #1762")]
[TestCase(1)]
[TestCase(2)]
public void IgnoreBeforeTestCase(int i)
{
Assert.Fail("This test should be ignored");
}
[TestCase(1)]
[TestCase(2)]
[Ignore("NUnit Issue #1762")]
public void IgnoreAfterTestCase(int i)
{
Assert.Fail("This test should be ignored");
}
}
}
| using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace nunit.v3
{
[TestFixture]
public class IgnoreTests
{
[Ignore("NUnit Issue #1762")]
[Test]
public void IgnoreBeforeTest()
{
Assert.Fail("This test should be ignored");
}
[Test]
[Ignore("NUnit Issue #1762")]
public void IgnoreAfterTest()
{
Assert.Fail("This test should be ignored");
}
[Ignore("NUnit Issue #1762")]
[TestCase(1)]
public void IgnoreBeforeTestCase(int i)
{
Assert.Fail("This test should be ignored");
}
[TestCase(1)]
[Ignore("NUnit Issue #1762")]
public void IgnoreAfterTestCase(int i)
{
Assert.Fail("This test should be ignored");
}
}
}
| mit | C# |
72745a8ba1fad63b6aec87b8aca1548e08312932 | Clean up unused Context constants | ejadib/AuthBot,ejadib/AuthBot | AuthBot/ContextConstants.cs | AuthBot/ContextConstants.cs | // Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
namespace AuthBot
{
public class ContextConstants
{
public const string PersistedCookieKey = "persistedCookie";
public const string AuthResultKey = "authResult";
public const string MagicNumberKey = "authMagicNumber";
public const string MagicNumberValidated = "authMagicNumberValidated";
}
}
//*********************************************************
//
//AuthBot, https://github.com/matvelloso/AuthBot
//
//Copyright (c) Microsoft Corporation
//All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// ""Software""), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//*********************************************************
| // Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
namespace AuthBot
{
public class ContextConstants
{
public const string PersistedCookieKey = "persistedCookie";
public const string AuthResultKey = "authResult";
public const string OriginalMessageKey = "originalMessage";
public const string CurrentMessageFromKey = "messageFrom";
public const string CurrentMessageToKey = "messageTo";
public const string MagicNumberKey = "authMagicNumber";
public const string MagicNumberValidated = "authMagicNumberValidated";
}
}
//*********************************************************
//
//AuthBot, https://github.com/matvelloso/AuthBot
//
//Copyright (c) Microsoft Corporation
//All rights reserved.
//
// MIT License:
// 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.
//
//*********************************************************
| mit | C# |
20646d5273e458fa0a2208e32553bbad8f3f049d | Use uppercase letters ONLY | 12joan/hangman | hangman.cs | hangman.cs | using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
var game = new Game("HANG THE MAN");
game.GuessLetter('H');
var output = game.ShownWord();
Console.WriteLine(output);
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
| using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
var game = new Game("hang the man");
game.GuessLetter('h');
var output = game.ShownWord();
Console.WriteLine(output);
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
| unlicense | C# |
a3dbe7efa354462c0b513362be38dd82d6314373 | Fix minor bugs. | rryk/omp-server,rryk/omp-server,rryk/omp-server,rryk/omp-server,rryk/omp-server,rryk/omp-server | KIARA/ObjectDeserializer.cs | KIARA/ObjectDeserializer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace KIARA
{
class ObjectDeserializer
{
#region Public interface
public static object Read(SerializedDataReader reader, Type objectType, List<WireEncoding> encoding)
{
object obj = ObjectConstructor.ConstructObject(encoding, objectType);
foreach (WireEncoding encodingEntry in encoding)
{
if (encodingEntry.Kind == WireEncoding.WireEncodingKind.Base)
{
object value = null;
switch (encodingEntry.BaseEncoding)
{
case BaseEncoding.ZCString:
value = reader.ReadZCString();
break;
case BaseEncoding.U32:
value = reader.ReadUint32();
break;
default:
throw new NotImplementedException();
}
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, value);
}
else if (encodingEntry.Kind == WireEncoding.WireEncodingKind.Array)
{
int size = (int)reader.ReadUint32();
Type arrayType = ObjectAccessor.GetTypeAtPath(obj, encodingEntry.ValuePath);
IList array = ObjectConstructor.ConstructAndAllocateArray(arrayType, size);
for (int i = 0; i < size; i++)
array[i] = Read(reader, ObjectAccessor.GetElementType(arrayType), encodingEntry.ElementEncoding);
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, array);
}
else if (encodingEntry.Kind == WireEncoding.WireEncodingKind.Enum)
{
int value = (int)reader.ReadUint32();
Type memberType = ObjectAccessor.GetTypeAtPath(obj, encodingEntry.ValuePath);
if (typeof(string).IsAssignableFrom(memberType))
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, encodingEntry.KeyByValue(value));
else
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, value);
}
}
return obj;
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace KIARA
{
class ObjectDeserializer
{
#region Public interface
public static object Read(SerializedDataReader reader, Type objectType, List<WireEncoding> encoding)
{
object obj = ObjectConstructor.ConstructObject(encoding, objectType);
foreach (WireEncoding encodingEntry in encoding)
{
if (encodingEntry.Kind == WireEncoding.WireEncodingKind.Base)
{
object value = null;
switch (encodingEntry.BaseEncoding)
{
case BaseEncoding.ZCString:
value = reader.ReadZCString();
break;
case BaseEncoding.U32:
value = reader.ReadUint32();
break;
default:
throw new NotImplementedException();
}
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, value);
}
else if (encodingEntry.Kind == WireEncoding.WireEncodingKind.Array)
{
int size = (int)reader.ReadUint32();
Type arrayType = ObjectAccessor.GetTypeAtPath(obj, encodingEntry.ValuePath);
IList array = ObjectConstructor.ConstructAndAllocateArray(arrayType, size);
for (int i = 0; i < size; i++)
array[i] = Read(reader, ObjectAccessor.GetElementType(arrayType), encodingEntry.ElementEncoding);
obj = array;
}
else if (encodingEntry.Kind == WireEncoding.WireEncodingKind.Enum)
{
int value = (int)reader.ReadUint32();
Type memberType = ObjectAccessor.GetTypeAtPath(obj, encodingEntry.ValuePath);
if (typeof(string).IsAssignableFrom(memberType))
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, encodingEntry.KeyByValue(value));
else
ObjectAccessor.SetValueAtPath(ref obj, encodingEntry.ValuePath, value);
}
}
return obj;
}
#endregion
}
}
| bsd-3-clause | C# |
176979aeb0b1b3a4897fa7bb302d17c9609c8b66 | Fix typo in TabViewModel.cs | serenabenny/Caliburn.Micro,Caliburn-Micro/Caliburn.Micro | samples/features/Features.CrossPlatform.Shared/ViewModels/TabViewModel.cs | samples/features/Features.CrossPlatform.Shared/ViewModels/TabViewModel.cs | using System;
using Caliburn.Micro;
namespace Features.CrossPlatform.ViewModels
{
public class TabViewModel : Screen
{
public TabViewModel()
{
Messages = new BindableCollection<string>();
}
protected override void OnInitialize()
{
Messages.Add("Initialized");
}
protected override void OnActivate()
{
Messages.Add("Activated");
}
protected override void OnDeactivate(bool close)
{
Messages.Add($"Deactivated, close: {close}");
}
public BindableCollection<string> Messages { get; }
}
}
| using System;
using Caliburn.Micro;
namespace Features.CrossPlatform.ViewModels
{
public class TabViewModel : Screen
{
public TabViewModel()
{
Messages = new BindableCollection<string>();
}
protected override void OnInitialize()
{
Messages.Add("Initialized");
}
protected override void OnActivate()
{
Messages.Add("Activated");
}
protected override void OnDeactivate(bool close)
{
Messages.Add($"Deactivted, close: {close}");
}
public BindableCollection<string> Messages { get; }
}
}
| mit | C# |
29bf497ed3bfbf42862d96d86f1a10989a989428 | Fix renamed OmniXAML interface. | OronDF343/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,susloparovdenis/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jazzay/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,susloparovdenis/Avalonia,Perspex/Perspex,MrDaedra/Avalonia,punker76/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,susloparovdenis/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,grokys/Perspex,susloparovdenis/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia | src/Markup/Perspex.Markup.Xaml/Converters/SolidColorBrushTypeConverter.cs | src/Markup/Perspex.Markup.Xaml/Converters/SolidColorBrushTypeConverter.cs | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media;
namespace Perspex.Markup.Xaml.Converters
{
public class SolidColorBrushTypeConverter : ITypeConverter
{
public bool CanConvertFrom(IValueContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(IValueContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(IValueContext context, CultureInfo culture, object value)
{
return Brush.Parse((string)value);
}
public object ConvertTo(IValueContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
} | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media;
namespace Perspex.Markup.Xaml.Converters
{
public class SolidColorBrushTypeConverter : ITypeConverter
{
public bool CanConvertFrom(ITypeConverterContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public bool CanConvertTo(ITypeConverterContext context, Type destinationType)
{
return false;
}
public object ConvertFrom(ITypeConverterContext context, CultureInfo culture, object value)
{
return Brush.Parse((string)value);
}
public object ConvertTo(ITypeConverterContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
} | mit | C# |
2b87997ff753d92912ebb67070f0a9dabec43b2b | Make JSNLogLogger available to the outside world, so it can actually be used in ASP.NET 5 apps | mperdeck/jsnlog | JSNLog.aspnet5/PublicFacing/Configuration/JSNlogLogger.cs | JSNLog.aspnet5/PublicFacing/Configuration/JSNlogLogger.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using JSNLog.Infrastructure;
namespace JSNLog
{
public class JSNlogLogger : IJSNLogLogger
{
private ILoggerFactory _loggerFactory;
public JSNlogLogger(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void Log(FinalLogData finalLogData)
{
ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger);
Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage);
switch (finalLogData.FinalLevel)
{
case Level.TRACE: logger.LogDebug("{logMessage}", message); break;
case Level.DEBUG: logger.LogVerbose("{logMessage}", message); break;
case Level.INFO: logger.LogInformation("{logMessage}", message); break;
case Level.WARN: logger.LogWarning("{logMessage}", message); break;
case Level.ERROR: logger.LogError("{logMessage}", message); break;
case Level.FATAL: logger.LogCritical("{logMessage}", message); break;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using JSNLog.Infrastructure;
namespace JSNLog
{
internal class JSNlogLogger : IJSNLogLogger
{
private ILoggerFactory _loggerFactory;
public JSNlogLogger(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void Log(FinalLogData finalLogData)
{
ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger);
Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage);
switch (finalLogData.FinalLevel)
{
case Level.TRACE: logger.LogDebug("{logMessage}", message); break;
case Level.DEBUG: logger.LogVerbose("{logMessage}", message); break;
case Level.INFO: logger.LogInformation("{logMessage}", message); break;
case Level.WARN: logger.LogWarning("{logMessage}", message); break;
case Level.ERROR: logger.LogError("{logMessage}", message); break;
case Level.FATAL: logger.LogCritical("{logMessage}", message); break;
}
}
}
}
| mit | C# |
ce9a0d4707434786efc1cca3589b55e6489bcfb9 | update script with nuget download | Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving | XamarinApp/build.cake | XamarinApp/build.cake | #addin nuget:https://nuget.org/api/v2/?package=Cake.FileHelpers&version=1.0.3.2
#addin nuget:https://nuget.org/api/v2/?package=Cake.Xamarin&version=1.2.3
var username = EnvironmentVariable("XamarinLicenseUser", "");
var password = EnvironmentVariable("XamarinLicensePassword", "");
var TARGET = Argument ("target", Argument ("t", "Default"));
Task ("Default").Does (() =>
{
RestoreComponents ("./MyTrips.sln", new XamarinComponentRestoreSettings
{
Email = username,
Password = password,
ToolPath = "./tools/xamarin-component.exe"
});
});
RunTarget (TARGET);
| #addin "Cake.Xamarin"
var username = EnvironmentVariable("XamarinLicenseUser", "");
var password = EnvironmentVariable("XamarinLicensePassword", "");
var TARGET = Argument ("target", Argument ("t", "Default"));
Task ("Default").Does (() =>
{
RestoreComponents ("./MyTrips.sln", new XamarinComponentRestoreSettings
{
Email = username,
Password = password,
ToolPath = "./tools/xamarin-component.exe"
});
});
RunTarget (TARGET);
| mit | C# |
83dd503698be240c3a2fa502093de2c3a2473292 | fix SummonuerSpell1 typo (#306) | frederickrogan/RiotSharp,JanOuborny/RiotSharp,Challengermode/RiotSharp,florinciubotariu/RiotSharp,jono-90/RiotSharp,BenFradet/RiotSharp,Oucema90/RiotSharp,oisindoherty/RiotSharp,Shidesu/RiotSharp | RiotSharp/CurrentGameEndpoint/Participant.cs | RiotSharp/CurrentGameEndpoint/Participant.cs | using Newtonsoft.Json;
using System.Collections.Generic;
namespace RiotSharp.CurrentGameEndpoint
{
/// <summary>
/// Class representing a Participant in the API.
/// </summary>
public class Participant
{
/// <summary>
/// Flag indicating whether or not this participant is a bot
/// </summary>
[JsonProperty("bot")]
public bool Bot { get; set; }
/// <summary>
/// The ID of the champion played by this participant
/// </summary>
[JsonProperty("championId")]
public long ChampionId { get; set; }
/// <summary>
/// The masteries used by this participant
/// </summary>
[JsonProperty("masteries")]
public List<Mastery> Masteries { get; set; }
/// <summary>
/// The ID of the profile icon used by this participant
/// </summary>
[JsonProperty("profileIconId")]
public long ProfileIconId { get; set; }
/// <summary>
/// The runes used by this participant
/// </summary>
[JsonProperty("runes")]
public List<Rune> Runes { get; set; }
/// <summary>
/// The ID of the first summoner spell used by this participant
/// </summary>
[JsonProperty("spell1Id")]
public long SummonerSpell1 { get; set; }
/// <summary>
/// The ID of the second summoner spell used by this participant
/// </summary>
[JsonProperty("spell2Id")]
public long SummonerSpell2 { get; set; }
/// <summary>
/// The summoner name of this participant
/// </summary>
[JsonProperty("summonerName")]
public string SummonerName { get; set; }
/// <summary>
/// The team ID of this participant, indicating the participant's team
/// </summary>
[JsonProperty("teamId")]
public long TeamId { get; set; }
}
}
| using Newtonsoft.Json;
using System.Collections.Generic;
namespace RiotSharp.CurrentGameEndpoint
{
/// <summary>
/// Class representing a Participant in the API.
/// </summary>
public class Participant
{
/// <summary>
/// Flag indicating whether or not this participant is a bot
/// </summary>
[JsonProperty("bot")]
public bool Bot { get; set; }
/// <summary>
/// The ID of the champion played by this participant
/// </summary>
[JsonProperty("championId")]
public long ChampionId { get; set; }
/// <summary>
/// The masteries used by this participant
/// </summary>
[JsonProperty("masteries")]
public List<Mastery> Masteries { get; set; }
/// <summary>
/// The ID of the profile icon used by this participant
/// </summary>
[JsonProperty("profileIconId")]
public long ProfileIconId { get; set; }
/// <summary>
/// The runes used by this participant
/// </summary>
[JsonProperty("runes")]
public List<Rune> Runes { get; set; }
/// <summary>
/// The ID of the first summoner spell used by this participant
/// </summary>
[JsonProperty("spell1Id")]
public long SummonuerSpell1 { get; set; }
/// <summary>
/// The ID of the second summoner spell used by this participant
/// </summary>
[JsonProperty("spell2Id")]
public long SummonerSpell2 { get; set; }
/// <summary>
/// The summoner name of this participant
/// </summary>
[JsonProperty("summonerName")]
public string SummonerName { get; set; }
/// <summary>
/// The team ID of this participant, indicating the participant's team
/// </summary>
[JsonProperty("teamId")]
public long TeamId { get; set; }
}
}
| mit | C# |
bbcc8ac4f51be2c6119b45ab9c91f35c85dca3f3 | Create Request Ready. | bergthor13/Skermstafir,bergthor13/Skermstafir,bergthor13/Skermstafir | Skermstafir/Controllers/RequestController.cs | Skermstafir/Controllers/RequestController.cs | using Skermstafir.Exceptions;
using Skermstafir.Models;
using Skermstafir.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Skermstafir.Controllers
{
public class RequestController : Controller
{
//
// GET: /Request/
public ActionResult ShowRequest(int? id)
{
if (id == null)
{
return View("Errors/NoSubFound");
}
try
{
RequestRepository sr = new RequestRepository();
int idValue = id.Value;
RequestModel result = sr.GetRequestByID(idValue);
FillModel(result);
return View(result);
}
catch (NoRequestFoundException)
{
return View("Errors/NoSubFound");
}
}
// Adds a new request.
[HttpPost]
public ActionResult CreateRequest(FormCollection fc)
{
RequestModel model = new RequestModel();
RequestRepository rr = new RequestRepository();
model.request.Name = fc["title"];
model.request.Language.Name = fc["language"];
model.request.Director.Name = fc["director"];
model.request.Username = "NOTIMPL";
model.request.Description = fc["description"];
int year = Convert.ToInt32(fc["year"]);
model.request.YearCreated = year;
model.request.DateAdded = DateTime.Now;
model.request.Link = fc["link"];
string actors = fc["actors"];
String[] actorers = actors.Split(',');
foreach (var item in actorers)
{
Actor temp = new Actor();
temp.Name = item;
model.request.Actors.Add(temp);
}
rr.AddRequest(model);
return this.RedirectToAction("ShowRequest", new { id = model.request.IdRequest });
}
[HttpGet]
public ActionResult CreateRequest()
{
RequestModel model = new RequestModel();
return View(model);
}
public void FillModel(RequestModel rm)
{
foreach (var item in rm.request.Genres)
{
for (int i = 0; i < 8; i++)
{
if (item.IdGenre == i + 1)
{
rm.genreValue[i] = true;
}
}
}
foreach (var art in rm.request.Actors)
{
if (art != rm.request.Actors.Last())
{
rm.actorsForView += art.Name + ", ";
}
else
{
rm.actorsForView += art.Name;
}
}
}
}
} | using Skermstafir.Exceptions;
using Skermstafir.Models;
using Skermstafir.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Skermstafir.Controllers
{
public class RequestController : Controller
{
//
// GET: /Request/
public ActionResult ShowRequest(int? id)
{
if (id == null)
{
return View("Errors/NoSubFound");
}
try
{
RequestRepository sr = new RequestRepository();
int idValue = id.Value;
RequestModel result = sr.GetRequestByID(idValue);
FillModel(result);
return View(result);
}
catch (NoRequestFoundException)
{
return View("Errors/NoSubFound");
}
}
// Adds a new request.
public ActionResult CreateRequest()
{
RequestModel model = new RequestModel();
return View(model);
}
public void FillModel(RequestModel rm)
{
foreach (var item in rm.request.Genres)
{
for (int i = 0; i < 8; i++)
{
if (item.IdGenre == i + 1)
{
rm.genreValue[i] = true;
}
}
}
foreach (var art in rm.request.Actors)
{
if (art != rm.request.Actors.Last())
{
rm.actorsForView += art.Name + ", ";
}
else
{
rm.actorsForView += art.Name;
}
}
}
}
} | mit | C# |
4934ae1421d2c23d8fe46c48d31669e302a14ffe | Add TargetPlatformMinVersion | pakdev/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,pakdev/roslyn-analyzers | src/Utilities/Compiler/Options/MSBuildPropertyOptionNames.cs | src/Utilities/Compiler/Options/MSBuildPropertyOptionNames.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Analyzer.Utilities
{
/// <summary>
/// MSBuild property names that are required to be threaded as analyzer config options.
/// </summary>
internal static partial class MSBuildPropertyOptionNames
{
public const string TargetFramework = "TargetFramework";
public const string TargetPlatformMinVersion = "TargetPlatformMinVersion";
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Analyzer.Utilities
{
/// <summary>
/// MSBuild property names that are required to be threaded as analyzer config options.
/// </summary>
internal static partial class MSBuildPropertyOptionNames
{
public const string TargetFramework = "TargetFramework";
}
}
| mit | C# |
bda8b29d597da26de42c341b014d6c85581d7f0e | Add ActualDelete to IDeletableEntityRepository. | yyankova/CountryFoodSubscribe,yyankova/CountryFoodSubscribe | CountryFoodSubscribe/CountryFood.Data.Common/IDeletableEntityRepository.cs | CountryFoodSubscribe/CountryFood.Data.Common/IDeletableEntityRepository.cs | namespace CountryFood.Data.Common
{
using System.Linq;
public interface IDeletableEntityRepository<T> : IRepository<T> where T : class
{
IQueryable<T> AllWithDeleted();
void ActualDelete(T entity);
}
}
| namespace CountryFood.Data.Common
{
using System.Linq;
public interface IDeletableEntityRepository<T> : IRepository<T> where T : class
{
IQueryable<T> AllWithDeleted();
}
}
| mit | C# |
0d8b0de71669ecd7078e262c6e308d64b51cf268 | Update comments for CopyMethod. | Azure/azure-storage-net-data-movement | lib/CopyMethod.cs | lib/CopyMethod.cs | //------------------------------------------------------------------------------
// <copyright file="CopyMethod.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
/// <summary>
/// Enum to indicate how the copying operation is handled in DataMovement Library.
/// </summary>
public enum CopyMethod
{
/// <summary>
/// To download data from source to memory, and upload the data from memory to destination.
/// </summary>
SyncCopy,
/// <summary>
/// To send a start copy request to azure storage to let it do the copying,
/// and monitor the copying progress until the copy completed.
/// </summary>
ServiceSideAsyncCopy,
/// <summary>
/// To copy content of each chunk with with Put Block From URL, Append Block From URL or Put Page From URL.
/// See <c>https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url</c> for Put Block From URL,
/// <c>https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url</c> for Append Block From URL,
/// <c>https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url</c> for Put Page From URL for details.
/// </summary>
ServiceSideSyncCopy
}
}
| //------------------------------------------------------------------------------
// <copyright file="CopyMethod.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
/// <summary>
/// Enum to indicate how the copying operation is handled in DataMovement Library.
/// </summary>
public enum CopyMethod
{
/// <summary>
/// To read data from source to memory and then write the data in memory to destination.
/// </summary>
SyncCopy,
/// <summary>
/// To send a start copy request to azure storage to let it do the copying,
/// and monitor the copying progress until the copy finished.
/// </summary>
ServiceSideAsyncCopy,
/// <summary>
/// To copy content of each chunk with with "Put Block From URL", "Append Block From URL" or "Put Page From URL".
/// </summary>
ServiceSideSyncCopy
}
}
| mit | C# |
f15f0d5edef28f7465a769d124f489b13b50d270 | Implement last test case. | tiesmaster/DebuggerStepThroughRemover,modulexcite/DebuggerStepThroughRemover | DebuggerStepThroughRemover/DebuggerStepThroughRemover/DiagnosticAnalyzer.cs | DebuggerStepThroughRemover/DebuggerStepThroughRemover/DiagnosticAnalyzer.cs | using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace DebuggerStepThroughRemover
{
// TODO: add ReSharper solution file with default setttings of resharper/C#
// ReSharper disable InconsistentNaming
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DebuggerStepThroughRemoverAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "DebuggerStepThroughRemover";
private static readonly LocalizableString Title = "Type is decorated with DebuggerStepThrough attribute";
private static readonly LocalizableString MessageFormat = "Type '{0}' is decorated with DebuggerStepThrough attribute";
private static readonly LocalizableString Description = "";
private const string Category = "Debugging";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
private static readonly string _targetAttributeName = nameof(DebuggerStepThroughAttribute).Replace(nameof(Attribute), string.Empty);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeClassDeclarationSyntax, SyntaxKind.ClassDeclaration);
}
private static void AnalyzeClassDeclarationSyntax(SyntaxNodeAnalysisContext context)
{
var classDeclarationNode = (ClassDeclarationSyntax)context.Node;
foreach(var attributeListSyntax in classDeclarationNode.AttributeLists)
{
foreach(var attributeSyntax in attributeListSyntax.Attributes)
{
var classContainsTargetAttribute = attributeSyntax.Name.GetText().ToString().EndsWith(_targetAttributeName);
if (classContainsTargetAttribute)
{
var diagnosticLocation = attributeListSyntax.Attributes.Count > 1
? attributeSyntax.GetLocation()
: attributeListSyntax.GetLocation();
var className = classDeclarationNode.Identifier.Text;
var diagnostic = Diagnostic.Create(Rule, diagnosticLocation, className);
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
} | using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace DebuggerStepThroughRemover
{
// TODO: add ReSharper solution file with default setttings of resharper/C#
// ReSharper disable InconsistentNaming
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DebuggerStepThroughRemoverAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "DebuggerStepThroughRemover";
private static readonly LocalizableString Title = "Type is decorated with DebuggerStepThrough attribute";
private static readonly LocalizableString MessageFormat = "Type '{0}' is decorated with DebuggerStepThrough attribute";
private static readonly LocalizableString Description = "";
private const string Category = "Debugging";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
private static readonly string _targetAttributeName = nameof(DebuggerStepThroughAttribute).Replace(nameof(Attribute), string.Empty);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeClassDeclarationSyntax, SyntaxKind.ClassDeclaration);
}
private static void AnalyzeClassDeclarationSyntax(SyntaxNodeAnalysisContext context)
{
var classDeclarationNode = (ClassDeclarationSyntax)context.Node;
foreach(var attributeListSyntax in classDeclarationNode.AttributeLists)
{
foreach(var attributeSyntax in attributeListSyntax.Attributes)
{
var classContainsTargetAttribute = attributeSyntax.Name.GetText().ToString().EndsWith(_targetAttributeName);
if (classContainsTargetAttribute)
{
var className = classDeclarationNode.Identifier.Text;
var diagnostic = Diagnostic.Create(Rule, attributeListSyntax.GetLocation(), className);
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
} | mit | C# |
6e5c4ed7c6c3e4890c1480d7ccac1d52b131c8cf | Revert "Remove empty override" | peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu | osu.Game/Rulesets/Mods/ModHidden.cs | osu.Game/Rulesets/Mods/ModHidden.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModHidden : ModWithVisibilityAdjustment, IApplicableToScoreProcessor
{
public override string Name => "Hidden";
public override string Acronym => "HD";
public override IconUsage? Icon => OsuIcon.ModHidden;
public override ModType Type => ModType.DifficultyIncrease;
public override bool Ranked => true;
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
// Default value of ScoreProcessor's Rank in Hidden Mod should be SS+
scoreProcessor.Rank.Value = ScoreRank.XH;
}
public ScoreRank AdjustRank(ScoreRank rank, double accuracy)
{
switch (rank)
{
case ScoreRank.X:
return ScoreRank.XH;
case ScoreRank.S:
return ScoreRank.SH;
default:
return rank;
}
}
protected override void ApplyIncreasedVisibilityState(DrawableHitObject hitObject, ArmedState state)
{
}
protected override void ApplyNormalVisibilityState(DrawableHitObject hitObject, ArmedState state)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModHidden : ModWithVisibilityAdjustment, IApplicableToScoreProcessor
{
public override string Name => "Hidden";
public override string Acronym => "HD";
public override IconUsage? Icon => OsuIcon.ModHidden;
public override ModType Type => ModType.DifficultyIncrease;
public override bool Ranked => true;
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
// Default value of ScoreProcessor's Rank in Hidden Mod should be SS+
scoreProcessor.Rank.Value = ScoreRank.XH;
}
public ScoreRank AdjustRank(ScoreRank rank, double accuracy)
{
switch (rank)
{
case ScoreRank.X:
return ScoreRank.XH;
case ScoreRank.S:
return ScoreRank.SH;
default:
return rank;
}
}
}
}
| mit | C# |
9c6a06c4d6354ada8a8eaf0cb91d8639f2092c2c | Add major American issuers | jcolag/CreditCardValidator | CreditCardRange/CreditCardRange/CreditCardType.cs | CreditCardRange/CreditCardRange/CreditCardType.cs | using System.ComponentModel;
namespace CreditCardProcessing
{
public enum CreditCardType
{
[Description("Unknown Issuer")]
Unknown,
[Description("American Express")]
AmEx,
[Description("Discover Card")]
Discover,
[Description("MasterCard")]
MasterCard,
[Description("Visa")]
Visa,
}
}
| namespace CreditCardProcessing
{
public enum CreditCardType
{
Unknown,
}
}
| agpl-3.0 | C# |
ca42905feb98d595e5e37a6831f0251af581a371 | fix failing unit tests | OBeautifulCode/OBeautifulCode.IO | OBeautifulCode.IO.Test/Properties/AssemblyInfo.cs | OBeautifulCode.IO.Test/Properties/AssemblyInfo.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
// 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("OBeautifulCode.IO.Test")]
[assembly: AssemblyDescription("OBeautifulCode.IO.Test")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("OBeautifulCode")]
[assembly: AssemblyProduct("OBeautifulCode.IO.Test")]
[assembly: AssemblyCopyright("Copyright (c) 2016 OBeautifulCode")]
[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("ac4d46a0-fc25-4ace-b418-af6333b2937d")]
// 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")]
[assembly: CLSCompliant(true)]
[assembly: CollectionBehavior(DisableTestParallelization = true)] | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
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("OBeautifulCode.IO.Test")]
[assembly: AssemblyDescription("OBeautifulCode.IO.Test")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("OBeautifulCode")]
[assembly: AssemblyProduct("OBeautifulCode.IO.Test")]
[assembly: AssemblyCopyright("Copyright (c) 2016 OBeautifulCode")]
[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("ac4d46a0-fc25-4ace-b418-af6333b2937d")]
// 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")]
[assembly: CLSCompliant(true)] | mit | C# |
f7235deb5f87a2416a876595f415b59fcbd9069d | Add MaskedConsoleInput#Get class stub | appharbor/appharbor-cli | src/AppHarbor/MaskedConsoleInput.cs | src/AppHarbor/MaskedConsoleInput.cs | using System;
namespace AppHarbor
{
public class MaskedConsoleInput
{
public string Get()
{
string input = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
input += key.KeyChar;
Console.Write("*");
}
else if (key.Key == ConsoleKey.Backspace && input.Length > 0)
{
input = input.Substring(0, (input.Length - 1));
Console.Write("\b \b");
}
}
while (key.Key != ConsoleKey.Enter);
return input;
}
}
}
| namespace AppHarbor
{
public class MaskedConsoleInput
{
}
}
| mit | C# |
cdc09a12f61e03f19fe1547355d5fcb5b95115d5 | Add Deconstruct and Flatten for Maybe<T?>. | chtoucas/Narvalo.NET,chtoucas/Narvalo.NET | src/Narvalo.Fx/Applicative/Maybe.cs | src/Narvalo.Fx/Applicative/Maybe.cs | // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Applicative
{
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// Provides a set of static and extension methods for <see cref="Maybe{T}"/>
/// and for querying objects that implement <see cref="IEnumerable{T}"/>
/// where T is of type <see cref="Maybe{S}"/>.
/// </summary>
public static partial class Maybe { }
// Provides extension methods for Maybe<T?> or Maybe<T> where T is a struct.
public static partial class Maybe
{
// Conversion from T? to Maybe<T>.
// NB: This method makes it impossible to create a Maybe<T?> **directly**.
public static Maybe<T> Of<T>(T? value) where T : struct
=> value.HasValue ? Of(value.Value) : Maybe<T>.None;
public static void Deconstruct<T>(
this Maybe<T?> @this, out bool isSome, out T value) where T : struct
{
isSome = @this.IsSome;
value = @this.IsSome && @this.Value.HasValue ? @this.Value.Value : default(T);
}
// Conversion from Maybe<T?> to Maybe<T>.
public static Maybe<T> Flatten<T>(this Maybe<T?> @this) where T : struct
=> @this.IsSome && @this.Value.HasValue
? Maybe.Of(@this.Value.Value)
: Maybe<T>.None;
// Conversion from Maybe<T> to T?.
public static T? ToNullable<T>(this Maybe<T> @this) where T : struct
=> @this.IsSome ? (T?)@this.Value : null;
// Conversion from Maybe<T?> to T?.
public static T? ToNullable<T>(this Maybe<T?> @this) where T : struct
=> @this.IsSome ? @this.Value : null;
}
// Provides extension methods for IEnumerable<Maybe<T>>.
public static partial class Maybe
{
public static IEnumerable<TSource> CollectAny<TSource>(this IEnumerable<Maybe<TSource>> @this)
{
Require.NotNull(@this, nameof(@this));
return CollectAnyIterator(@this);
}
private static IEnumerable<TSource> CollectAnyIterator<TSource>(IEnumerable<Maybe<TSource>> source)
{
Debug.Assert(source != null);
foreach (var item in source)
{
if (item.IsSome) { yield return item.Value; }
}
}
}
}
| // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Applicative
{
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// Provides a set of static and extension methods for <see cref="Maybe{T}"/>
/// and for querying objects that implement <see cref="IEnumerable{T}"/>
/// where T is of type <see cref="Maybe{S}"/>.
/// </summary>
public static partial class Maybe { }
// Provides extension methods for Maybe<T?> or Maybe<T> where T is a struct.
// When it comes to value types, there is really no reason to use Maybe<T> or Maybe<T?>
// instead of T?. NB: It is still possible to construct indirectly such objects via Bind().
public static partial class Maybe
{
// Conversion from T? to Maybe<T>.
// NB: This method makes it impossible to create a Maybe<T?> **directly**.
public static Maybe<T> Of<T>(T? value) where T : struct
=> value.HasValue ? Of(value.Value) : Maybe<T>.None;
// Conversion from Maybe<T> to T?.
public static T? ToNullable<T>(this Maybe<T> @this) where T : struct
=> @this.IsSome ? (T?)@this.Value : null;
// Conversion from Maybe<T?> to T?.
public static T? ToNullable<T>(this Maybe<T?> @this) where T : struct
=> @this.IsSome ? @this.Value : null;
}
// Provides extension methods for IEnumerable<Maybe<T>>.
public static partial class Maybe
{
public static IEnumerable<TSource> CollectAny<TSource>(this IEnumerable<Maybe<TSource>> @this)
{
Require.NotNull(@this, nameof(@this));
return CollectAnyIterator(@this);
}
private static IEnumerable<TSource> CollectAnyIterator<TSource>(IEnumerable<Maybe<TSource>> source)
{
Debug.Assert(source != null);
foreach (var item in source)
{
if (item.IsSome) { yield return item.Value; }
}
}
}
}
| bsd-2-clause | C# |
42000f3e17b6e76b9c8ba1a4465c5643f359f65d | Remove extraneous #if | nunit/nunit-console,nunit/nunit-console,nunit/nunit-console | src/Common/nunit/Env.cs | src/Common/nunit/Env.cs | // ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Text;
namespace NUnit
{
/// <summary>
/// Env is a static class that provides some of the features of
/// System.Environment that are not available under all runtimes
/// </summary>
public class Env
{
// Define NewLine to be used for this system
// NOTE: Since this is done at compile time for .NET CF,
// these binaries are not yet currently portable.
/// <summary>
/// The newline sequence in the current environment.
/// </summary>
#if PocketPC || WindowsCE || NETCF
public static readonly string NewLine = "\r\n";
#else
public static readonly string NewLine = Environment.NewLine;
#endif
/// <summary>
/// Path to the 'My Documents' folder
/// </summary>
#if PocketPC || WindowsCE || NETCF || PORTABLE
public static string DocumentFolder = @"\My Documents";
#else
public static string DocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
#endif
/// <summary>
/// Directory used for file output if not specified on commandline.
/// </summary>
#if SILVERLIGHT || PocketPC || WindowsCE || NETCF || PORTABLE
public static readonly string DefaultWorkDirectory = DocumentFolder;
#else
public static readonly string DefaultWorkDirectory = Environment.CurrentDirectory;
#endif
}
}
| // ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Text;
#if NUNIT
#endif
namespace NUnit
{
/// <summary>
/// Env is a static class that provides some of the features of
/// System.Environment that are not available under all runtimes
/// </summary>
public class Env
{
// Define NewLine to be used for this system
// NOTE: Since this is done at compile time for .NET CF,
// these binaries are not yet currently portable.
/// <summary>
/// The newline sequence in the current environment.
/// </summary>
#if PocketPC || WindowsCE || NETCF
public static readonly string NewLine = "\r\n";
#else
public static readonly string NewLine = Environment.NewLine;
#endif
/// <summary>
/// Path to the 'My Documents' folder
/// </summary>
#if PocketPC || WindowsCE || NETCF || PORTABLE
public static string DocumentFolder = @"\My Documents";
#else
public static string DocumentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
#endif
/// <summary>
/// Directory used for file output if not specified on commandline.
/// </summary>
#if SILVERLIGHT || PocketPC || WindowsCE || NETCF || PORTABLE
public static readonly string DefaultWorkDirectory = DocumentFolder;
#else
public static readonly string DefaultWorkDirectory = Environment.CurrentDirectory;
#endif
}
}
| mit | C# |
018adf7ffcd815cda8d3230e87d0c66fdb9a14ff | Call Bass.Free() after each test | EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework | osu.Framework.Tests/Audio/AudioThreadTest.cs | osu.Framework.Tests/Audio/AudioThreadTest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading;
using System.Threading.Tasks;
using ManagedBass;
using NUnit.Framework;
using osu.Framework.Audio.Track;
using osu.Framework.IO.Stores;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public abstract class AudioThreadTest
{
private AudioThread thread;
internal AudioManagerWithDeviceLoss Manager;
[SetUp]
public virtual void SetUp()
{
thread = new AudioThread();
var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.dll"), @"Resources");
Manager = new AudioManagerWithDeviceLoss(thread, store, store);
thread.Start();
}
[TearDown]
public void TearDown()
{
Assert.IsFalse(thread.Exited);
thread.Exit();
WaitForOrAssert(() => thread.Exited, "Audio thread did not exit in time");
Bass.Free();
}
public void CheckTrackIsProgressing(Track track)
{
// playback should be continuing after device change
for (int i = 0; i < 2; i++)
{
var checkAfter = track.CurrentTime;
WaitForOrAssert(() => track.CurrentTime > checkAfter, "Track time did not increase", 1000);
Assert.IsTrue(track.IsRunning);
}
}
/// <summary>
/// Waits for a specified condition to become true, or timeout reached.
/// </summary>
/// <param name="condition">The condition which should become true.</param>
/// <param name="message">A message to display on timeout.</param>
/// <param name="timeout">Timeout in milliseconds.</param>
public static void WaitForOrAssert(Func<bool> condition, string message, int timeout = 60000) =>
Assert.IsTrue(Task.Run(() =>
{
while (!condition()) Thread.Sleep(50);
}).Wait(timeout), message);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Audio.Track;
using osu.Framework.IO.Stores;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public abstract class AudioThreadTest
{
private AudioThread thread;
internal AudioManagerWithDeviceLoss Manager;
[SetUp]
public virtual void SetUp()
{
thread = new AudioThread();
var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.dll"), @"Resources");
Manager = new AudioManagerWithDeviceLoss(thread, store, store);
thread.Start();
}
[TearDown]
public void TearDown()
{
Assert.IsFalse(thread.Exited);
thread.Exit();
WaitForOrAssert(() => thread.Exited, "Audio thread did not exit in time");
}
public void CheckTrackIsProgressing(Track track)
{
// playback should be continuing after device change
for (int i = 0; i < 2; i++)
{
var checkAfter = track.CurrentTime;
WaitForOrAssert(() => track.CurrentTime > checkAfter, "Track time did not increase", 1000);
Assert.IsTrue(track.IsRunning);
}
}
/// <summary>
/// Waits for a specified condition to become true, or timeout reached.
/// </summary>
/// <param name="condition">The condition which should become true.</param>
/// <param name="message">A message to display on timeout.</param>
/// <param name="timeout">Timeout in milliseconds.</param>
public static void WaitForOrAssert(Func<bool> condition, string message, int timeout = 60000) =>
Assert.IsTrue(Task.Run(() =>
{
while (!condition()) Thread.Sleep(50);
}).Wait(timeout), message);
}
}
| mit | C# |
2600c8681ae02bdcd3bc9de4ec1ed60a0efb252a | Fix redundant this | smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework | osu.Framework/Text/TexturedCharacterGlyph.cs | osu.Framework/Text/TexturedCharacterGlyph.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Runtime.CompilerServices;
using osu.Framework.Graphics.Textures;
namespace osu.Framework.Text
{
public sealed class TexturedCharacterGlyph : ITexturedCharacterGlyph
{
public Texture Texture { get; }
public float XOffset => glyph.XOffset * ScaleAdjustment;
public float YOffset => glyph.YOffset * ScaleAdjustment;
public float XAdvance => glyph.XAdvance * ScaleAdjustment;
public char Character => glyph.Character;
public float Width => Texture.Width * ScaleAdjustment;
public float Height => Texture.Height * ScaleAdjustment;
public readonly float ScaleAdjustment;
private readonly CharacterGlyph glyph;
public TexturedCharacterGlyph(CharacterGlyph glyph, Texture texture, float scaleAdjustment)
{
this.glyph = glyph;
ScaleAdjustment = scaleAdjustment;
Texture = texture;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float GetKerning<T>(T lastGlyph)
where T : ICharacterGlyph
=> glyph.GetKerning(lastGlyph) * ScaleAdjustment;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Runtime.CompilerServices;
using osu.Framework.Graphics.Textures;
namespace osu.Framework.Text
{
public sealed class TexturedCharacterGlyph : ITexturedCharacterGlyph
{
public Texture Texture { get; }
public float XOffset => glyph.XOffset * ScaleAdjustment;
public float YOffset => glyph.YOffset * ScaleAdjustment;
public float XAdvance => glyph.XAdvance * ScaleAdjustment;
public char Character => glyph.Character;
public float Width => Texture.Width * ScaleAdjustment;
public float Height => Texture.Height * ScaleAdjustment;
public readonly float ScaleAdjustment;
private readonly CharacterGlyph glyph;
public TexturedCharacterGlyph(CharacterGlyph glyph, Texture texture, float scaleAdjustment)
{
this.glyph = glyph;
this.ScaleAdjustment = scaleAdjustment;
Texture = texture;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float GetKerning<T>(T lastGlyph)
where T : ICharacterGlyph
=> glyph.GetKerning(lastGlyph) * ScaleAdjustment;
}
}
| mit | C# |
ae7547bbdafdb7b3bdaae3c9386a423fd8f42ea1 | Fix up distance -> positional length comments. | EVAST9919/osu,ppy/osu,2yangk23/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,peppy/osu,Damnae/osu,ZLima12/osu,NeoAdonis/osu,Nabile-Rahmani/osu,tacchinotacchi/osu,smoogipoo/osu,ZLima12/osu,smoogipoo/osu,nyaamara/osu,peppy/osu-new,2yangk23/osu,osu-RP/osu-RP,johnneijzen/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,EVAST9919/osu,ppy/osu,peppy/osu,DrabWeb/osu,naoey/osu,NeoAdonis/osu,Frontear/osuKyzer,RedNesto/osu,Drezi126/osu,naoey/osu,naoey/osu,UselessToucan/osu,johnneijzen/osu,UselessToucan/osu | osu.Game/Modes/Objects/Types/IHasDistance.cs | osu.Game/Modes/Objects/Types/IHasDistance.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
namespace osu.Game.Modes.Objects.Types
{
/// <summary>
/// A HitObject that has a positional length.
/// </summary>
public interface IHasDistance : IHasEndTime
{
/// <summary>
/// The positional length of the HitObject.
/// </summary>
double Distance { get; }
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
namespace osu.Game.Modes.Objects.Types
{
/// <summary>
/// A HitObject that has a distance.
/// </summary>
public interface IHasDistance : IHasEndTime
{
/// <summary>
/// The distance of the HitObject.
/// </summary>
double Distance { get; }
}
}
| mit | C# |
6258fca3b6e71dd9a426a19ba04ccb58e136a4d3 | fix urlencode bug | fengyhack/csharp-sdk,qiniu/csharp-sdk | Qiniu/RS/GetPolicy.cs | Qiniu/RS/GetPolicy.cs | using System;
using System.Linq;
using Qiniu.Auth.digest;
using Qiniu.Conf;
namespace Qiniu.RS
{
/// <summary>
/// GetPolicy
/// </summary>
public class GetPolicy
{
public static string MakeRequest (string baseUrl, UInt32 expires = 3600, Mac mac = null)
{
if (mac == null) {
mac = new Mac (Config.ACCESS_KEY, Config.Encoding.GetBytes (Config.SECRET_KEY));
}
UInt32 deadline = (UInt32)((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000 + expires);
if (baseUrl.Contains ('?')) {
baseUrl += "&e=";
} else {
baseUrl += "?e=";
}
baseUrl += deadline;
string token = mac.Sign (Conf.Config.Encoding.GetBytes (baseUrl));
return string.Format ("{0}&token={1}", baseUrl, token);
}
public static string MakeBaseUrl (string domain, string key)
{
return string.Format ("http://{0}/{1}", domain, key);
}
}
}
| using System;
using System.Linq;
using Qiniu.Auth.digest;
using Qiniu.Conf;
namespace Qiniu.RS
{
/// <summary>
/// GetPolicy
/// </summary>
public class GetPolicy
{
public static string MakeRequest (string baseUrl, UInt32 expires = 3600, Mac mac = null)
{
if (mac == null) {
mac = new Mac (Config.ACCESS_KEY, Config.Encoding.GetBytes (Config.SECRET_KEY));
}
UInt32 deadline = (UInt32)((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000 + expires);
if (baseUrl.Contains ('?')) {
baseUrl += "&e=";
} else {
baseUrl += "?e=";
}
baseUrl += deadline;
string token = mac.Sign (Conf.Config.Encoding.GetBytes (baseUrl));
return string.Format ("{0}&token={1}", baseUrl, token);
}
public static string MakeBaseUrl (string domain, string key)
{
return string.Format ("http://{0}/{1}", domain, System.Web.HttpUtility.UrlEncode (key));
}
}
}
| mit | C# |
d07597ac8de21d5f3b0bfbd38bbe49ec60a2320a | Update cake.build | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | Android/ARCore/build.cake | Android/ARCore/build.cake | #load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "Default"));
var NUGET_VERSION = "1.7.0";
var AAR_VERSION = "1.7.0";
var AAR_URL = string.Format("https://dl.google.com/dl/android/maven2/com/google/ar/core/{0}/core-{0}.aar", AAR_VERSION);
var OBJ_VERSION = "0.3.0";
var OBJ_URL = string.Format("https://oss.sonatype.org/content/repositories/releases/de/javagl/obj/{0}/obj-{0}.jar", OBJ_VERSION);
var buildSpec = new BuildSpec () {
Libs = new [] {
new DefaultSolutionBuilder {
SolutionPath = "./ARCore.sln",
OutputFiles = new [] {
new OutputFileCopy {
FromFile = "./source/bin/Release/Xamarin.Google.ARCore.dll",
}
}
}
},
NuGets = new [] {
new NuGetInfo { NuSpec = "./nuget/Xamarin.Google.ARCore.nuspec", Version = NUGET_VERSION, RequireLicenseAcceptance = true },
},
};
Task ("externals")
.Does (() =>
{
var AAR_FILE = "./externals/arcore.aar";
var OBJ_JAR_FILE = "./externals/obj.jar";
if (!DirectoryExists ("./externals/"))
CreateDirectory ("./externals");
if (!FileExists (AAR_FILE))
DownloadFile (AAR_URL, AAR_FILE);
if (!FileExists (OBJ_JAR_FILE))
DownloadFile (OBJ_URL, OBJ_JAR_FILE);
});
Task ("clean").IsDependentOn ("clean-base").Does (() =>
{
if (DirectoryExists ("./externals"))
DeleteDirectory ("./externals", true);
});
SetupXamarinBuildTasks (buildSpec, Tasks, Task);
RunTarget (TARGET); | #load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "Default"));
var NUGET_VERSION = "1.6.0";
var AAR_VERSION = "1.6.0";
var AAR_URL = string.Format("https://dl.google.com/dl/android/maven2/com/google/ar/core/{0}/core-{0}.aar", AAR_VERSION);
var OBJ_VERSION = "0.3.0";
var OBJ_URL = string.Format("https://oss.sonatype.org/content/repositories/releases/de/javagl/obj/{0}/obj-{0}.jar", OBJ_VERSION);
var buildSpec = new BuildSpec () {
Libs = new [] {
new DefaultSolutionBuilder {
SolutionPath = "./ARCore.sln",
OutputFiles = new [] {
new OutputFileCopy {
FromFile = "./source/bin/Release/Xamarin.Google.ARCore.dll",
}
}
}
},
NuGets = new [] {
new NuGetInfo { NuSpec = "./nuget/Xamarin.Google.ARCore.nuspec", Version = NUGET_VERSION, RequireLicenseAcceptance = true },
},
};
Task ("externals")
.Does (() =>
{
var AAR_FILE = "./externals/arcore.aar";
var OBJ_JAR_FILE = "./externals/obj.jar";
if (!DirectoryExists ("./externals/"))
CreateDirectory ("./externals");
if (!FileExists (AAR_FILE))
DownloadFile (AAR_URL, AAR_FILE);
if (!FileExists (OBJ_JAR_FILE))
DownloadFile (OBJ_URL, OBJ_JAR_FILE);
});
Task ("clean").IsDependentOn ("clean-base").Does (() =>
{
if (DirectoryExists ("./externals"))
DeleteDirectory ("./externals", true);
});
SetupXamarinBuildTasks (buildSpec, Tasks, Task);
RunTarget (TARGET); | mit | C# |
6578283965473dd161b7bd14c5d504c43bf491dc | Add description | tobyclh/UnityCNTK,tobyclh/UnityCNTK | Assets/UnityCNTK/Model.cs | Assets/UnityCNTK/Model.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine.Assertions;
using System.Linq;
using UnityEngine;
using UnityEditor;
using CNTK;
using System.Timers;
using CNTK;
namespace UnityCNTK
{
// Unifying class that combine the use of both EvalDLL and CNTKLibrary
// The reason we have not dropped support for EvalDLL is that it expose more native function of the full API,
// which are very useful in general.
public abstract class Model : ScriptableObject
{
public Function function;
public Object input;
public Object output;
public abstract void LoadModel();
public abstract void Evaluate(DeviceDescriptor device);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine.Assertions;
using System.Linq;
using UnityEngine;
using UnityEditor;
using CNTK;
using System.Timers;
using CNTK.Extensibility.Managed;
namespace UnityCNTK
{
public abstract class Model : ScriptableObject
{
public Function function;
public Object input;
public Object output;
public abstract void LoadModel();
public abstract void Evaluate();
}
}
| mit | C# |
f79fa9f50ab0eaf96a8f05cae249f5d03f8e7819 | Bump version to 2.1.0 | mj1856/TimeZoneNames | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: AssemblyVersion("2.1.0.*")]
[assembly: AssemblyInformationalVersion("2.1.0")]
| using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: AssemblyVersion("2.0.1.*")]
[assembly: AssemblyInformationalVersion("2.0.1")]
| mit | C# |
afa5506415dc8690dbe87e59333932b20b428702 | Document and suppress an FxCop warning | badjer/Nvelope,badjer/Nvelope,TrinityWestern/Nvelope,TrinityWestern/Nvelope | src/Month.cs | src/Month.cs | //-----------------------------------------------------------------------
// <copyright file="Month.cs" company="TWU">
// MIT Licenced
// </copyright>
//-----------------------------------------------------------------------
namespace Nvelope
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Represents a month of the year
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue",
Justification = "There's no such thing as a 'default' or 'none' month.")]
public enum Month
{
/* These doc comments are stupid, but it keeps FxCop from getting made
* and it by looking at Microsoft's docs it seems to be in line with
* their practices */
/// <summary>
/// Indicates January
/// </summary>
January = 1,
/// <summary>
/// Indicates February
/// </summary>
February = 2,
/// <summary>
/// Indicates January
/// </summary>
March = 3,
/// <summary>
/// Indicates April
/// </summary>
April = 4,
/// <summary>
/// Indicates January
/// </summary>
May = 5,
/// <summary>
/// Indicates June
/// </summary>
June = 6,
/// <summary>
/// Indicates July
/// </summary>
July = 7,
/// <summary>
/// Indicates August
/// </summary>
August = 8,
/// <summary>
/// Indicates September
/// </summary>
September = 9,
/// <summary>
/// Indicates October
/// </summary>
October = 10,
/// <summary>
/// Indicates November
/// </summary>
November = 11,
/// <summary>
/// Indicates December
/// </summary>
December = 12
}
}
|
namespace Nvelope
{
public enum Month
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12
}
}
| mit | C# |
c4325788e3032c33b3a0224e0df66924972d3a1b | Stop collision with done | ArcticEcho/Hatman | Hatman/Commands/Should.cs | Hatman/Commands/Should.cs | using System.Text.RegularExpressions;
using ChatExchangeDotNet;
namespace Hatman.Commands
{
class Should : ICommand
{
private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|did|will|is|has|do(es)\b)", Extensions.RegOpts);
private readonly string[] phrases = new[]
{
"No.",
"Yes.",
"Yup.",
"Nope.",
"Indubitably",
"Never. Ever. *EVER*.",
"I'll tell ya, only if I get my coffee.",
"Nah.",
"Ask The Skeet.",
"... do I look like I know everything?",
"Ask me no questions, and I shall tell no lies.",
"Sure, when it rains imaginary internet points.",
"Yeah.",
"Ofc.",
"NOOOOOOOOOOOOOOOO",
"Sure..."
};
public Regex CommandPattern
{
get
{
return ptn;
}
}
public string Description
{
get
{
return "Decides whether or not something should happen.";
}
}
public string Usage
{
get
{
return "(sh|[wc])ould|will|did and many words alike";
}
}
public void ProcessMessage(Message msg, ref Room rm)
{
rm.PostReplyFast(msg, phrases.PickRandom());
}
}
}
| using System.Text.RegularExpressions;
using ChatExchangeDotNet;
namespace Hatman.Commands
{
class Should : ICommand
{
private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|did|will|is|has|do)", Extensions.RegOpts);
private readonly string[] phrases = new[]
{
"No.",
"Yes.",
"Yup.",
"Nope.",
"Indubitably",
"Never. Ever. *EVER*.",
"I'll tell ya, only if I get my coffee.",
"Nah.",
"Ask The Skeet.",
"... do I look like I know everything?",
"Ask me no questions, and I shall tell no lies.",
"Sure, when it rains imaginary internet points.",
"Yeah.",
"Ofc.",
"NOOOOOOOOOOOOOOOO",
"Sure..."
};
public Regex CommandPattern
{
get
{
return ptn;
}
}
public string Description
{
get
{
return "Decides whether or not something should happen.";
}
}
public string Usage
{
get
{
return "(sh|[wc])ould|will|did and many words alike";
}
}
public void ProcessMessage(Message msg, ref Room rm)
{
rm.PostReplyFast(msg, phrases.PickRandom());
}
}
}
| isc | C# |
a11d28db1f929d0dc307abe1585ead0940fef493 | Test Scan being lazy | anders9ustafsson/morelinq-portable,anders9ustafsson/morelinq-portable,anders9ustafsson/morelinq-portable | MoreLinq.Test/ScanTest.cs | MoreLinq.Test/ScanTest.cs | #region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Linq;
using NUnit.Framework;
namespace MoreLinq.Test
{
[TestFixture]
public class ScanTest
{
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ScanEmpty()
{
(new int[] { }).Scan(SampleData.Plus).Count();
}
[Test]
public void ScanSum()
{
var result = SampleData.Values.Scan(SampleData.Plus);
var gold = SampleData.Values.PreScan(SampleData.Plus, 0).Zip(SampleData.Values, SampleData.Plus);
result.AssertSequenceEqual(gold);
}
[Test]
public void ScanIsLazy()
{
new BreakingSequence<object>().Scan<object>(delegate { throw new NotImplementedException(); });
}
}
}
| #region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Linq;
using NUnit.Framework;
namespace MoreLinq.Test
{
[TestFixture]
public class ScanTest
{
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ScanEmpty()
{
(new int[] { }).Scan(SampleData.Plus).Count();
}
[Test]
public void ScanSum()
{
var result = SampleData.Values.Scan(SampleData.Plus);
var gold = SampleData.Values.PreScan(SampleData.Plus, 0).Zip(SampleData.Values, SampleData.Plus);
result.AssertSequenceEqual(gold);
}
}
}
| apache-2.0 | C# |
8843ce8a2c0bc2100a8a38d23cd8514a0c70bc07 | Fix #427 - Add required check for KeysHeadings | SusanaL/Glimpse,elkingtonmcb/Glimpse,paynecrl97/Glimpse,dudzon/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,dudzon/Glimpse,gabrielweyer/Glimpse,codevlabs/Glimpse,flcdrg/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,codevlabs/Glimpse,SusanaL/Glimpse,Glimpse/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,dudzon/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,sorenhl/Glimpse,flcdrg/Glimpse,codevlabs/Glimpse,Glimpse/Glimpse,gabrielweyer/Glimpse,SusanaL/Glimpse,paynecrl97/Glimpse,sorenhl/Glimpse,rho24/Glimpse | source/Glimpse.Core/Framework/TabMetadata.cs | source/Glimpse.Core/Framework/TabMetadata.cs | namespace Glimpse.Core.Framework
{
/// <summary>
/// Contains any metadata associated with a given tab.
/// </summary>
public class TabMetadata
{
/// <summary>
/// Gets or sets the documentation Uri.
/// </summary>
/// <value>
/// The documentation URI.
/// </value>
public string DocumentationUri { get; set; }
/// <summary>
/// Gets or sets the layout override instructions.
/// </summary>
/// <value>
/// The layout.
/// </value>
public object Layout { get; set; }
/// <summary>
/// Gets or sets wheather root level objects should be pivoted when displayed.
/// </summary>
/// <value>
/// Keys Headings.
/// </value>
public bool KeysHeadings { get; set; }
/// <summary>
/// Gets a value indicating whether this instance has metadata.
/// </summary>
/// <value>
/// <c>true</c> if this instance has metadata; otherwise, <c>false</c>.
/// </value>
public bool HasMetadata
{
get
{
return !string.IsNullOrEmpty(DocumentationUri) || Layout != null || KeysHeadings;
}
}
}
} | namespace Glimpse.Core.Framework
{
/// <summary>
/// Contains any metadata associated with a given tab.
/// </summary>
public class TabMetadata
{
/// <summary>
/// Gets or sets the documentation Uri.
/// </summary>
/// <value>
/// The documentation URI.
/// </value>
public string DocumentationUri { get; set; }
/// <summary>
/// Gets or sets the layout override instructions.
/// </summary>
/// <value>
/// The layout.
/// </value>
public object Layout { get; set; }
/// <summary>
/// Gets or sets wheather root level objects should be pivoted when displayed.
/// </summary>
/// <value>
/// Keys Headings.
/// </value>
public bool KeysHeadings { get; set; }
/// <summary>
/// Gets a value indicating whether this instance has metadata.
/// </summary>
/// <value>
/// <c>true</c> if this instance has metadata; otherwise, <c>false</c>.
/// </value>
public bool HasMetadata
{
get
{
return !string.IsNullOrEmpty(DocumentationUri) || this.Layout != null;
}
}
}
} | apache-2.0 | C# |
1bc81d343cc0a44db5805c8b57fc382bbce7ff8f | correct delay calc | AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us | src/Maw.Cache.Initializer/DelayCalculator.cs | src/Maw.Cache.Initializer/DelayCalculator.cs | namespace Maw.Cache.Initializer;
internal class DelayCalculator
: IDelayCalculator
{
public int CalculateRandomizedDelay(int baseDelayMs, float fluctuationPercentage)
{
if(fluctuationPercentage <= 0)
{
return baseDelayMs;
}
var flux = Convert.ToInt32(baseDelayMs * fluctuationPercentage);
var min = Math.Max(0, baseDelayMs - flux);
var max = baseDelayMs + flux;
var rand = new Random();
return Convert.ToInt32(rand.NextInt64(min, max));
}
}
| namespace Maw.Cache.Initializer;
internal class DelayCalculator
: IDelayCalculator
{
public int CalculateRandomizedDelay(int baseDelayMs, float fluctuationPercentage)
{
if(fluctuationPercentage <= 0)
{
return baseDelayMs;
}
var flux = Convert.ToInt32(baseDelayMs * fluctuationPercentage);
var min = Math.Min(0, baseDelayMs - flux);
var max = baseDelayMs + flux;
var rand = new Random();
return Convert.ToInt32(rand.NextInt64(min, max));
}
}
| mit | C# |
117d3b6f86a5ce840a1928d56001aad2f703d616 | Convert rollover lifecycle action to accept max size as a string and not long? #3775 | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/XPack/Ilm/Actions/RolloverAction.cs | src/Nest/XPack/Ilm/Actions/RolloverAction.cs | using System.Runtime.Serialization;
namespace Nest
{
/// <summary>
/// The Rollover Action rolls an alias over to a new index when the existing index meets one of the rollover conditions.
/// </summary>
/// <remarks>
/// Phases allowed: hot.
/// </remarks>
public interface IRolloverLifecycleAction : ILifecycleAction
{
/// <summary>
/// Max time elapsed from index creation.
/// </summary>
[DataMember(Name = "max_age")]
Time MaximumAge { get; set; }
/// <summary>
/// Max number of documents an index is to contain before rolling over.
/// </summary>
[DataMember(Name = "max_docs")]
long? MaximumDocuments { get; set; }
/// <summary>
/// Max primary shard index storage size using byte notation (e.g. $0gb, 100mb...)
/// </summary>
[DataMember(Name = "max_size")]
string MaximumSize { get; set; }
}
public class RolloverLifecycleAction : IRolloverLifecycleAction
{
/// <inheritdoc />
public Time MaximumAge { get; set; }
/// <inheritdoc />
public long? MaximumDocuments { get; set; }
/// <inheritdoc />
public string MaximumSize { get; set; }
}
public class RolloverLifecycleActionDescriptor
: DescriptorBase<RolloverLifecycleActionDescriptor, IRolloverLifecycleAction>, IRolloverLifecycleAction
{
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumAge" />
Time IRolloverLifecycleAction.MaximumAge { get; set; }
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumDocuments" />
long? IRolloverLifecycleAction.MaximumDocuments { get; set; }
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumSize" />
string IRolloverLifecycleAction.MaximumSize { get; set; }
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumSize" />
public RolloverLifecycleActionDescriptor MaximumSize(string maximumSize) => Assign(maximumSize, (a, v) => a.MaximumSize = maximumSize);
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumAge" />
public RolloverLifecycleActionDescriptor MaximumAge(Time maximumAge) => Assign(maximumAge, (a, v) => a.MaximumAge = maximumAge);
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumDocuments" />
public RolloverLifecycleActionDescriptor MaximumDocuments(long? maximumDocuments)
=> Assign(maximumDocuments, (a, v) => a.MaximumDocuments = maximumDocuments);
}
}
| using System.Runtime.Serialization;
namespace Nest
{
/// <summary>
/// The Rollover Action rolls an alias over to a new index when the existing index meets one of the rollover conditions.
/// </summary>
/// <remarks>
/// Phases allowed: hot.
/// </remarks>
public interface IRolloverLifecycleAction : ILifecycleAction
{
/// <summary>
/// Max time elapsed from index creation.
/// </summary>
[DataMember(Name = "max_age")]
Time MaximumAge { get; set; }
/// <summary>
/// Max number of documents an index is to contain before rolling over.
/// </summary>
[DataMember(Name = "max_docs")]
long? MaximumDocuments { get; set; }
/// <summary>
/// Max primary shard index storage size in bytes.
/// </summary>
[DataMember(Name = "max_size")]
long? MaximumSize { get; set; }
}
public class RolloverLifecycleAction : IRolloverLifecycleAction
{
/// <inheritdoc />
public Time MaximumAge { get; set; }
/// <inheritdoc />
public long? MaximumDocuments { get; set; }
/// <inheritdoc />
public long? MaximumSize { get; set; }
}
public class RolloverLifecycleActionDescriptor
: DescriptorBase<RolloverLifecycleActionDescriptor, IRolloverLifecycleAction>, IRolloverLifecycleAction
{
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumAge" />
Time IRolloverLifecycleAction.MaximumAge { get; set; }
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumDocuments" />
long? IRolloverLifecycleAction.MaximumDocuments { get; set; }
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumSize" />
long? IRolloverLifecycleAction.MaximumSize { get; set; }
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumSize" />
public RolloverLifecycleActionDescriptor MaximumSize(long? maximumSize) => Assign(maximumSize, (a, v) => a.MaximumSize = maximumSize);
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumAge" />
public RolloverLifecycleActionDescriptor MaximumAge(Time maximumAge) => Assign(maximumAge, (a, v) => a.MaximumAge = maximumAge);
/// <inheritdoc cref="IRolloverLifecycleAction.MaximumDocuments" />
public RolloverLifecycleActionDescriptor MaximumDocuments(long? maximumDocuments)
=> Assign(maximumDocuments, (a, v) => a.MaximumDocuments = maximumDocuments);
}
}
| apache-2.0 | C# |
29a54be946433db82b1da9ca0015be89804ed4d2 | Update DotNetVersionFinder | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/Utils/DotNetVersionFinder.cs | src/SyncTrayzor/Utils/DotNetVersionFinder.cs | using Microsoft.Win32;
using System;
using System.Collections.Generic;
namespace SyncTrayzor.Utils
{
public static class DotNetVersionFinder
{
// See https://msdn.microsoft.com/en-us/library/hh925568.aspx#net_d
private static readonly Dictionary<int, string> versionMapping = new Dictionary<int, string>()
{
{ 378389, "4.5" },
{ 378675, "4.5.1 on Windows 8.1 or Windows Server 2012 R2" },
{ 378758, "4.5.1 on WIndows 8, Windows 7 SPI1, or Windows Vista SP2" },
{ 379893, "4.5.2" },
{ 393295, "4.6 on Windows 10" },
{ 393297, "4.6 on non-Windows 10" },
{ 394254, "4.6.1 on Windows 10 November Update systems" },
{ 394271, "4.6.1 on non-Windows 10 November Update systems" },
{ 394802, "4.6.2 on Windows 10 Anniversary Update systems" },
{ 394806, "4.6.2 on non-Windows 10 Anniversary Update systems" },
{ 460798, "4.7 on Windows 10 Creators Update systems" },
};
public static string FindDotNetVersion()
{
try
{
using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
return $"{DescriptionForReleaseKey(releaseKey)} ({releaseKey})";
}
}
catch (Exception e)
{
return $"Unknown ({e.Message})";
}
}
private static string DescriptionForReleaseKey(int releaseKey)
{
if (!versionMapping.TryGetValue(releaseKey, out var description))
description = "Unknown";
return description;
}
}
}
| using Microsoft.Win32;
using System;
using System.Collections.Generic;
namespace SyncTrayzor.Utils
{
public static class DotNetVersionFinder
{
// See https://msdn.microsoft.com/en-us/library/hh925568.aspx#net_d
private static readonly Dictionary<int, string> versionMapping = new Dictionary<int, string>()
{
{ 378389, "4.5" },
{ 378675, "4.5.1 on Windows 8.1 or Windows Server 2012 R2" },
{ 378758, "4.5.1 on WIndows 8, Wwndows 7 SPI1, or Windows Vista SP2" },
{ 379893, "4.5.2" },
{ 393295, "4.6 on Windows 10" },
{ 393297, "4.6 on all other OS versions" },
{ 394254, "4.6.1 on Windows 10 November Update systems" },
{ 394271, "4.6.1 on all other OS versions" },
};
public static string FindDotNetVersion()
{
try
{
using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
return $"{DescriptionForReleaseKey(releaseKey)} ({releaseKey})";
}
}
catch (Exception e)
{
return $"Unknown ({e.Message})";
}
}
private static string DescriptionForReleaseKey(int releaseKey)
{
if (!versionMapping.TryGetValue(releaseKey, out var description))
description = "Unknown";
return description;
}
}
}
| mit | C# |
b06f2ff5e445ac6cf51394a55872a7ca53708b54 | Fix after spelling mistake | dreamnucleus/Commands | Slipstream.CommonDotNet.Commands.Playground/ExceptionNotification.cs | Slipstream.CommonDotNet.Commands.Playground/ExceptionNotification.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Slipstream.CommonDotNet.Commands.Notifications;
namespace Slipstream.CommonDotNet.Commands.Playground
{
public class ExceptionNotification : IExceptionNotification<FakeCommand>
{
public Task OnExceptionAsync(FakeCommand command, Exception exception)
{
Console.WriteLine("OnExecptionAsync");
return Task.FromResult(0);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Slipstream.CommonDotNet.Commands.Notifications;
namespace Slipstream.CommonDotNet.Commands.Playground
{
public class ExceptionNotification : IExceptionNotification<FakeCommand>
{
public Task OnExecptionAsync(FakeCommand command, Exception exception)
{
Console.WriteLine("OnExecptionAsync");
return Task.FromResult(0);
}
}
}
| mit | C# |
9e20cb66a4635e6ab9962dc4afeafb3b93149c6e | Add doc tags. | jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | vision/api/DetectLabels/DetectLabels.cs | vision/api/DetectLabels/DetectLabels.cs | // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START all]
// [START import_libraries]
using Google.Cloud.Vision.V1;
using System;
// [END import_libraries]
namespace GoogleCloudSamples
{
public class DetectLabels
{
// [START run_application]
static readonly string s_usage = @"DetectLabels image-file
Use the Google Cloud Vision API to detect labels in the image.";
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine(s_usage);
return;
}
Detect(args[0]);
}
// [END run_application]
static void Detect(string imageFilePath)
{
// [START authenticate]
var client = ImageAnnotatorClient.Create();
// [END authenticate]
// [START construct_request]
var image = Image.FromFile(imageFilePath);
// [END construct_request]
// [START detect_labels]
var response = client.DetectLabels(image);
// [END detect_labels]
// [START parse_response]
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
// [END parse_response]
}
}
}
// [END all]
| // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START all]
// [START import_libraries]
using Google.Cloud.Vision.V1;
using System;
// [END import_libraries]
namespace GoogleCloudSamples
{
public class DetectLabels
{
// [START run_application]
static readonly string s_usage = @"DetectLabels image-file
Use the Google Cloud Vision API to detect labels in the image.";
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine(s_usage);
return;
}
Detect(args[0]);
}
// [END run_application]
static void Detect(string imageFilePath)
{
// [START authenticate]
var client = ImageAnnotatorClient.Create();
// [END authenticate]
// [START detect_labels]
var response = client.DetectLabels(Image.FromFile(imageFilePath));
// [END detect_labels]
// [START parse_response]
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
// [END parse_response]
}
}
}
// [END all]
| apache-2.0 | C# |
d3269ff87fef1184535d08762bbcfe5b4c3e3b78 | Add XML description for Authentication Scheme | damonbarry/azure-iot-sdks-1,damonbarry/azure-iot-sdks-1,oriolpinol/azure-iot-sdks,Eclo/azure-iot-sdks,damonbarry/azure-iot-sdks-1,Eclo/azure-iot-sdks,dominicbetts/azure-iot-sdks,Eclo/azure-iot-sdks,Eclo/azure-iot-sdks,kevinledinh/azure-iot-sdks,dominicbetts/azure-iot-sdks,kevinledinh/azure-iot-sdks,kevinledinh/azure-iot-sdks,Eclo/azure-iot-sdks,kevinledinh/azure-iot-sdks,Eclo/azure-iot-sdks,oriolpinol/azure-iot-sdks,Eclo/azure-iot-sdks,kevinledinh/azure-iot-sdks,damonbarry/azure-iot-sdks-1,dominicbetts/azure-iot-sdks,kevinledinh/azure-iot-sdks,dominicbetts/azure-iot-sdks,dominicbetts/azure-iot-sdks,damonbarry/azure-iot-sdks-1,damonbarry/azure-iot-sdks-1,Eclo/azure-iot-sdks,damonbarry/azure-iot-sdks-1,oriolpinol/azure-iot-sdks,kevinledinh/azure-iot-sdks,oriolpinol/azure-iot-sdks,oriolpinol/azure-iot-sdks,kevinledinh/azure-iot-sdks,dominicbetts/azure-iot-sdks,dominicbetts/azure-iot-sdks,kevinledinh/azure-iot-sdks,Eclo/azure-iot-sdks,oriolpinol/azure-iot-sdks,damonbarry/azure-iot-sdks-1,oriolpinol/azure-iot-sdks,oriolpinol/azure-iot-sdks,dominicbetts/azure-iot-sdks | csharp/device/Microsoft.Azure.Devices.Client/AuthenticationScheme.cs | csharp/device/Microsoft.Azure.Devices.Client/AuthenticationScheme.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
/// <summary>
/// Specifies the Authentication Scheme used by Device Client
/// </summary>
public enum S
{
// Shared Access Signature
SAS = 0,
// X509 Certificate
X509 = 1
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
public enum AuthenticationScheme
{
// Shared Access Signature
SAS = 0,
// X509 Certificate
X509 = 1
}
}
| mit | C# |
6be1daa7028a22e5d2245c12e3d054f0d51b4e9f | Remove shouldDeployGraphDocumentation from setup.cake | cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe | setup.cake | setup.cake | #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Recipe",
repositoryOwner: "cake-contrib",
repositoryName: "Cake.Recipe",
appVeyorAccountName: "cakecontrib");
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context);
Task("Run-Integration-Tests")
.IsDependentOn("Default")
.Does(() => {
CakeExecuteScript("./test.cake",
new CakeSettings {
Arguments = new Dictionary<string, string>{
{ "recipe-version", BuildParameters.Version.SemVersion },
{ "verbosity", Context.Log.Verbosity.ToString("F") }
}});
});
Build.RunNuGet(); | #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Recipe",
repositoryOwner: "cake-contrib",
repositoryName: "Cake.Recipe",
appVeyorAccountName: "cakecontrib",
shouldDeployGraphDocumentation: true);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context);
Task("Run-Integration-Tests")
.IsDependentOn("Default")
.Does(() => {
CakeExecuteScript("./test.cake",
new CakeSettings {
Arguments = new Dictionary<string, string>{
{ "recipe-version", BuildParameters.Version.SemVersion },
{ "verbosity", Context.Log.Verbosity.ToString("F") }
}});
});
Build.RunNuGet(); | mit | C# |
3ff3ba7ec3f087bf6bb8c8841b148bff333676e8 | Implement unwrapOr | Winwardo/ResultType | ResultType/Result.cs | ResultType/Result.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResultType
{
public class Result<T, E> : IResult<T, E>
{
private readonly bool ok;
T value;
E error;
public static Result<T, E> Ok(T value)
{
return new Result<T, E>(value, default(E));
}
public static Result<T, E> Error(E error)
{
return new Result<T, E>(default(T), error);
}
private Result(T value, E error)
{
this.value = value;
this.error = error;
if (value == null || error != null)
{
ok = false;
}
else
{
ok = true;
}
}
public bool isError()
{
return !ok;
}
public bool isOk()
{
return ok;
}
public T unwrap()
{
if (ok)
{
return value;
}
else
{
throw new AttemptedToUnwrapErrorException();
}
}
public T unwrapOr(T other)
{
if (ok)
{
return value;
}
else
{
return other;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResultType
{
public class Result<T, E> : IResult<T, E>
{
private readonly bool ok;
T value;
E error;
public static Result<T, E> Ok(T value)
{
return new Result<T, E>(value, default(E));
}
public static Result<T, E> Error(E error)
{
return new Result<T, E>(default(T), error);
}
private Result(T value, E error)
{
this.value = value;
this.error = error;
if (value == null || error != null)
{
ok = false;
}
else
{
ok = true;
}
}
public bool isError()
{
return !ok;
}
public bool isOk()
{
return ok;
}
public T unwrap()
{
if (ok)
{
return value;
}
else
{
throw new AttemptedToUnwrapErrorException();
}
}
public T unwrapOr(T other)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
8d899f4e7742e93b8afa0432e865685e3b92e71f | Apply changes to the BreakTracker and more adjustment | NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipoo/osu | osu.Game/Screens/Play/BreakTracker.cs | osu.Game/Screens/Play/BreakTracker.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.Timing;
using osu.Game.Rulesets.Scoring;
using osu.Game.Utils;
namespace osu.Game.Screens.Play
{
public class BreakTracker : Component
{
private readonly ScoreProcessor scoreProcessor;
private readonly double gameplayStartTime;
private readonly PeriodTracker tracker = new PeriodTracker();
/// <summary>
/// Whether the gameplay is currently in a break.
/// </summary>
public IBindable<bool> IsBreakTime => isBreakTime;
private readonly BindableBool isBreakTime = new BindableBool();
public IReadOnlyList<BreakPeriod> Breaks
{
set
{
isBreakTime.Value = false;
tracker.Periods = value?.Where(b => b.HasEffect)
.Select(b => new Period(b.StartTime, b.EndTime - BreakOverlay.BREAK_FADE_DURATION));
}
}
public BreakTracker(double gameplayStartTime = 0, ScoreProcessor scoreProcessor = null)
{
this.gameplayStartTime = gameplayStartTime;
this.scoreProcessor = scoreProcessor;
}
protected override void Update()
{
base.Update();
var time = Clock.CurrentTime;
isBreakTime.Value = tracker.Contains(time)
|| time < gameplayStartTime
|| scoreProcessor?.HasCompleted == 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 System.Collections.Generic;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.Timing;
using osu.Game.Lists;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Play
{
public class BreakTracker : Component
{
private readonly ScoreProcessor scoreProcessor;
private readonly double gameplayStartTime;
/// <summary>
/// Whether the gameplay is currently in a break.
/// </summary>
public IBindable<bool> IsBreakTime => isBreakTime;
private readonly BindableBool isBreakTime = new BindableBool();
private readonly IntervalList<double> breakIntervals = new IntervalList<double>();
public IReadOnlyList<BreakPeriod> Breaks
{
set
{
isBreakTime.Value = false;
breakIntervals.Clear();
foreach (var b in value)
{
if (!b.HasEffect)
continue;
breakIntervals.Add(b.StartTime, b.EndTime - BreakOverlay.BREAK_FADE_DURATION);
}
}
}
public BreakTracker(double gameplayStartTime = 0, ScoreProcessor scoreProcessor = null)
{
this.gameplayStartTime = gameplayStartTime;
this.scoreProcessor = scoreProcessor;
}
protected override void Update()
{
base.Update();
var time = Clock.CurrentTime;
isBreakTime.Value = breakIntervals.IsInAnyInterval(time)
|| time < gameplayStartTime
|| scoreProcessor?.HasCompleted == true;
}
}
}
| mit | C# |
cb5cf1a81e15c61a47591d19cf222e89ee4ee2e7 | Remove comment from other project | Frozenfire92/UnityScripts | Scripts/TimeColor.cs | Scripts/TimeColor.cs | /* TimeColor.cs
*
* Author: Joel Kuntz - github.com/Frozenfire92
* Started: December 19 2014
* Updated: December 20 2014
* License: Public Domain
*
* Attach this script to a Unity 4.6 UI/Text object.
* It will update the text with the time and hex value
* afterwards it updates the main cameras background color to match it.
*
* Inspired by http://whatcolourisit.scn9a.org/
* HexToColor from http://wiki.unity3d.com/index.php?title=HexConverter
*/
using UnityEngine;
using UnityEngine.UI;
using System;
public class TimeColor : MonoBehaviour {
private DateTime time;
private Camera cam;
private Text textObj;
private string doubleZero = "00";
private string hex;
private Color32 color;
private bool toggleText = true;
void Start()
{
// Set references
cam = Camera.main;
textObj = gameObject.GetComponent<Text>();
}
void Update ()
{
// Get current time
time = DateTime.Now;
// Reset and build hex string
hex = "";
// Hour
if (time.Hour == 0) hex += doubleZero;
else if (time.Hour > 0 && time.Hour < 10) hex += ("0" + time.Hour);
else hex += time.Hour;
// Minute
if (time.Minute == 0) hex += doubleZero;
else if (time.Minute > 0 && time.Minute < 10) hex += ("0" + time.Minute);
else hex += time.Minute;
// Second
if (time.Second == 0) hex += doubleZero;
else if (time.Second > 0 && time.Second < 10) hex += ("0" + time.Second);
else hex += time.Second;
// Get color, update text & camera
color = HexToColor(hex);
textObj.text = (toggleText) ? hex.Substring(0,2) + ":" + hex.Substring(2,2) + ":" + hex.Substring(4,2) + "\n#" + hex;
cam.backgroundColor = color;
}
// For UI to toggle the text on/off while maintaining camera color change
public void ToggleText ()
{
toggleText = !toggleText;
}
// Converts a string hex color ("123456") to Unity Color
private Color32 HexToColor(string HexVal)
{
// Convert each set of 2 digits to its corresponding byte value
byte R = byte.Parse(HexVal.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
byte G = byte.Parse(HexVal.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
byte B = byte.Parse(HexVal.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
return new Color32(R, G, B, 255);
}
}
| /* TimeColor.cs
*
* Author: Joel Kuntz - github.com/Frozenfire92
* Started: December 19 2014
* Updated: December 20 2014
* License: Public Domain
*
* Attach this script to a Unity 4.6 UI/Text object.
* It will update the text with the time, hex value, and rgb
* afterwards it updates the main cameras background color to match it.
*
* Inspired by http://whatcolourisit.scn9a.org/
* HexToColor from http://wiki.unity3d.com/index.php?title=HexConverter
*/
using UnityEngine;
using UnityEngine.UI;
using System;
public class TimeColor : MonoBehaviour {
private DateTime time;
private Camera cam;
private Text textObj;
private string doubleZero = "00";
private string hex;
private Color32 color;
private bool toggleText = true;
void Start()
{
// Set references
cam = Camera.main;
textObj = gameObject.GetComponent<Text>();
}
void Update ()
{
// Get current time
time = DateTime.Now;
// Reset and build hex string
hex = "";
// Hour
if (time.Hour == 0) hex += doubleZero;
else if (time.Hour > 0 && time.Hour < 10) hex += ("0" + time.Hour);
else hex += time.Hour;
// Minute
if (time.Minute == 0) hex += doubleZero;
else if (time.Minute > 0 && time.Minute < 10) hex += ("0" + time.Minute);
else hex += time.Minute;
// Second
if (time.Second == 0) hex += doubleZero;
else if (time.Second > 0 && time.Second < 10) hex += ("0" + time.Second);
else hex += time.Second;
// Get color, update text & camera
color = HexToColor(hex);
textObj.text = (toggleText) ? hex.Substring(0,2) + ":" + hex.Substring(2,2) + ":" + hex.Substring(4,2) + "\n#" + hex;
cam.backgroundColor = color;
}
// For UI to toggle the text on/off while maintaining camera color change
public void ToggleText ()
{
toggleText = !toggleText;
}
// Converts a string hex color ("123456") to Unity Color
private Color32 HexToColor(string HexVal)
{
// Convert each set of 2 digits to its corresponding byte value
byte R = byte.Parse(HexVal.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
byte G = byte.Parse(HexVal.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
byte B = byte.Parse(HexVal.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
return new Color32(R, G, B, 255);
}
}
| unlicense | C# |
6f79e72b1b941e4a5723008b5b74daa94077ca3b | Fix bug in artifact.cake | fwinkelbauer/Bumpy | Source/artifact.cake | Source/artifact.cake | private const string ArtifactsDirectory = "../Artifacts";
private const string ChocolateyDirectory = ArtifactsDirectory + "/Chocolatey";
private const string NuGetDirectory = ArtifactsDirectory + "/NuGet";
void CleanArtifacts()
{
CleanDirectory(ArtifactsDirectory);
}
void StoreBuildArtifacts(string projectName, string filePattern)
{
StoreBuildArtifacts(projectName, GetFiles(filePattern));
}
void StoreBuildArtifacts(string projectName, IEnumerable<FilePath> filePaths)
{
var dir = $"{ArtifactsDirectory}/Build/{projectName}";
EnsureDirectoryExists(dir);
Information("Copying artifacts to {0}", dir);
CopyFiles(filePaths, dir, true);
DeleteFiles($"{dir}/*.lastcodeanalysissucceeded");
DeleteFiles($"{dir}/*.CodeAnalysisLog.xml");
}
void PublishChocolateyArtifact(string packageId, string pushSource)
{
var files = GetFiles($"{ChocolateyDirectory}/{packageId}/*.nupkg");
ChocolateyPush(files, new ChocolateyPushSettings { Source = pushSource });
}
void StoreChocolateyArtifact(FilePath nuspecPath)
{
var dir = $"{ChocolateyDirectory}/{nuspecPath.GetFilenameWithoutExtension()}";
EnsureDirectoryExists(dir);
ChocolateyPack(nuspecPath, new ChocolateyPackSettings { OutputDirectory = dir });
}
void PublishNuGetArtifact(string packageId, string pushSource)
{
var files = GetFiles($"{NuGetDirectory}/{packageId}/*.nupkg");
NuGetPush(files, new NuGetPushSettings { Source = pushSource });
}
void StoreNuGetArtifact(FilePath nuspecPath)
{
var dir = $"{NuGetDirectory}/{nuspecPath.GetFilenameWithoutExtension()}";
EnsureDirectoryExists(dir);
NuGetPack(nuspecPath, new NuGetPackSettings { OutputDirectory = dir });
}
| private const string ArtifactsDirectory = "../Artifacts";
private const string ChocolateyDirectory = ArtifactsDirectory + "/Chocolatey";
private const string NuGetDirectory = ArtifactsDirectory + "/NuGet";
void CleanArtifacts()
{
CleanDirectory(ArtifactsDirectory);
}
void StoreBuildArtifacts(string projectName, string filePattern)
{
StoreBuildArtifacts(projectName, GetFiles(filePattern));
}
void StoreBuildArtifacts(string projectName, IEnumerable<FilePath> filePaths)
{
var dir = $"{ArtifactsDirectory}/Build/{projectName}";
EnsureDirectoryExists(dir);
Information("Copying artifacts to {0}", dir);
CopyFiles(filePaths, dir, true);
DeleteFiles($"{dir}/*.lastcodeanalysissucceeded");
DeleteFiles($"{dir}/*.CodeAnalysisLog.xml");
}
void PublishChocolateyArtifact(string packageId, string pushSource)
{
var files = GetFiles($"{ChocolateyDirectory}/{packageId}/*.nupkg");
foreach (var file in files)
{
ChocolateyPush(file, new ChocolateyPushSettings { Source = pushSource });
}
}
void StoreChocolateyArtifact(FilePath nuspecPath)
{
var dir = $"{ChocolateyDirectory}/{nuspecPath.GetFilenameWithoutExtension()}";
EnsureDirectoryExists(dir);
ChocolateyPack(nuspecPath, new ChocolateyPackSettings { OutputDirectory = dir });
}
void PublishNuGetArtifact(string packageId, string pushSource)
{
var files = GetFiles($"{NuGetDirectory}/{packageId}/*.nupkg");
foreach (var file in files)
{
NuGetPush(files, new NuGetPushSettings { Source = pushSource });
}
}
void StoreNuGetArtifact(FilePath nuspecPath)
{
var dir = $"{NuGetDirectory}/{nuspecPath.GetFilenameWithoutExtension()}";
EnsureDirectoryExists(dir);
NuGetPack(nuspecPath, new NuGetPackSettings { OutputDirectory = dir });
}
| mit | C# |
48e21d0d5a135f785b0b2e1ade4b9d17d3c12d48 | Disable some Cake.Recipe features | jeyjeyemem/Xer.Cqrs | setup.cake | setup.cake | #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./Src",
title: "Xer.Cqrs",
solutionFilePath: "./Xer.Cqrs.sln",
repositoryOwner: "XerProjects",
repositoryName: "Xer.Cqrs",
appVeyorAccountName: "xerprojects-bot",
testFilePattern: "/**/*Tests.csproj",
testDirectoryPath: "./Tests",
shouldRunDotNetCorePack: true,
shouldRunDupFinder: false,
shouldRunCodecov: false,
shouldRunInspectCode: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context,
testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* ",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./Src",
title: "Xer.Cqrs",
solutionFilePath: "./Xer.Cqrs.sln",
repositoryOwner: "XerProjects",
repositoryName: "Xer.Cqrs",
appVeyorAccountName: "xerprojects-bot",
testFilePattern: "/**/*Tests.csproj",
testDirectoryPath: "./Tests",
shouldRunDupFinder: false,
shouldRunDotNetCorePack: true);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context,
testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* ",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| mit | C# |
7f6b0cca1f8413cf1cbc162dc77d0c21c957cfde | Update AssemblyInfo | JeremyAnsel/JeremyAnsel.ColorQuant | JeremyAnsel.ColorQuant/JeremyAnsel.ColorQuant.Tests/Properties/AssemblyInfo.cs | JeremyAnsel.ColorQuant/JeremyAnsel.ColorQuant.Tests/Properties/AssemblyInfo.cs | // <copyright file="AssemblyInfo.cs" company="Jérémy Ansel">
// Copyright (c) 2014-2015 Jérémy Ansel
// </copyright>
// <license>
// Licensed under the MIT license. See LICENSE.txt
// </license>
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("JeremyAnsel.ColorQuant.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jérémy Ansel")]
[assembly: AssemblyProduct("JeremyAnsel.ColorQuant.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014-2015 Jérémy Ansel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("b2b39722-0a4d-49aa-a7f0-1506ccd3a273")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| // <copyright file="AssemblyInfo.cs" company="Jérémy Ansel">
// Copyright (c) 2014-2015 Jérémy Ansel
// </copyright>
// <license>
// Licensed under the MIT license. See LICENSE.txt
// </license>
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("JeremyAnsel.ColorQuant.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jérémy Ansel")]
[assembly: AssemblyProduct("JeremyAnsel.ColorQuant.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014-2015 Jérémy Ansel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("b2b39722-0a4d-49aa-a7f0-1506ccd3a273")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
ac54d4cb10dcd69b3adf1b748eb0144bfc6014ee | add new method on Business Layer | 78526Nasir/E-Commerce-Site,78526Nasir/E-Commerce-Site | BusinessAccessLayer/ECommerceBusiness.cs | BusinessAccessLayer/ECommerceBusiness.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using DataAccessLayer;
/// <summary>
/// Business Access Layer mainly deals with the Business
/// since this is a E-commerce site
/// so the main business belongs with product and category
/// </summary>
namespace BusinessAccessLayer
{
public class ECommerceBusiness
{
public string categoryName;
public string categoryDescription;
public string productName;
public string productDescription;
public string productPrice;
public string productImage;
public void addNewCategory()
{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = DataAccess.addParameter("@categoryName", categoryName);
parameters[1] = DataAccess.addParameter("@categoryDesc", categoryDescription);
DataAccess.executeDTByProcedure("sp_addNewCategory", parameters);
}
public DataTable getAllCategories()
{
return DataAccess.executeDTByProcedure("sp_getAllCategory", null); // second parameter is set to be null because of it is select query
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using DataAccessLayer;
/// <summary>
/// Business Access Layer mainly deals with the Business
/// since this is a E-commerce site
/// so the main business belongs with product and category
/// </summary>
namespace BusinessAccessLayer
{
public class ECommerceBusiness
{
public string categoryName;
public string categoryDescription;
public string productName;
public string productDescription;
public string productPrice;
public string productImage;
public void addNewCategory()
{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = DataAccess.addParameter("@categoryName", categoryName);
parameters[1] = DataAccess.addParameter("@categoryDesc", categoryDescription);
DataAccess.executeDTByProcedure("sp_addNewCategory", parameters);
}
}
}
| mit | C# |
26cf9fbd3d475c8f1d78039e942955d4a1b59f08 | Update version to 1.0.4 | codejuicer/POxOSerializer,ggerla/POxOSerializer,codejuicer/POxOSerializer,ggerla/POxOSerializer | C#/POxO/Properties/AssemblyInfo.cs | C#/POxO/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("POxO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("POxO")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e3c58b29-5f5c-44c6-9f76-2651bc372a6b")]
// 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.4.0")]
[assembly: AssemblyFileVersion("1.0.4.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("POxO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("POxO")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e3c58b29-5f5c-44c6-9f76-2651bc372a6b")]
// 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.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
| apache-2.0 | C# |
bc4028344acc5e22dcf66d5b01028d0778ee127e | throw more exception | neowutran/OpcodeSearcher | DamageMeter.Core/Heuristic/S_SPAWN_ME.cs | DamageMeter.Core/Heuristic/S_SPAWN_ME.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tera.Game.Messages;
namespace DamageMeter.Heuristic
{
internal class S_SPAWN_ME : AbstractPacketHeuristic
{
public static S_SPAWN_ME Instance => _instance ?? (_instance = new S_SPAWN_ME());
private static S_SPAWN_ME _instance;
private S_SPAWN_ME() : base(OpcodeEnum.S_SPAWN_ME)
{
}
public new void Process(ParsedMessage message)
{
base.Process(message);
if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; }
if (message.Payload.Count != 26) return;
var target = Reader.ReadUInt64();
var pos = Reader.ReadVector3f(); //maybe add more checks based on pos?
var w = Reader.ReadUInt16();
var alive = Reader.ReadBoolean();
var unk = Reader.ReadByte();
if (unk != 0) return;
if (!OpcodeFinder.Instance.KnowledgeDatabase.TryGetValue(OpcodeFinder.KnowledgeDatabaseItem.LoggedCharacter, out Tuple<Type, object> currChar)) {
throw new Exception("Logger character should be know at this point.");
}
var ch = (LoggedCharacter)currChar.Item2;
if (target != ch.Cid) return;
OpcodeFinder.Instance.SetOpcode(message.OpCode, OpcodeEnum.S_SPAWN_ME);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tera.Game.Messages;
namespace DamageMeter.Heuristic
{
internal class S_SPAWN_ME : AbstractPacketHeuristic
{
public static S_SPAWN_ME Instance => _instance ?? (_instance = new S_SPAWN_ME());
private static S_SPAWN_ME _instance;
private S_SPAWN_ME() : base(OpcodeEnum.S_SPAWN_ME)
{
}
public new void Process(ParsedMessage message)
{
base.Process(message);
if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) { return; }
if (message.Payload.Count != 26) return;
var target = Reader.ReadUInt64();
var pos = Reader.ReadVector3f(); //maybe add more checks based on pos?
var w = Reader.ReadUInt16();
var alive = Reader.ReadBoolean();
var unk = Reader.ReadByte();
if (unk != 0) return;
if (!OpcodeFinder.Instance.KnowledgeDatabase.TryGetValue(OpcodeFinder.KnowledgeDatabaseItem.PlayerLocation, out Tuple<Type, object> currChar)) { return; }
var ch = (LoggedCharacter)currChar.Item2;
if (target != ch.Cid) return;
OpcodeFinder.Instance.SetOpcode(message.OpCode, OpcodeEnum.S_SPAWN_ME);
}
}
} | mit | C# |
c9f981c189d9c9b8e038acdeb962c38070aba3bd | Implement service call Facade (Request & Confirm PhoneNumber) complete. | tlaothong/xdailysoccer,tlaothong/xdailysoccer,tlaothong/xdailysoccer,tlaothong/xdailysoccer | src/DailySoccerSolution/DailySoccerAppService/Controllers/AccountController.cs | src/DailySoccerSolution/DailySoccerAppService/Controllers/AccountController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using DailySoccer.Shared.Models;
using DailySoccer.Shared.Facades;
namespace DailySoccerAppService.Controllers
{
public class AccountController : ApiController
{
public ApiServices Services { get; set; }
[HttpGet]
public CreateNewGuestRespond CreateNewGuest()
{
var accountFacade = new AccountFacade();
var result = accountFacade.CreateNewGuest();
return result;
}
[HttpGet]
public CreateNewGuestRespond CreateNewGuestWithFacebook(string OAuthId)
{
var accountFacade = new AccountFacade();
var email = "testuser@dailysoccer.com";
var result = accountFacade.CreateNewGuestWithFaceebook(OAuthId, email);
return result;
}
[HttpGet]
public bool UpdateAccountWithFacebook(string secretCode, string OAuthId)
{
var accountFacade = new AccountFacade();
var email = "testuser@dailysoccer.com";
accountFacade.UpdateAccountWithFacebook(secretCode, OAuthId, email);
return true;
}
[HttpGet]
public AccountInformation GetAccountByOAuthId(string OAuthId)
{
var accountFacade = new AccountFacade();
var result = accountFacade.GetAccountByOAuthId(OAuthId);
return result;
}
[HttpGet]
public RequestConfirmPhoneNumberRespond RequestConfirmPhoneNumber(string userId, string phoneNo)
{
var request = new RequestConfirmPhoneNumberRequest
{
PhoneNo = phoneNo,
UserId = userId
};
var result = FacadeRepository.Instance.AccountFacade.RequestConfirmPhoneNumber(request);
return result;
}
[HttpGet]
public ConfirmPhoneNumberRespond ConfirmPhoneNumber(string userId, string verificationCode)
{
var request = new ConfirmPhoneNumberRequest
{
UserId = userId,
VerificationCode = verificationCode
};
var result = FacadeRepository.Instance.AccountFacade.ConfirmPhoneNumber(request);
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using DailySoccer.Shared.Models;
using DailySoccer.Shared.Facades;
namespace DailySoccerAppService.Controllers
{
public class AccountController : ApiController
{
public ApiServices Services { get; set; }
[HttpGet]
public CreateNewGuestRespond CreateNewGuest()
{
var accountFacade = new AccountFacade();
var result = accountFacade.CreateNewGuest();
return result;
}
[HttpGet]
public CreateNewGuestRespond CreateNewGuestWithFacebook(string OAuthId)
{
var accountFacade = new AccountFacade();
var email = "testuser@dailysoccer.com";
var result = accountFacade.CreateNewGuestWithFaceebook(OAuthId, email);
return result;
}
[HttpGet]
public bool UpdateAccountWithFacebook(string secretCode, string OAuthId)
{
var accountFacade = new AccountFacade();
var email = "testuser@dailysoccer.com";
accountFacade.UpdateAccountWithFacebook(secretCode, OAuthId, email);
return true;
}
[HttpGet]
public AccountInformation GetAccountByOAuthId(string OAuthId)
{
var accountFacade = new AccountFacade();
var result = accountFacade.GetAccountByOAuthId(OAuthId);
return result;
}
}
}
| mit | C# |
74c5763576253c81690f92e672cb82d5a5f3ae69 | Revert html body part's wysiwyg toolbar to be always visible (#2905) | xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard | src/OrchardCore.Modules/OrchardCore.Html/Views/HtmlBodyPart-Wysiwyg.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Html/Views/HtmlBodyPart-Wysiwyg.Edit.cshtml | @model HtmlBodyPartViewModel
@using OrchardCore.Html.ViewModels;
@using OrchardCore.Html.Settings;
@using OrchardCore.ContentManagement.Metadata.Models
@{
var settings = Model.TypePartDefinition.Settings.ToObject<HtmlBodyPartSettings>();
}
<script asp-name="trumbowyg" depends-on="admin" asp-src="~/OrchardCore.Resources/Scripts/trumbowyg.min.js" debug-src="~/OrchardCore.Resources/Scripts/trumbowyg.js" at="Foot"></script>
<style asp-name="trumbowyg" asp-src="~/OrchardCore.Resources/Styles/trumbowyg.min.css" debug-src="~/OrchardCore.Resources/Styles/trumbowyg.css"></style>
<fieldset class="form-group">
<label asp-for="Source">@Model.TypePartDefinition.DisplayName()</label>
<textarea asp-for="Source" rows="5" class="form-control"></textarea>
<span class="hint">@T["The body of the content item."]</span>
</fieldset>
<script at="Foot">
$(function () {
$('#@Html.IdFor(m => m.Source)').trumbowyg().on('tbwchange', function () {
$(document).trigger('contentpreview:render');
});
});
</script> | @model HtmlBodyPartViewModel
@using OrchardCore.Html.ViewModels;
@using OrchardCore.Html.Settings;
@using OrchardCore.ContentManagement.Metadata.Models
@{
var settings = Model.TypePartDefinition.Settings.ToObject<HtmlBodyPartSettings>();
}
<script asp-name="trumbowyg" depends-on="admin" asp-src="~/OrchardCore.Resources/Scripts/trumbowyg.min.js" debug-src="~/OrchardCore.Resources/Scripts/trumbowyg.js" at="Foot"></script>
<style asp-name="trumbowyg" asp-src="~/OrchardCore.Resources/Styles/trumbowyg.min.css" debug-src="~/OrchardCore.Resources/Styles/trumbowyg.css"></style>
<fieldset class="form-group">
<label asp-for="Source">@Model.TypePartDefinition.DisplayName()</label>
<textarea asp-for="Source" rows="5" class="form-control"></textarea>
<span class="hint">@T["The body of the content item."]</span>
</fieldset>
<script at="Foot">
$(function () {
var editor = $('#@Html.IdFor(m => m.Source)').trumbowyg();
editor.on('tbwchange', function () {
$(document).trigger('contentpreview:render');
});
// hide toolbar when editor is not in focus (to avoid z-index clashes with dropdown components that may be on the page)
(function toolbarToggler() {
function getButtonPane(textarea) {
return $(textarea).siblings('.trumbowyg-button-pane');
}
editor.on('tbwfocus', function () { getButtonPane(this).fadeIn(); });
editor.on('tbwblur', function () { getButtonPane(this).fadeOut(); });
// hide initially
editor.siblings('.trumbowyg-button-pane').css("display", "none");
}());
});
</script> | bsd-3-clause | C# |
e2838bf73c5ca23c1b1d6202a7d172a15936a956 | Add missing copyright notice to CoreCLR sample app | AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet | samples/AdalCoreCLRTestApp/Program.cs | samples/AdalCoreCLRTestApp/Program.cs | //----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace AdalCoreCLRTestApp
{
class Program
{
static void Main(string[] args)
{
try
{
AcquireTokenAsync().Wait();
}
catch (AggregateException ae)
{
Console.WriteLine(ae.InnerException.Message);
Console.WriteLine(ae.InnerException.StackTrace);
}
finally
{
Console.ReadKey();
}
}
private static async Task AcquireTokenAsync()
{
AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/common", true);
var certificate = GetCertificateByThumbprint("<CERT_THUMBPRINT>");
var result = await context.AcquireTokenAsync("https://graph.windows.net", new ClientAssertionCertificate("<CLIENT_ID>", certificate));
string token = result.AccessToken;
Console.WriteLine(token + "\n");
}
private static X509Certificate2 GetCertificateByThumbprint(string thumbprint)
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certs.Count > 0)
{
return certs[0];
}
throw new Exception($"Cannot find certificate with thumbprint '{thumbprint}'");
}
}
}
}
| using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace AdalCoreCLRTestApp
{
class Program
{
static void Main(string[] args)
{
try
{
AcquireTokenAsync().Wait();
}
catch (AggregateException ae)
{
Console.WriteLine(ae.InnerException.Message);
Console.WriteLine(ae.InnerException.StackTrace);
}
finally
{
Console.ReadKey();
}
}
private static async Task AcquireTokenAsync()
{
AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/common", true);
var certificate = GetCertificateByThumbprint("<CERT_THUMBPRINT>");
var result = await context.AcquireTokenAsync("https://graph.windows.net", new ClientAssertionCertificate("<CLIENT_ID>", certificate));
string token = result.AccessToken;
Console.WriteLine(token + "\n");
}
private static X509Certificate2 GetCertificateByThumbprint(string thumbprint)
{
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certs.Count > 0)
{
return certs[0];
}
throw new Exception($"Cannot find certificate with thumbprint '{thumbprint}'");
}
}
}
} | mit | C# |
bab74b232c70882a47cb515f09d875b2134b9321 | add check on panels | shengoo/umb,shengoo/umb | Site/Views/Partials/ContentPanels.cshtml | Site/Views/Partials/ContentPanels.cshtml | @inherits Umbraco.Web.Mvc.UmbracoViewPage<IPublishedContent>
@if (!string.IsNullOrWhiteSpace(Model.GetPropertyValue<string>("contentPanels")))
{
Layout = null;
var nodeIds = Model.GetPropertyValue<string>("contentPanels").Split(',');
List<IPublishedContent> panels = new List<IPublishedContent>();
foreach(var nodeId in nodeIds)
{
if(!String.IsNullOrEmpty(nodeId))
{
var publishedContent = Umbraco.NiceUrl(Convert.ToInt32(nodeId));
if (!String.IsNullOrEmpty(publishedContent) && publishedContent!="#")
{
panels.Add(Umbraco.TypedContent(nodeId));
}
}
}
if(panels.Count() > 0)
{
<ul id="rightPanel">
@foreach (var panel in panels)
{
if (panel != null)
{
<li>@Html.Raw(panel.GetPropertyValue<string>("bodyText"))</li>
}
}
</ul>
}
} | @inherits Umbraco.Web.Mvc.UmbracoViewPage<IPublishedContent>
@{
Layout = null;
var nodeIds = Model.GetPropertyValue<string>("contentPanels").Split(',');
List<IPublishedContent> panels = new List<IPublishedContent>();
foreach(var nodeId in nodeIds)
{
if(!String.IsNullOrEmpty(nodeId))
{
var publishedContent = Umbraco.NiceUrl(Convert.ToInt32(nodeId));
if (!String.IsNullOrEmpty(publishedContent) && publishedContent!="#")
{
panels.Add(Umbraco.TypedContent(nodeId));
}
}
}
}
@if(panels.Count() > 0)
{
<ul id="rightPanel">
@foreach (var panel in panels)
{
if (panel != null)
{
<li>@Html.Raw(panel.GetPropertyValue<string>("bodyText"))</li>
}
}
</ul>
}
| mit | C# |
51a25d89a668857fa5d5c177b363e3971ee2c8c5 | enable continue button on testnet and regtest | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/AddWallet/Create/ConfirmRecoveryWordsViewModel.cs | WalletWasabi.Fluent/ViewModels/AddWallet/Create/ConfirmRecoveryWordsViewModel.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;
using NBitcoin;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels.AddWallet.Create
{
public class ConfirmRecoveryWordsViewModel : RoutableViewModel
{
private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords;
public ConfirmRecoveryWordsViewModel(List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager)
{
Title = "Confirm recovery words";
var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>();
var nextCommandCanExecute =
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.WhenValueChanged(x => x.IsConfirmed)
.Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed) || walletManager.Network != Network.Main);
NextCommand = ReactiveCommand.Create(
() =>
{
Navigate().To(new AddedWalletPageViewModel(walletManager, keyManager, WalletType.Normal));
},
nextCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => Navigate().Clear());
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.OnItemAdded(x => x.Reset())
.Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index))
.Bind(out _confirmationWords)
.Subscribe();
// Select 4 random words to confirm.
confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(4));
}
public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords;
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;
using ReactiveUI;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels.AddWallet.Create
{
public class ConfirmRecoveryWordsViewModel : RoutableViewModel
{
private readonly ReadOnlyObservableCollection<RecoveryWordViewModel> _confirmationWords;
public ConfirmRecoveryWordsViewModel(List<RecoveryWordViewModel> mnemonicWords, KeyManager keyManager, WalletManager walletManager)
{
Title = "Confirm recovery words";
var confirmationWordsSourceList = new SourceList<RecoveryWordViewModel>();
var finishCommandCanExecute =
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.WhenValueChanged(x => x.IsConfirmed)
.Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed));
NextCommand = ReactiveCommand.Create(
() =>
{
Navigate().To(new AddedWalletPageViewModel(walletManager, keyManager, WalletType.Normal));
},
finishCommandCanExecute);
CancelCommand = ReactiveCommand.Create(() => Navigate().Clear());
confirmationWordsSourceList
.Connect()
.ObserveOn(RxApp.MainThreadScheduler)
.OnItemAdded(x => x.Reset())
.Sort(SortExpressionComparer<RecoveryWordViewModel>.Ascending(x => x.Index))
.Bind(out _confirmationWords)
.Subscribe();
// Select 4 random words to confirm.
confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(4));
}
public ReadOnlyObservableCollection<RecoveryWordViewModel> ConfirmationWords => _confirmationWords;
}
}
| mit | C# |
6dea8dfae59ff5e8d2d273b0e12a12336b233ef8 | use Uri as type for url-valued response properties | NebulousConcept/b2-csharp-client | b2-csharp-client/B2.Client/Apis/AuthorizeAccountV1/AuthorizeAccountV1Response.cs | b2-csharp-client/B2.Client/Apis/AuthorizeAccountV1/AuthorizeAccountV1Response.cs | using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using B2.Client.Rest;
using B2.Client.Rest.Response;
namespace B2.Client.Apis.AuthorizeAccountV1
{
/// <summary>
/// Response object for the 'b2_authorize_account' version 1 API.
/// </summary>
[DataContract]
public sealed class AuthorizeAccountV1Response : IAuthenticationResponse
{
/// <summary>
/// The account identifier.
/// </summary>
[DataMember(Name = "accountId", IsRequired = true)]
public string AccountId { get; }
/// <summary>
/// The authorization token to use in subsequent API calls.
/// </summary>
[DataMember(Name = "authorizationToken", IsRequired = true)]
public string AuthorizationToken { get; }
/// <summary>
/// The URL to use in subsequent API calls (except for file downloads).
/// </summary>
[DataMember(Name = "apiUrl", IsRequired = true)]
public Uri ApiUrl { get; }
/// <summary>
/// The URL to use in subsequent file downloads.
/// </summary>
[DataMember(Name = "downloadUrl", IsRequired = true)]
public Uri DownloadUrl { get; }
/// <summary>
/// The minimum size for parts of large files (apart from the last part).
/// </summary>
[DataMember(Name = "minimumPartSize", IsRequired = true)]
public ulong MinimumPartSize { get; }
//parameter names have to match property names for deserializer to tie them together
[SuppressMessage("ReSharper", "InconsistentNaming")]
public AuthorizeAccountV1Response(string AccountId, string AuthorizationToken, Uri ApiUrl, Uri DownloadUrl,
ulong MinimumPartSize)
{
this.AccountId = AccountId;
this.AuthorizationToken = AuthorizationToken;
this.ApiUrl = ApiUrl;
this.DownloadUrl = DownloadUrl;
this.MinimumPartSize = MinimumPartSize;
}
/// <inheritDoc />
public IAuthenticationToken GetAuthenticationToken()
=> new B2AuthenticationToken(AuthorizationToken, ApiUrl);
}
} | using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using B2.Client.Rest;
using B2.Client.Rest.Response;
namespace B2.Client.Apis.AuthorizeAccountV1
{
/// <summary>
/// Response object for the 'b2_authorize_account' version 1 API.
/// </summary>
[DataContract]
public sealed class AuthorizeAccountV1Response : IAuthenticationResponse
{
/// <summary>
/// The account identifier.
/// </summary>
[DataMember(Name = "accountId", IsRequired = true)]
public string AccountId { get; }
/// <summary>
/// The authorization token to use in subsequent API calls.
/// </summary>
[DataMember(Name = "authorizationToken", IsRequired = true)]
public string AuthorizationToken { get; }
/// <summary>
/// The URL to use in subsequent API calls (except for file downloads).
/// </summary>
[DataMember(Name = "apiUrl", IsRequired = true)]
public string ApiUrl { get; }
/// <summary>
/// The URL to use in subsequent file downloads.
/// </summary>
[DataMember(Name = "downloadUrl", IsRequired = true)]
public string DownloadUrl { get; }
/// <summary>
/// The minimum size for parts of large files (apart from the last part).
/// </summary>
[DataMember(Name = "minimumPartSize", IsRequired = true)]
public ulong MinimumPartSize { get; }
//parameter names have to match property names for deserializer to tie them together
[SuppressMessage("ReSharper", "InconsistentNaming")]
public AuthorizeAccountV1Response(string AccountId, string AuthorizationToken, string ApiUrl, string DownloadUrl,
ulong MinimumPartSize)
{
this.AccountId = AccountId;
this.AuthorizationToken = AuthorizationToken;
this.ApiUrl = ApiUrl;
this.DownloadUrl = DownloadUrl;
this.MinimumPartSize = MinimumPartSize;
}
/// <inheritDoc />
public IAuthenticationToken GetAuthenticationToken()
=> new B2AuthenticationToken(AuthorizationToken, new Uri(ApiUrl));
}
} | mit | C# |
95db212ea49071b7e163ec21122dce0b0521b1a2 | Update Form1.cs | t3ntman/BrowserCheck | BrowserCheck/Form1.cs | BrowserCheck/Form1.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers; // For progress bar timing
using System.Diagnostics; // For process creation
namespace BrowserCheck
{
public partial class Form1 : Form
{
System.Timers.Timer progressBarTimer = new System.Timers.Timer(); // Creates globally-accessible timer
public Form1()
{
InitializeComponent();
textBox1.Text = "Not Applicable"; // Sets initial value of "Status" text box to "Not Applicable"
}
// When "Run Browser Check" is clicked
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Running";
progressBarTimer.Interval = 10000; // Tick interval - determines how fast the progress bar will complete (defaults to 10 seconds)
progressBarTimer.Elapsed += OnTimedEvent; // Function to be called for each tick
progressBarTimer.Enabled = true; // Enables timer
progressBar1.Value = 0; // Sets initial value of progress bar to 0
progressBar1.Step = 10; // Steps by 10% each time
}
// This function is called for each tick
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
progressBar1.PerformStep(); // Performs step
// If progress bar is at 100% - we need to stop the timer
if (progressBar1.Value == 100)
{
progressBarTimer.Stop(); // Stops timer
MessageBox.Show("Your computer has passed the browser check. You may exit the program now."); // Displays pop-up window to user letting them know that they passed
textBox1.Text = "Passed"; // Sets "Status" text box to "Passed"
}
}
// When the program loads
private void Form1_Load(object sender, EventArgs e)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = ""; // **** Need to include CobaltStrike PowerShell code here ****
Process.Start(startInfo);
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers; // For progress bar timing
using System.Diagnostics; // For process creation
namespace BrowserCheck
{
public partial class Form1 : Form
{
System.Timers.Timer progressBarTimer = new System.Timers.Timer(); // Creates globally-accessible timer
public Form1()
{
InitializeComponent();
textBox1.Text = "Not Applicable"; // Sets initial value of "Status" text box to "Not Applicable"
}
// When "Run Browser Check" is clicked
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Running";
progressBarTimer.Interval = 10000; // Tick interval - determines how fast the progress bar will complete (defaults to 10 seconds)
progressBarTimer.Elapsed += OnTimedEvent; // Function to be called for each tick
progressBarTimer.Enabled = true; // Enables timer
progressBar1.Value = 0; // Sets initial value of progress bar to 0
progressBar1.Step = 10; // Steps by 10% each time
}
// This function is called for each tick
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
progressBar1.PerformStep(); // Performs step
// If progress bar is at 100% - we need to stop the timer
if (progressBar1.Value == 100)
{
progressBarTimer.Stop(); // Stops timer
MessageBox.Show("Your computer has passed the browser check. You may exit the program now."); // Displays pop-up window to user letting them know that they passed
textBox1.Text = "Passed"; // Sets "Status" text box to "Passed"
}
}
// When the program loads
private void Form1_Load(object sender, EventArgs e)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = true;
startInfo.Arguments = ""; // **** Need to include CobaltStrike PowerShell code here ****
Process.Start(startInfo);
}
}
}
| apache-2.0 | C# |
dec81b67df70af8ebadf5db2278d61703c7df58d | set ValidAudience to Wtrealm, removes the need to set TokenValidationParameters. | eocampo/KatanaProject301,julianpaulozzi/katanaproject,evicertia/Katana,evicertia/Katana,PxAndy/Katana,julianpaulozzi/katanaproject,eocampo/KatanaProject301,abrodersen/katana,eocampo/KatanaProject301,abrodersen/katana,eocampo/KatanaProject301,abrodersen/katana,julianpaulozzi/katanaproject,tomi85/Microsoft.Owin,abrodersen/katana,abrodersen/katana,HongJunRen/katanaproject,HongJunRen/katanaproject,HongJunRen/katanaproject,PxAndy/Katana,evicertia/Katana,julianpaulozzi/katanaproject,eocampo/KatanaProject301,tomi85/Microsoft.Owin,julianpaulozzi/katanaproject,PxAndy/Katana,tomi85/Microsoft.Owin,tomi85/Microsoft.Owin,HongJunRen/katanaproject,evicertia/Katana,abrodersen/katana,HongJunRen/katanaproject,HongJunRen/katanaproject,julianpaulozzi/katanaproject,evicertia/Katana,eocampo/KatanaProject301,evicertia/Katana,PxAndy/Katana | src/Microsoft.Owin.Security.WsFederation/WsFederationAuthenticationExtensions.cs | src/Microsoft.Owin.Security.WsFederation/WsFederationAuthenticationExtensions.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Owin.Security.WsFederation;
namespace Owin
{
/// <summary>
/// Extension methods for using <see cref="WsFederationAuthenticationMiddleware"/>
/// </summary>
public static class WsFederationAuthenticationExtensions
{
/// <summary>
/// Adds the <see cref="WsFederationAuthenticationMiddleware"/> into the OWIN runtime.
/// </summary>
/// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
/// <param name="wsFederationOptions">WsFederationAuthenticationOptions configuration options</param>
/// <returns>The updated <see cref="IAppBuilder"/></returns>
public static IAppBuilder UseWsFederationAuthentication(this IAppBuilder app, WsFederationAuthenticationOptions wsFederationOptions)
{
if (app == null)
{
throw new ArgumentNullException("app");
}
if (wsFederationOptions == null)
{
throw new ArgumentNullException("wsFederationOptions");
}
app.Use<WsFederationAuthenticationMiddleware>(app, wsFederationOptions);
wsFederationOptions.TokenValidationParameters.ValidAudience = wsFederationOptions.Wtrealm;
return app;
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Owin.Security.WsFederation;
namespace Owin
{
/// <summary>
/// Extension methods for using <see cref="WsFederationAuthenticationMiddleware"/>
/// </summary>
public static class WsFederationAuthenticationExtensions
{
/// <summary>
/// Adds the <see cref="WsFederationAuthenticationMiddleware"/> into the OWIN runtime.
/// </summary>
/// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
/// <param name="wsFederationOptions">WsFederationAuthenticationOptions configuration options</param>
/// <returns>The updated <see cref="IAppBuilder"/></returns>
public static IAppBuilder UseWsFederationAuthentication(this IAppBuilder app, WsFederationAuthenticationOptions wsFederationOptions)
{
if (app == null)
{
throw new ArgumentNullException("app");
}
if (wsFederationOptions == null)
{
throw new ArgumentNullException("wsFederationOptions");
}
app.Use<WsFederationAuthenticationMiddleware>(app, wsFederationOptions);
return app;
}
}
} | apache-2.0 | C# |
079ad108a4b08b771801dec63f921eb185202969 | Disable failing EventSource test | Jiayili1/corefx,ViktorHofer/corefx,ptoonen/corefx,Jiayili1/corefx,shimingsg/corefx,shimingsg/corefx,shimingsg/corefx,mmitche/corefx,shimingsg/corefx,BrennanConroy/corefx,ericstj/corefx,ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,Jiayili1/corefx,ptoonen/corefx,Jiayili1/corefx,mmitche/corefx,shimingsg/corefx,ptoonen/corefx,ericstj/corefx,Jiayili1/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,mmitche/corefx,ViktorHofer/corefx,ericstj/corefx,Jiayili1/corefx,mmitche/corefx,ViktorHofer/corefx,Jiayili1/corefx,ptoonen/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx,BrennanConroy/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,BrennanConroy/corefx,ViktorHofer/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,ericstj/corefx | src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.Etw.cs | src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.Etw.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using Xunit;
namespace BasicEventSourceTests
{
/// <summary>
/// Tests the user experience for common user errors.
/// </summary>
public partial class TestsUserErrors
{
/// <summary>
/// Test the
/// </summary>
[ActiveIssue(30876)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29754
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")]
public void Test_BadEventSource_MismatchedIds_WithEtwListener()
{
// We expect only one session to be on when running the test but if a ETW session was left
// hanging, it will confuse the EventListener tests.
if(TestUtilities.IsProcessElevated)
{
EtwListener.EnsureStopped();
}
TestUtilities.CheckNoEventSourcesRunning("Start");
var onStartups = new bool[] { false, true };
var listenerGenerators = new List<Func<Listener>> { () => new EventListenerListener() };
if(TestUtilities.IsProcessElevated)
{
listenerGenerators.Add(() => new EtwListener());
}
var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };
// For every interesting combination, run the test and see that we get a nice failure message.
foreach (bool onStartup in onStartups)
{
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
foreach (EventSourceSettings setting in settings)
{
Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
}
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using Xunit;
namespace BasicEventSourceTests
{
/// <summary>
/// Tests the user experience for common user errors.
/// </summary>
public partial class TestsUserErrors
{
/// <summary>
/// Test the
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29754
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")]
public void Test_BadEventSource_MismatchedIds_WithEtwListener()
{
// We expect only one session to be on when running the test but if a ETW session was left
// hanging, it will confuse the EventListener tests.
if(TestUtilities.IsProcessElevated)
{
EtwListener.EnsureStopped();
}
TestUtilities.CheckNoEventSourcesRunning("Start");
var onStartups = new bool[] { false, true };
var listenerGenerators = new List<Func<Listener>> { () => new EventListenerListener() };
if(TestUtilities.IsProcessElevated)
{
listenerGenerators.Add(() => new EtwListener());
}
var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };
// For every interesting combination, run the test and see that we get a nice failure message.
foreach (bool onStartup in onStartups)
{
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
foreach (EventSourceSettings setting in settings)
{
Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
}
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
}
}
| mit | C# |
9e2c89a7e3f8e3190f76b0e155cbadf18b4d97ab | Refactor IUndirectedEdge to use weights | DasAllFolks/SharpGraphs | Graph/IUndirectedEdge.cs | Graph/IUndirectedEdge.cs | using System;
using System.Collections.Generic;
namespace Graph
{
/// <summary>
/// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>.
/// </summary>
/// <typeparam name="V">
/// The type used to create vertex (node) labels.
/// </typeparam>
/// <typeparam name="W">
/// The type used for the edge weight.
/// </typeparam>
public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>>
where V : struct, IEquatable<V>
where W : struct, IComparable<W>, IEquatable<W>
{
/// <summary>
/// The vertices comprising the <see cref="IUndirectedEdge{V}"/>.
/// </summary>
ISet<V> Vertices { get; }
}
}
| using System;
using System.Collections.Generic;
namespace Graph
{
/// <summary>
/// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>.
/// </summary>
/// <typeparam name="T">
/// The type used to create vertex (node) labels.
/// </typeparam>
public interface IUndirectedEdge<T> : IEdge<T>, IEquatable<IUndirectedEdge<T>> where T : struct
{
/// <summary>
/// The vertices comprising the <see cref="IUndirectedEdge{T}"/>.
/// </summary>
ISet<T> Vertices { get; }
}
}
| apache-2.0 | C# |
809e77ff9af5720b9a726b9fe702b69ecaeae481 | Fix possible race due to multiple concurrent assignement of the wait event in PendingCall. | tmds/Tmds.DBus | PendingCall.cs | PendingCall.cs | // Copyright 2007 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Threading;
namespace DBus
{
class PendingCall : IAsyncResult
{
Connection conn;
Message reply = null;
//AutoResetEvent waitHandle = new AutoResetEvent (false);
ManualResetEvent waitHandle;
public PendingCall (Connection conn)
{
this.conn = conn;
}
public Message Reply
{
get {
if (reply != null)
return reply;
if (Thread.CurrentThread == conn.mainThread) {
/*
while (reply == null)
conn.Iterate ();
*/
while (reply == null)
conn.HandleMessage (conn.Transport.ReadMessage ());
completedSync = true;
conn.DispatchSignals ();
} else {
if (waitHandle == null)
Interlocked.CompareExchange (ref waitHandle, new ManualResetEvent (false), null);
// TODO: Possible race condition?
while (reply == null)
waitHandle.WaitOne ();
completedSync = false;
}
return reply;
} set {
if (reply != null)
throw new Exception ("Cannot handle reply more than once");
reply = value;
if (waitHandle != null)
waitHandle.Set ();
if (Completed != null)
Completed (reply);
}
}
public event Action<Message> Completed;
bool completedSync;
public void Cancel ()
{
throw new NotImplementedException ();
}
#region IAsyncResult Members
object IAsyncResult.AsyncState
{
get {
return conn;
}
}
WaitHandle IAsyncResult.AsyncWaitHandle
{
get {
if (waitHandle == null)
waitHandle = new ManualResetEvent (false);
return waitHandle;
}
}
bool IAsyncResult.CompletedSynchronously
{
get {
return reply != null && completedSync;
}
}
bool IAsyncResult.IsCompleted
{
get {
return reply != null;
}
}
#endregion
}
}
| // Copyright 2007 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Threading;
namespace DBus
{
class PendingCall : IAsyncResult
{
Connection conn;
Message reply = null;
//AutoResetEvent waitHandle = new AutoResetEvent (false);
ManualResetEvent waitHandle;
public PendingCall (Connection conn)
{
this.conn = conn;
}
public Message Reply
{
get {
if (reply != null)
return reply;
if (Thread.CurrentThread == conn.mainThread) {
/*
while (reply == null)
conn.Iterate ();
*/
while (reply == null)
conn.HandleMessage (conn.Transport.ReadMessage ());
completedSync = true;
conn.DispatchSignals ();
} else {
if (waitHandle == null)
waitHandle = new ManualResetEvent (false);
// TODO: Possible race condition?
while (reply == null)
waitHandle.WaitOne ();
completedSync = false;
}
return reply;
} set {
if (reply != null)
throw new Exception ("Cannot handle reply more than once");
reply = value;
if (waitHandle != null)
waitHandle.Set ();
if (Completed != null)
Completed (reply);
}
}
public event Action<Message> Completed;
bool completedSync;
public void Cancel ()
{
throw new NotImplementedException ();
}
#region IAsyncResult Members
object IAsyncResult.AsyncState
{
get {
return conn;
}
}
WaitHandle IAsyncResult.AsyncWaitHandle
{
get {
if (waitHandle == null)
waitHandle = new ManualResetEvent (false);
return waitHandle;
}
}
bool IAsyncResult.CompletedSynchronously
{
get {
return reply != null && completedSync;
}
}
bool IAsyncResult.IsCompleted
{
get {
return reply != null;
}
}
#endregion
}
}
| mit | C# |
a378dac98b7558cad1d253dc5da9b5e19ba856e1 | Check RevisionDate in OutlookCardDavUpdateFromNewerToOlder | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer/Implementation/Contacts/OutlookCardDavUpdateFromNewerToOlder.cs | CalDavSynchronizer/Implementation/Contacts/OutlookCardDavUpdateFromNewerToOlder.cs | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using CalDavSynchronizer.Implementation.ComWrappers;
using GenSync.EntityRelationManagement;
using GenSync.Synchronization;
using GenSync.Synchronization.States;
using log4net;
using Microsoft.Office.Interop.Outlook;
using Thought.vCards;
namespace CalDavSynchronizer.Implementation.Contacts
{
internal class OutlookCardDavUpdateFromNewerToOlder
: UpdateFromNewerToOlder<string, DateTime, GenericComObjectWrapper<ContactItem>, Uri, string, vCard>
{
private static readonly ILog s_logger = LogManager.GetLogger (System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType);
public OutlookCardDavUpdateFromNewerToOlder (
EntitySyncStateEnvironment<string, DateTime, GenericComObjectWrapper<ContactItem>, Uri, string, vCard> environment,
IEntityRelationData<string, DateTime, Uri, string> knownData,
DateTime newA,
string newB)
: base (environment, knownData, newA, newB)
{
}
protected override bool AIsNewerThanB
{
get
{
// Assume that no modification means, that the item is never modified. Therefore it must be new.
if (_bEntity.RevisionDate == null)
return false;
return _aEntity.Inner.LastModificationTime.ToUniversalTime() >= _bEntity.RevisionDate.Value;
}
}
}
} | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using CalDavSynchronizer.Implementation.ComWrappers;
using GenSync.EntityRelationManagement;
using GenSync.Synchronization;
using GenSync.Synchronization.States;
using log4net;
using Microsoft.Office.Interop.Outlook;
using Thought.vCards;
namespace CalDavSynchronizer.Implementation.Contacts
{
internal class OutlookCardDavUpdateFromNewerToOlder
: UpdateFromNewerToOlder<string, DateTime, GenericComObjectWrapper<ContactItem>, Uri, string, vCard>
{
private static readonly ILog s_logger = LogManager.GetLogger (System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType);
public OutlookCardDavUpdateFromNewerToOlder (
EntitySyncStateEnvironment<string, DateTime, GenericComObjectWrapper<ContactItem>, Uri, string, vCard> environment,
IEntityRelationData<string, DateTime, Uri, string> knownData,
DateTime newA,
string newB)
: base (environment, knownData, newA, newB)
{
}
protected override bool AIsNewerThanB
{
get
{
// TODO:
s_logger.ErrorFormat ("This method is not yet implemented and considers outlook version always as newer.");
return true;
// Assume that no modification means, that the item is never modified. Therefore it must be new.
//if (_bEntity.RevisionDate == null)
// return false;
//return _aEntity.Inner.LastModificationTime.ToUniversalTime() >= _bEntity.RevisionDate.Value;
}
}
}
} | agpl-3.0 | C# |
551db9269a909027e9c868675155deb1daec7dbb | Correct spelling mistake | Paymentsense/Dapper.SimpleSave | PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/ITaskNotificationService.cs | PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/ITaskNotificationService.cs | using System;
using System.Collections.Generic;
using System.ServiceModel;
using PS.Mothership.Core.Common.Dto.Notification;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(CallbackContract = typeof(ITaskNotificationCallback))]
public interface ITaskNotificationService
{
[OperationContract(IsOneWay = false)]
void Subscribe(string applicationName);
[OperationContract(IsOneWay = true)]
void EndSubscribe(string applicationName);
[OperationContract]
TaskNotificationDto AddNewTask(TaskNotificationDto taskNotificationDto);
[OperationContract]
IList<TaskNotificationDto> RetrieveUserTasks(Guid userGuid);
[OperationContract]
TaskNotificationDto UpdateTask(TaskNotificationDto taskNotificationDto);
[OperationContract]
void CloseTask(TaskNotificationDto taskNotificationDto);
[OperationContract]
void CancelTask(TaskNotificationDto taskNotificationDto);
}
}
| using System;
using System.Collections.Generic;
using System.ServiceModel;
using PS.Mothership.Core.Common.Dto.Notification;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(CallbackContract = typeof(ITaskNotificationCallback))]
public interface ITaskNotificationService
{
[OperationContract(IsOneWay = false)]
void Subscribe(string applicationName);
[OperationContract(IsOneWay = true)]
void EndSubscribe(string applicationName);
[OperationContract]
TaskNotificationDto AddNewTask(TaskNotificationDto taskNotificationDto);
[OperationContract]
IList<TaskNotificationDto> RetreiveUserTasks(Guid userGuid);
[OperationContract]
TaskNotificationDto UpdateTask(TaskNotificationDto taskNotificationDto);
[OperationContract]
void CloseTask(TaskNotificationDto taskNotificationDto);
[OperationContract]
void CancelTask(TaskNotificationDto taskNotificationDto);
}
}
| mit | C# |
a9f6933da637b8f6e42b85767a18887f7d439937 | Bump up version number to 2.12 | Klocman/Bulk-Crap-Uninstaller,Klocman/Bulk-Crap-Uninstaller,Klocman/Bulk-Crap-Uninstaller | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System.Reflection;
// 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: AssemblyCompany("Marcin Szeniak")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// 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("2.12.0.0")] | using System.Reflection;
// 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: AssemblyCompany("Marcin Szeniak")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// 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("2.11.0.0")] | apache-2.0 | C# |
9a5395fbc48ef14f50071f1c8e24dc3c4053b66a | Allow usage of Avg outside of dynamic filtering | bojanrajkovic/pingu | src/Pingu/Filters/Filters.cs | src/Pingu/Filters/Filters.cs | using System;
using System.Numerics;
namespace Pingu.Filters
{
static class DefaultFilters
{
public static IFilter GetFilterForType(FilterType filter)
{
switch (filter) {
case FilterType.None:
return NullFilter.Instance;
case FilterType.Sub:
return SubFilter.Instance;
case FilterType.Up:
return UpFilter.Instance;
case FilterType.Average:
return AvgFilter.Instance;
case FilterType.Paeth:
throw new NotImplementedException();
case FilterType.Dynamic:
return DynamicFilter.Instance;
default:
throw new ArgumentOutOfRangeException(nameof(filter));
}
}
public static readonly bool UseVectors = true;
static DefaultFilters()
{
// If we're on Mono, don't use vectors.
if (Type.GetType("Mono.Runtime") != null)
UseVectors = false;
// If Vectors aren't hardware accelerated, use pointers.
if (!Vector.IsHardwareAccelerated)
UseVectors = false;
}
}
}
| using System;
using System.Numerics;
namespace Pingu.Filters
{
static class DefaultFilters
{
public static IFilter GetFilterForType(FilterType filter)
{
switch (filter) {
case FilterType.None:
return NullFilter.Instance;
case FilterType.Sub:
return SubFilter.Instance;
case FilterType.Up:
return UpFilter.Instance;
case FilterType.Average:
throw new NotImplementedException();
case FilterType.Paeth:
throw new NotImplementedException();
case FilterType.Dynamic:
return DynamicFilter.Instance;
default:
throw new ArgumentOutOfRangeException(nameof(filter));
}
}
public static readonly bool UseVectors = true;
static DefaultFilters()
{
// If we're on Mono, don't use vectors.
if (Type.GetType("Mono.Runtime") != null)
UseVectors = false;
// If Vectors aren't hardware accelerated, use pointers.
if (!Vector.IsHardwareAccelerated)
UseVectors = false;
}
}
}
| mit | C# |
1a52f121733609293e1a0bb5869233b02fec7264 | Fix Necronomicon flipping too many pages when submitting | samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/NecronomiconComponentSolver.cs | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/NecronomiconComponentSolver.cs | using System;
using System.Collections;
using UnityEngine;
public class NecronomiconComponentSolver : ComponentSolver
{
public NecronomiconComponentSolver(TwitchModule module) :
base(module)
{
_component = Module.BombComponent.GetComponent(ComponentType);
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Cycle all the pages using !{0} cycle. Submit a specific page using !{0} page 3.");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
inputCommand = inputCommand.ToLowerInvariant().Trim();
string[] split = inputCommand.Split(new[] { ' ', ',', ';' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1 && split[0].EqualsAny("cycle", "c", "pages"))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 0; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return new WaitForSecondsWithCancel(2.25f, false, this);
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
for (int i = pagesTurned; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
else if (split.Length == 2 && split[0].EqualsAny("page", "p") && int.TryParse(split[1], out int pageNumber) && pageNumber.InRange(1, 8))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 1; i < pageNumber; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
if (CoroutineCanceller.ShouldCancel)
{
for (int i = pagesTurned; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
yield return "solve";
yield return "strike";
}
}
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
yield return RespondToCommandInternal("page " + _component.GetValue<int>("correctPage"));
}
static NecronomiconComponentSolver()
{
ComponentType = ReflectionHelper.FindType("necronomiconScript");
}
private static readonly Type ComponentType;
private readonly object _component;
private readonly KMSelectable[] selectables;
}
| using System;
using System.Collections;
using UnityEngine;
public class NecronomiconComponentSolver : ComponentSolver
{
public NecronomiconComponentSolver(TwitchModule module) :
base(module)
{
_component = Module.BombComponent.GetComponent(ComponentType);
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Cycle all the pages using !{0} cycle. Submit a specific page using !{0} page 3.");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
inputCommand = inputCommand.ToLowerInvariant().Trim();
string[] split = inputCommand.Split(new[] { ' ', ',', ';' }, System.StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1 && split[0].EqualsAny("cycle", "c", "pages"))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 0; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return new WaitForSecondsWithCancel(2.25f, false, this);
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
for (int i = pagesTurned; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
}
else if (split.Length == 2 && split[0].EqualsAny("page", "p") && int.TryParse(split[1], out int pageNumber) && pageNumber.InRange(1, 8))
{
yield return null;
yield return DoInteractionClick(selectables[0]);
int pagesTurned = 0;
for (int i = 1; i < pageNumber; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
if (CoroutineCanceller.ShouldCancel)
break;
pagesTurned = i;
yield return DoInteractionClick(selectables[1]);
}
for (int i = pagesTurned; i < 8; i++)
{
yield return new WaitUntil(() => !_component.GetValue<bool>("animating"));
yield return DoInteractionClick(selectables[1]);
}
yield return "solve";
yield return "strike";
}
}
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
yield return RespondToCommandInternal("page " + _component.GetValue<int>("correctPage"));
}
static NecronomiconComponentSolver()
{
ComponentType = ReflectionHelper.FindType("necronomiconScript");
}
private static readonly Type ComponentType;
private readonly object _component;
private readonly KMSelectable[] selectables;
}
| mit | C# |
a047ab48faf466bf66f1c80216c922de42eeb463 | Fix UITest for b#42832 (#471) | Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms | Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla42832.cs | Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla42832.cs | using System;
using System.Collections.Generic;
using Xamarin.Forms.Internals;
using Xamarin.Forms.CustomAttributes;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
#endif
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 42832, "Scrolling a ListView with active ContextAction Items causes NRE", PlatformAffected.Android)]
public class Bugzilla42832 : TestContentPage
{
ListView listview;
protected override void Init()
{
var items = new List<string>();
for(int i=0; i<20; i++)
items.Add($"Item #{i}");
var template = new DataTemplate(typeof(TestCell));
template.SetBinding(TextCell.TextProperty, ".");
listview = new ListView(ListViewCachingStrategy.RetainElement)
{
AutomationId = "mainList",
ItemsSource = items,
ItemTemplate = template
};
Content = listview;
}
[Preserve(AllMembers = true)]
public class TestCell : TextCell
{
public TestCell()
{
var menuItem = new MenuItem { Text = "Test Item" };
ContextActions.Add(menuItem);
}
}
#if UITEST && __ANDROID__
[Test]
public void ContextActionsScrollNRE()
{
RunningApp.TouchAndHold(q => q.Marked("Item #0"));
RunningApp.WaitForElement(q => q.Marked("Test Item"));
int counter = 0;
while(counter < 5)
{
RunningApp.ScrollDownTo("Item #15", "mainList", ScrollStrategy.Gesture, timeout:TimeSpan.FromMinutes(1));
RunningApp.ScrollUpTo("Item #0", "mainList", ScrollStrategy.Gesture, timeout: TimeSpan.FromMinutes(1));
counter++;
}
RunningApp.Screenshot("If the app did not crash, then the test has passed.");
}
#endif
}
}
| using System;
using System.Collections.Generic;
using Xamarin.Forms.Internals;
using Xamarin.Forms.CustomAttributes;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
#endif
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 42832, "Scrolling a ListView with active ContextAction Items causes NRE", PlatformAffected.Android)]
public class Bugzilla42832 : TestContentPage
{
ListView listview;
protected override void Init()
{
var items = new List<string>();
for(int i=0; i<20; i++)
items.Add($"Item #{i}");
var template = new DataTemplate(typeof(TestCell));
template.SetBinding(TextCell.TextProperty, ".");
listview = new ListView(ListViewCachingStrategy.RetainElement)
{
AutomationId = "mainList",
ItemsSource = items,
ItemTemplate = template
};
Content = listview;
}
[Preserve(AllMembers = true)]
public class TestCell : TextCell
{
public TestCell()
{
var menuItem = new MenuItem { Text = "Test Item" };
ContextActions.Add(menuItem);
}
}
#if UITEST
[Test]
public void ContextActionsScrollNRE()
{
// mark is an icon on android
RunningApp.TouchAndHold(q => q.Marked("Item #0"));
RunningApp.WaitForElement(q => q.Marked("Test Item"));
int counter = 0;
while(counter < 5)
{
RunningApp.ScrollDownTo("Item #15", "mainList", ScrollStrategy.Gesture, timeout:TimeSpan.FromMinutes(1));
RunningApp.ScrollUpTo("Item #0", "mainList", ScrollStrategy.Gesture, timeout: TimeSpan.FromMinutes(1));
counter++;
}
RunningApp.Screenshot("If the app did not crash, then the test has passed.");
}
#endif
}
}
| mit | C# |
1ec083f9959d940c2b8b807ee551051092750846 | Make Who's On First's help message (slightly) less confusing | ashbash1987/ktanemod-twitchplays,CaitSith2/ktanemod-twitchplays | Assets/Scripts/ComponentSolvers/Vanilla/WhosOnFirstComponentSolver.cs | Assets/Scripts/ComponentSolvers/Vanilla/WhosOnFirstComponentSolver.cs | using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
public class WhosOnFirstComponentSolver : ComponentSolver
{
public WhosOnFirstComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
_buttons = (Array)_buttonsField.GetValue(bombComponent);
helpMessage = "Press a button with !{0} what?. Phrase must match exactly, not case sensitive.";
manualCode = "Who%E2%80%99s%20on%20First";
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
foreach (object buttonObject in _buttons)
{
MonoBehaviour button = (MonoBehaviour)buttonObject;
string buttonText = (string)_getTextMethod.Invoke(button, null);
if (inputCommand.Equals(buttonText, StringComparison.InvariantCultureIgnoreCase))
{
yield return buttonText;
DoInteractionStart(button);
yield return new WaitForSeconds(0.1f);
DoInteractionEnd(button);
break;
}
}
}
static WhosOnFirstComponentSolver()
{
_whosOnFirstComponentType = ReflectionHelper.FindType("WhosOnFirstComponent");
_buttonsField = _whosOnFirstComponentType.GetField("Buttons", BindingFlags.Public | BindingFlags.Instance);
_keypadButtonType = ReflectionHelper.FindType("KeypadButton");
_getTextMethod = _keypadButtonType.GetMethod("GetText", BindingFlags.Public | BindingFlags.Instance);
}
private static Type _whosOnFirstComponentType = null;
private static FieldInfo _buttonsField = null;
private static Type _keypadButtonType = null;
private static MethodInfo _getTextMethod = null;
private Array _buttons = null;
}
| using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
public class WhosOnFirstComponentSolver : ComponentSolver
{
public WhosOnFirstComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
_buttons = (Array)_buttonsField.GetValue(bombComponent);
helpMessage = "Press a button with !{0} phrase. Phrase must match exactly, not case sensitive.";
manualCode = "Who%E2%80%99s%20on%20First";
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
foreach (object buttonObject in _buttons)
{
MonoBehaviour button = (MonoBehaviour)buttonObject;
string buttonText = (string)_getTextMethod.Invoke(button, null);
if (inputCommand.Equals(buttonText, StringComparison.InvariantCultureIgnoreCase))
{
yield return buttonText;
DoInteractionStart(button);
yield return new WaitForSeconds(0.1f);
DoInteractionEnd(button);
break;
}
}
}
static WhosOnFirstComponentSolver()
{
_whosOnFirstComponentType = ReflectionHelper.FindType("WhosOnFirstComponent");
_buttonsField = _whosOnFirstComponentType.GetField("Buttons", BindingFlags.Public | BindingFlags.Instance);
_keypadButtonType = ReflectionHelper.FindType("KeypadButton");
_getTextMethod = _keypadButtonType.GetMethod("GetText", BindingFlags.Public | BindingFlags.Instance);
}
private static Type _whosOnFirstComponentType = null;
private static FieldInfo _buttonsField = null;
private static Type _keypadButtonType = null;
private static MethodInfo _getTextMethod = null;
private Array _buttons = null;
}
| mit | C# |
01f22ffaa8f9eb657a79c2fb74b8b96c9ff6898a | create api method for retrieve achievements using the achievement retriever service | YeeRSoft/broken-shoe-league,YeeRSoft/broken-shoe-league,YeeRSoft/broken-shoe-league | Source/BrokenShoeLeague.Web.API/Controllers/AchievementsController.cs | Source/BrokenShoeLeague.Web.API/Controllers/AchievementsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BrokenShoeLeague.Domain.Repositories;
using BrokenShoeLeague.Services.Achievement;
namespace BrokenShoeLeague.Web.API.Controllers
{
[RoutePrefix("api/v1/achievements")]
public class AchievementsController : ApiController
{
private readonly IBrokenShoeLeagueRepository _brokenShoeLeagueRepository;
private readonly IAchivementProviderService _achivementProviderService;
public AchievementsController(IBrokenShoeLeagueRepository brokenShoeLeagueRepository, IAchivementProviderService achivementProviderService)
{
_brokenShoeLeagueRepository = brokenShoeLeagueRepository;
_achivementProviderService = achivementProviderService;
}
[Route("")]
public IHttpActionResult GetAchievements()
{
var achievements = _achivementProviderService.GetAchievements().ToArray();
return Ok(achievements);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BrokenShoeLeague.Domain.Repositories;
using BrokenShoeLeague.Services.Achievement;
namespace BrokenShoeLeague.Web.API.Controllers
{
[RoutePrefix("api/v1/achievements")]
public class AchievementsController : ApiController
{
private readonly IBrokenShoeLeagueRepository _brokenShoeLeagueRepository;
private readonly IAchivementProviderService _achivementProviderService;
public AchievementsController(IBrokenShoeLeagueRepository brokenShoeLeagueRepository, IAchivementProviderService achivementProviderService)
{
_brokenShoeLeagueRepository = brokenShoeLeagueRepository;
_achivementProviderService = achivementProviderService;
}
[Route("")]
public IHttpActionResult GetAchievements()
{
return Ok(_achivementProviderService.GetAchievements());
}
}
}
| mit | C# |
afaa18f1aa399823b76441de3f10d5dee0f693e3 | Add AwaitTask. | nessos/Eff | src/Eff.Tests/EffTests.cs | src/Eff.Tests/EffTests.cs | using Eff.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Eff.Tests
{
public class EffTests
{
[Fact]
public void SimpleReturn()
{
async Eff<int> Foo(int x)
{
return x + 1;
}
Assert.Equal(2, Foo(1).Result);
}
[Fact]
public void AwaitEff()
{
async Eff<int> Bar(int x)
{
return x + 1;
}
async Eff<int> Foo(int x)
{
var y = await Bar(x);
return y + 1;
}
Assert.Equal(3, Foo(1).Result);
}
[Fact]
public void AwaitTask()
{
async Eff<int> Foo(int x)
{
var y = await Task.FromResult(x + 1);
return y + 1;
}
Assert.Equal(3, Foo(1).Result);
}
}
}
| using Eff.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Eff.Tests
{
public class EffTests
{
[Fact]
public void SimpleReturn()
{
async Eff<int> Foo(int x)
{
return x + 1;
}
Assert.Equal(2, Foo(1).Result);
}
[Fact]
public void AwaitEff()
{
async Eff<int> Bar(int x)
{
return x + 1;
}
async Eff<int> Foo(int x)
{
var y = await Bar(x);
return y + 1;
}
Assert.Equal(3, Foo(1).Result);
}
}
}
| mit | C# |
993e9dcdd097abac9a6404b66fad9d0b6ab119bf | fix the connection exception (move Connect() out of OnGUI()) | PerfAssist/ResourceTracker,mc-gulu/ResourceTracker | Assets/PerfAssist/ResourceTracker/Editor/PAContrib/TrackerModes/TrackerMode_Remote.cs | Assets/PerfAssist/ResourceTracker/Editor/PAContrib/TrackerModes/TrackerMode_Remote.cs | using MemoryProfilerWindow;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.MemoryProfiler;
using UnityEngine;
public class TrackerMode_Remote : TrackerMode_Base
{
bool _autoSaveToggle = true;
string _IPField = MemConst.RemoteIPDefaultText;
bool _connectPressed = false;
public override void Update()
{
if (_connectPressed)
{
TrackerModeUtil.Connect(_IPField);
_connectPressed = false;
}
}
public override void OnGUI()
{
GUI.SetNextControlName("LoginIPTextField");
var currentStr = GUILayout.TextField(_IPField, GUILayout.Width(100));
if (!_IPField.Equals(currentStr))
{
_IPField = currentStr;
}
if (GUI.GetNameOfFocusedControl().Equals("LoginIPTextField") && _IPField.Equals(MemConst.RemoteIPDefaultText))
{
_IPField = "";
}
bool savedState = GUI.enabled;
bool connected = NetManager.Instance != null && NetManager.Instance.IsConnected && MemUtil.IsProfilerConnectedRemotely;
GUI.enabled = !connected;
if (GUILayout.Button("Connect", GUILayout.Width(80)))
{
_connectPressed = true;
}
GUI.enabled = connected;
if (GUILayout.Button("Take Snapshot", GUILayout.Width(100)))
{
MemorySnapshot.RequestNewSnapshot();
}
GUI.enabled = savedState;
GUILayout.Space(DrawIndicesGrid(300, 20));
GUILayout.FlexibleSpace();
_autoSaveToggle = GUILayout.Toggle(_autoSaveToggle, new GUIContent("AutoSave"), GUILayout.MaxWidth(80));
if (GUILayout.Button("Open Dir", GUILayout.MaxWidth(80)))
{
EditorUtility.RevealInFinder(MemUtil.SnapshotsDir);
}
}
public override bool SaveSessionInfo(PackedMemorySnapshot packed, CrawledMemorySnapshot unpacked)
{
if (!_autoSaveToggle)
return false;
string sessionName = _sessionTimeStr + TrackerModeConsts.RemoteTag + _IPField;
return TrackerModeUtil.SaveSnapshotFiles(sessionName, _selected.ToString(), packed, unpacked);
}
}
| using MemoryProfilerWindow;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.MemoryProfiler;
using UnityEngine;
public class TrackerMode_Remote : TrackerMode_Base
{
bool _autoSaveToggle = true;
string _IPField = MemConst.RemoteIPDefaultText;
public override void OnGUI()
{
GUI.SetNextControlName("LoginIPTextField");
var currentStr = GUILayout.TextField(_IPField, GUILayout.Width(80));
if (!_IPField.Equals(currentStr))
{
_IPField = currentStr;
}
if (GUI.GetNameOfFocusedControl().Equals("LoginIPTextField") && _IPField.Equals(MemConst.RemoteIPDefaultText))
{
_IPField = "";
}
bool savedState = GUI.enabled;
bool connected = NetManager.Instance != null && NetManager.Instance.IsConnected && MemUtil.IsProfilerConnectedRemotely;
GUI.enabled = !connected;
if (GUILayout.Button("Connect", GUILayout.Width(60)))
{
TrackerModeUtil.Connect(_IPField);
}
GUI.enabled = connected;
if (GUILayout.Button("Take Snapshot", GUILayout.Width(100)))
{
MemorySnapshot.RequestNewSnapshot();
}
GUI.enabled = savedState;
GUILayout.Space(DrawIndicesGrid(250, 20));
GUILayout.FlexibleSpace();
_autoSaveToggle = GUILayout.Toggle(_autoSaveToggle, new GUIContent("AutoSave"), GUILayout.MaxWidth(80));
if (GUILayout.Button("Open Dir", GUILayout.MaxWidth(80)))
{
EditorUtility.RevealInFinder(MemUtil.SnapshotsDir);
}
}
public override bool SaveSessionInfo(PackedMemorySnapshot packed, CrawledMemorySnapshot unpacked)
{
if (!_autoSaveToggle)
return false;
string sessionName = _sessionTimeStr + TrackerModeConsts.RemoteTag + _IPField;
return TrackerModeUtil.SaveSnapshotFiles(sessionName, _selected.ToString(), packed, unpacked);
}
}
| mit | C# |
1666699503852cdc5180c946e9599e92f1a36cd6 | Fix typo | tpetricek/FSharp.Data,scrwtp/FSharp.Data,fsprojects/ApiaryProvider,AtwooTM/FSharp.Data,johansson/FSharp.Data,tpetricek/FSharp.Data,taylorwood/FSharp.Data,olgierdd/FSharp.Data,olgierdd/FSharp.Data,AtwooTM/FSharp.Data,taylorwood/FSharp.Data,taylorwood/FSharp.Data,tpetricek/FSharp.Data,scrwtp/FSharp.Data,scrwtp/FSharp.Data,ImaginaryDevelopment/FSharp.Data,ImaginaryDevelopment/FSharp.Data,NaseUkolyCZ/ApiaryProvider,johansson/FSharp.Data,johansson/FSharp.Data,olgierdd/FSharp.Data,ImaginaryDevelopment/FSharp.Data,AtwooTM/FSharp.Data | docs/tools/reference/type.cshtml | docs/tools/reference/type.cshtml | @using FSharp.MetadataFormat
@{
Layout = "template";
Title = Model.Type.Name + " - " + Properties["project-name"];
}
@{
var members = (IEnumerable<Member>)Model.Type.AllMembers;
var comment = (Comment)Model.Type.Comment;
var byCategory =
members.GroupBy(m => m.Category).OrderBy(g => String.IsNullOrEmpty(g.Key) ? "ZZZ" : g.Key)
.Select((g, n) => new { Index = n, GroupKey = g.Key, Members = g.OrderBy(m => m.Name), Name = String.IsNullOrEmpty(g.Key) ? "Other type members" : g.Key });
}
<h1>@Model.Type.Name</h1>
<div class="xmldoc">
@foreach (var sec in comment.Sections) {
if (!byCategory.Any(g => g.GroupKey == sec.Key)) {
if (sec.Key != "<default>") {
<h2>@sec.Key</h2>
}
@sec.Value
}
}
</div>
@if (byCategory.Count() > 1)
{
<h2>Table of contents</h2>
<ul>
@foreach (var g in byCategory)
{
<li><a href="@("#section" + g.Index.ToString())">@g.Name</a></li>
}
</ul>
}
@foreach (var g in byCategory) {
if (byCategory.Count() > 1) {
<h2>@g.Name<a name="@("section" + g.Index.ToString())"> </a></h2>
var info = comment.Sections.FirstOrDefault(kvp => kvp.Key == g.GroupKey);
if (info.Key != null) {
<div class="xmldoc">
@info.Value
</div>
}
}
@RenderPart("members", new {
Header = "Union Cases",
TableHeader = "Union Case",
Members = Model.Type.UnionCases
})
@RenderPart("members", new {
Header = "Record Fields",
TableHeader = "Record Field",
Members = Model.Type.RecordFields
})
@RenderPart("members", new {
Header = "Constructors",
TableHeader = "Constructor",
Members = g.Members.Where(m => m.Kind == MemberKind.Constructor)
})
@RenderPart("members", new {
Header = "Instance members",
TableHeader = "Instance member",
Members = g.Members.Where(m => m.Kind == MemberKind.InstanceMember)
})
@RenderPart("members", new {
Header = "Static members",
TableHeader = "Static member",
Members = g.Members.Where(m => m.Kind == MemberKind.StaticMember)
})
}
| @using FSharp.MetadataFormat
@{
Layout = "template";
Title = Model.Type.Name + " - " + Properties["project-name"];
}
@{
var members = (IEnumerable<Member>)Model.Type.AllMembers;
var comment = (Comment)Model.Type.Comment;
var byCategory =
members.GroupBy(m => m.Category).OrderBy(g => String.IsNullOrEmpty(g.Key) ? "ZZZ" : g.Key)
.Select((g, n) => new { Index = n, GroupKey = g.Key, Members = g.OrderBy(m => m.Name), Name = String.IsNullOrEmpty(g.Key) ? "Other type members" : g.Key });
}
<h1>@Model.Type.Name</h1>
<div class="xmldoc">
@foreach (var sec in comment.Sections) {
if (!byCategory.Any(g => g.GroupKey == sec.Key)) {
if (sec.Key != "<default>") {
<h2>@sec.Key</h2>
}
@sec.Value
}
}
</div>
@if (byCategory.Count() > 1)
{
<h2>Table of contents</h2>
<ul>
@foreach (var g in byCategory)
{
<li><a href="@("#section" + g.Index.ToString())">@g.Name</a></li>
}
</ul>
}
@foreach (var g in byCategory) {
if (byCategory.Count() > 1) {
<h2>@g.Name<a name="@("section" + g.Index.ToString())"> </a></h2>
var info = comment.Sections.FirstOrDefault(kvp => kvp.Key == g.GroupKey);
if (info.Key != null) {
<div class="xmldoc">
@info.Value
</div>
}
}
@RenderPart("members", new {
Header = "Union Cases",
TableHeader = "Union Case",
Members = Model.Type.UnionCases
})
@RenderPart("members", new {
Header = "Record Fields",
TableHeader = "Record Fieldr",
Members = Model.Type.RecordFields
})
@RenderPart("members", new {
Header = "Constructors",
TableHeader = "Constructor",
Members = g.Members.Where(m => m.Kind == MemberKind.Constructor)
})
@RenderPart("members", new {
Header = "Instance members",
TableHeader = "Instance member",
Members = g.Members.Where(m => m.Kind == MemberKind.InstanceMember)
})
@RenderPart("members", new {
Header = "Static members",
TableHeader = "Static member",
Members = g.Members.Where(m => m.Kind == MemberKind.StaticMember)
})
}
| apache-2.0 | C# |
ad0d62f7ff226e611ab214725c6b25d161a86de4 | Add usage example | agc93/Cake.NSwag | usage.cake | usage.cake | #r "dist/lib/Cake.NSwag.dll"
Task("Sample")
.Does(() => {
CreateDirectory("./dist/sample");
#break
NSwag.FromSwaggerSpecification("./samples/swagger.json")
.ToCSharpClient("./client.cs", "Swagger.Client")
.ToTypeScriptClient("./client.ts", s => s.WithClassName("Client").WithModuleName("Swagger"));
});
Task("Full-Settings")
.Does(() => {
NSwag.FromSwaggerSpecification("./samples/swagger.json")
.ToTypeScriptClient("./client.ts", s =>
s.WithClassName("ApiClient")
.WithModuleName("SwaggerApi")
.WithSettings(new SwaggerToTypeScriptClientGeneratorSettings
{
PromiseType = PromiseType.Promise
}));
});
RunTarget("Sample");
| #r "dist/lib/Cake.NSwag.dll"
Task("Sample")
.Does(() => {
CreateDirectory("./dist/sample");
#break
NSwag.FromSwaggerSpecification("./sample/swagger.json")
.ToCSharpClient("./client.cs", "Swagger.Client")
.ToTypeScriptClient("./client.ts", s => s.WithClassName("Client").WithModuleName("Swagger"));
});
RunTarget("Sample");
| mit | C# |
548468a9c76037a655b8503c89af7ea21c8929ab | increment minor version, | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.21.0")]
[assembly: AssemblyInformationalVersion("0.21.0")]
/*
* Version 0.21.0
*
* - [FIX] Makes a test fixture creating a specimen without auto-properties as
* default. (BREAKING-CHANGE)
*
* - [NEW] Implements AutoPropertiesAttribute to explicitly set auto-properties
* of a specimen.
*
* - [NEW] Imports NoAutoPropertiesAttribute from AutoFixture.Xunit.
*
* - [NEW] Makes the TestCase class accepting the Delegate parameter to avoid
* the ambiguousness between Action and Func supplied to constructor parameter
* of generic TestCase, and removes all the generic TestCase classes.
* (BREAKING-CHANGE)
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.20.0")]
[assembly: AssemblyInformationalVersion("0.20.0")]
/*
* Version 0.21.0
*
* - [FIX] Makes a test fixture creating a specimen without auto-properties as
* default. (BREAKING-CHANGE)
*
* - [NEW] Implements AutoPropertiesAttribute to explicitly set auto-properties
* of a specimen.
*
* - [NEW] Imports NoAutoPropertiesAttribute from AutoFixture.Xunit.
*
* - [NEW] Makes the TestCase class accepting the Delegate parameter to avoid
* the ambiguousness between Action and Func supplied to constructor parameter
* of generic TestCase, and removes all the generic TestCase classes.
* (BREAKING-CHANGE)
*/ | mit | C# |
986130e845cd4aad155c81649d7289a8fa07c2a6 | Move version to 0.9.3-dev | radegastdev/libopenmetaverse,radegastdev/libopenmetaverse,radegastdev/libopenmetaverse,radegastdev/libopenmetaverse | OpenMetaverse/AssemblyInfo.cs | OpenMetaverse/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("OpenMetaverse")]
[assembly: AssemblyDescription("OpenMetaverse library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("openmetaverse.org")]
[assembly: AssemblyProduct("OpenMetaverse")]
[assembly: AssemblyCopyright("Copyright openmetaverse.org 2006-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.9.3.0")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
[assembly: AssemblyFileVersionAttribute("0.9.3.0")]
| 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("OpenMetaverse")]
[assembly: AssemblyDescription("OpenMetaverse library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("openmetaverse.org")]
[assembly: AssemblyProduct("OpenMetaverse")]
[assembly: AssemblyCopyright("Copyright openmetaverse.org 2006-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.9.2.3173")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
[assembly: AssemblyFileVersionAttribute("0.9.2.3173")]
| bsd-3-clause | C# |
2a3b3e846dc0a872e5cf407ecf4c5635fa39407c | update dependencies and android projec | 0xFireball/DeIonizer | DeIonizer/DeIonizer.Android/MainActivity.cs | DeIonizer/DeIonizer.Android/MainActivity.cs | using Android.App;
using Android.OS;
using Avalonia;
using DeIonizer.SharedUI;
namespace DeIonizer.Android
{
[Activity(Label = "DeIonizer.Android", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
App app;
if (Avalonia.Application.Current != null)
{
app = (App)Avalonia.Application.Current;
}
else
{
app = new App();
AppBuilder.Configure(app)
.UseAndroid()
.UseSkia()
.SetupWithoutStarting();
}
}
}
} | using Android.App;
using Android.OS;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Android.Platform.Specific;
using Avalonia.Markup.Xaml;
using DeIonizer.SharedUI;
namespace DeIonizer.Android
{
[Activity(Label = "DeIonizer.Android", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
App app;
if (Avalonia.Application.Current != null)
{
app = (App)Avalonia.Application.Current;
}
else
{
app = new App();
AppBuilder.Configure(app)
.UseAndroid()
.UseSkia()
.SetupWithoutStarting();
}
}
}
} | agpl-3.0 | C# |
b9f67b1fca958080e853ad78141c4be017b4882f | Fix the build error | migueldeicaza/TensorFlowSharp,migueldeicaza/TensorFlowSharp,migueldeicaza/TensorFlowSharp | Examples/ExampleCommon/ImageUtil.cs | Examples/ExampleCommon/ImageUtil.cs | using System.IO;
using TensorFlow;
namespace ExampleCommon
{
public static class ImageUtil
{
// Convert the image in filename to a Tensor suitable as input to the Inception model.
public static TFTensor CreateTensorFromImageFile (string file, TFDataType destinationDataType = TFDataType.Float)
{
var contents = File.ReadAllBytes (file);
// DecodeJpeg uses a scalar String-valued tensor as input.
var tensor = TFTensor.CreateString (contents);
TFOutput input, output;
// Construct a graph to normalize the image
using (var graph = ConstructGraphToNormalizeImage (out input, out output, destinationDataType)){
// Execute that graph to normalize this one image
using (var session = new TFSession (graph)) {
var normalized = session.Run (
inputs: new [] { input },
inputValues: new [] { tensor },
outputs: new [] { output });
return normalized [0];
}
}
}
// The inception model takes as input the image described by a Tensor in a very
// specific normalized format (a particular image size, shape of the input tensor,
// normalized pixel values etc.).
//
// This function constructs a graph of TensorFlow operations which takes as
// input a JPEG-encoded string and returns a tensor suitable as input to the
// inception model.
private static TFGraph ConstructGraphToNormalizeImage (out TFOutput input, out TFOutput output, TFDataType destinationDataType = TFDataType.Float)
{
// Some constants specific to the pre-trained model at:
// https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
//
// - The model was trained after with images scaled to 224x224 pixels.
// - The colors, represented as R, G, B in 1-byte each were converted to
// float using (value - Mean)/Scale.
const int W = 224;
const int H = 224;
const float Mean = 117;
const float Scale = 1;
var graph = new TFGraph ();
input = graph.Placeholder (TFDataType.String);
output = graph.Cast (graph.Div (
x: graph.Sub (
x: graph.ResizeBilinear (
images: graph.ExpandDims (
input: graph.Cast (
graph.DecodeJpeg (contents: input, channels: 3), DstT: TFDataType.Float),
dim: graph.Const (0, "make_batch")),
size: graph.Const (new int [] { W, H }, "size")),
y: graph.Const (Mean, "mean")),
y: graph.Const (Scale, "scale")), destinationDataType);
return graph;
}
}
}
| using System.IO;
using TensorFlow;
namespace ExampleCommon
{
public static class ImageUtil
{
// Convert the image in filename to a Tensor suitable as input to the Inception model.
public static TFTensor CreateTensorFromImageFile (string file, TFDataType destinationDataType = TFDataType.Float)
{
var contents = File.ReadAllBytes (file);
// DecodeJpeg uses a scalar String-valued tensor as input.
var tensor = TFTensor.CreateString (contents);
TFOutput input, output;
// Construct a graph to normalize the image
using (var graph = ConstructGraphToNormalizeImage (out graph, out input, out output, destinationDataType)){
// Execute that graph to normalize this one image
using (var session = new TFSession (graph)) {
var normalized = session.Run (
inputs: new [] { input },
inputValues: new [] { tensor },
outputs: new [] { output });
return normalized [0];
}
}
}
// The inception model takes as input the image described by a Tensor in a very
// specific normalized format (a particular image size, shape of the input tensor,
// normalized pixel values etc.).
//
// This function constructs a graph of TensorFlow operations which takes as
// input a JPEG-encoded string and returns a tensor suitable as input to the
// inception model.
private static TFGraph ConstructGraphToNormalizeImage (out TFOutput input, out TFOutput output, TFDataType destinationDataType = TFDataType.Float)
{
// Some constants specific to the pre-trained model at:
// https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
//
// - The model was trained after with images scaled to 224x224 pixels.
// - The colors, represented as R, G, B in 1-byte each were converted to
// float using (value - Mean)/Scale.
const int W = 224;
const int H = 224;
const float Mean = 117;
const float Scale = 1;
var graph = new TFGraph ();
input = graph.Placeholder (TFDataType.String);
output = graph.Cast (graph.Div (
x: graph.Sub (
x: graph.ResizeBilinear (
images: graph.ExpandDims (
input: graph.Cast (
graph.DecodeJpeg (contents: input, channels: 3), DstT: TFDataType.Float),
dim: graph.Const (0, "make_batch")),
size: graph.Const (new int [] { W, H }, "size")),
y: graph.Const (Mean, "mean")),
y: graph.Const (Scale, "scale")), destinationDataType);
return graph;
}
}
}
| mit | C# |
a7fa9c0eae5caec02ae116dd0fc76141abc7dacd | Add version to about box | NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,campersau/NuGetPackageExplorer | PackageExplorer/AboutWindow.xaml.cs | PackageExplorer/AboutWindow.xaml.cs | using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using NuGetPe;
using PackageExplorerViewModel;
using Clipboard = System.Windows.Forms.Clipboard;
using StringResources = PackageExplorer.Resources;
namespace PackageExplorer
{
/// <summary>
/// Interaction logic for AboutWindow.xaml
/// </summary>
public partial class AboutWindow : StandardDialog
{
#if STORE
private const string Channel = "Store";
#elif NIGHTLY
private const string Channel = "Nightly";
#elif CHOCO
private const string Channel = "Chocolatey";
#else
private const string Channel = "Zip";
#endif
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public AboutWindow()
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
{
CopyVersionCommand = new RelayCommand(CopyVersion);
InitializeComponent();
ProductTitle.Text = $"{StringResources.Dialog_Title} - {Channel} - {RuntimeInformation.ProcessArchitecture} - ({ typeof(AboutWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion})";
DiagnosticsClient.TrackPageView(nameof(AboutWindow));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
var link = (Hyperlink)sender;
DiagnosticsClient.TrackEvent("AboutWindow_LinkClick", new Dictionary<string, string> { { "Uri", link.NavigateUri.ToString() } });
UriHelper.OpenExternalLink(link.NavigateUri);
}
private void CopyVersion()
{
var version = $"{Channel} - {RuntimeInformation.ProcessArchitecture} - ({ typeof(AboutWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion})";
Clipboard.SetText(version);
}
public ICommand CopyVersionCommand { get; }
}
}
| using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using NuGetPe;
using PackageExplorerViewModel;
using Clipboard = System.Windows.Forms.Clipboard;
using StringResources = PackageExplorer.Resources;
namespace PackageExplorer
{
/// <summary>
/// Interaction logic for AboutWindow.xaml
/// </summary>
public partial class AboutWindow : StandardDialog
{
#if STORE
private const string Channel = "Store";
#elif NIGHTLY
private const string Channel = "Nightly";
#elif CHOCO
private const string Channel = "Chocolatey";
#else
private const string Channel = "Zip";
#endif
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public AboutWindow()
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
{
CopyVersionCommand = new RelayCommand(CopyVersion);
InitializeComponent();
ProductTitle.Text = $"{StringResources.Dialog_Title} - {Channel} - ({ typeof(AboutWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion})";
DiagnosticsClient.TrackPageView(nameof(AboutWindow));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
var link = (Hyperlink)sender;
DiagnosticsClient.TrackEvent("AboutWindow_LinkClick", new Dictionary<string, string> { { "Uri", link.NavigateUri.ToString() } });
UriHelper.OpenExternalLink(link.NavigateUri);
}
private void CopyVersion()
{
var version = $"{Channel} - ({ typeof(AboutWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion})";
Clipboard.SetText(version);
}
public ICommand CopyVersionCommand { get; }
}
}
| mit | C# |
5f97c8b2fe5432100119f94c17fc9b96849a84c9 | Increment T5CANLib version | Just4pLeisure/T5SuiteII,Just4pLeisure/T5SuiteII | T5CANLib/Properties/AssemblyInfo.cs | T5CANLib/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("T5CANLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("T5CANLib")]
[assembly: AssemblyCopyright("Copyright © 2011 Dilemma, 2013 Just4pLeisure")]
[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("ae21975c-6312-4039-9f08-cd167ce6f707")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("T5CANLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("T5CANLib")]
[assembly: AssemblyCopyright("Copyright © 2011 Dilemma, 2013 Just4pLeisure")]
[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("ae21975c-6312-4039-9f08-cd167ce6f707")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
| apache-2.0 | C# |
70d22b22ab43a31f44fa646754db7e5c2e1f2e61 | Add playerID and revisit the moving. | TammiLion/TacoTinder | TacoTinder/Assets/Scripts/Player.cs | TacoTinder/Assets/Scripts/Player.cs | using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public int playerID;
public float baseFireCooldown;
public float baseRotationSpeed;
public God god;
// public Weapon weapon;
public Vector2 direction; // Maybe this should be private?
public Vector2 targetDirection; // This too.
// Temporary
public GameObject tempProjectile;
private float cooldownTimeStamp;
// Use this for initialization
void Start () {
}
public void Move(float horizontal, float vertical) {
targetDirection = new Vector2 (horizontal, vertical);
}
public void Fire () {
// Don't fire when the cooldown is still active.
if (this.cooldownTimeStamp >= Time.time) {
return;
}
// Fire the weapon.
// TODO
Moveable arrowMoveable = Instantiate(tempProjectile).GetComponent<Moveable> ();
arrowMoveable.direction = this.direction;
// Set the cooldown.
this.cooldownTimeStamp = Time.time + this.baseFireCooldown;
}
// Update is called once per frame
void Update () {
float angle = Vector2.Angle (direction, targetDirection);
// this.transform.Rotate (targetDirection.x, angle * baseRotationSpeed * Time.deltaTime);
this.direction = new Vector2 (this.transform.TransformDirection.x , this.transform.TransformDirection.y);
}
}
| using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float baseFireCooldown;
public float baseRotationSpeed;
public God god;
// public Weapon weapon;
public Vector2 direction; // Maybe this should be private?
public Vector2 targetDirection; // This too.
// Temporary
public GameObject tempProjectile;
private float cooldownTimeStamp;
// Use this for initialization
void Start () {
}
public void Move(float horizontal, float vertical) {
targetDirection = new Vector2 (horizontal, vertical);
}
public void Fire () {
// Don't fire when the cooldown is still active.
if (this.cooldownTimeStamp >= Time.time) {
return;
}
// Fire the weapon.
// TODO
Moveable arrowMoveable = Instantiate(tempProjectile).GetComponent<Moveable> ();
arrowMoveable.direction = this.direction;
// Set the cooldown.
this.cooldownTimeStamp = Time.time + this.baseFireCooldown;
}
// Update is called once per frame
void Update () {
float angle = Vector2.Angle (direction, targetDirection);
this.transform.Rotate (targetDirection.x, angle * baseRotationSpeed * Time.deltaTime);
this.direction = new Vector2 (this.transform.TransformDirection.x, this.transform.TransformDirection.y);
}
}
| apache-2.0 | C# |
99ddd8195c46ab87808e2765488929ab2aeb04e8 | Add Matrix3x3 by Vector3 multiplication function | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Viewer/src/common/MathExtensions.cs | Viewer/src/common/MathExtensions.cs | using SharpDX;
using static System.Math;
public static class MathExtensions {
public static double Sqr(double d) {
return d * d;
}
public static double Cube(double d) {
return d * d * d;
}
public static float Sqr(float d) {
return d * d;
}
public static float Cube(float d) {
return d * d * d;
}
public static Quaternion Pow(this Quaternion q, float f) {
return Quaternion.RotationAxis(q.Axis, f * q.Angle);
}
/*
* Return a quaternion q such that v.q == (v.q1).q2, where '.' is Transformation
*/
public static Quaternion Chain(this Quaternion q1, Quaternion q2) {
return q2 * q1;
}
public static double Clamp(double x, double min, double max) {
if (x < min) {
return min;
} else if (x > max) {
return max;
} else {
return x;
}
}
public static float Clamp(float x, float min, float max) {
if (x < min) {
return min;
} else if (x > max) {
return max;
} else {
return x;
}
}
/**
* Properties:
* f[x,c] = x when x is close to 0
* f[x,c] = 0 when Abs[x] > c
*/
public static float TukeysBiweight(float x, float rejectionThreshold) {
float z = x / rejectionThreshold;
if (Abs(z) > 1) {
return 0;
} else {
return x * Sqr(1 - Sqr(z));
}
}
public static Vector3 DegreesToRadians(Vector3 angles) {
return new Vector3(
MathUtil.DegreesToRadians(angles.X),
MathUtil.DegreesToRadians(angles.Y),
MathUtil.DegreesToRadians(angles.Z));
}
public static Vector3 RadiansToDegrees(Vector3 angles) {
return new Vector3(
MathUtil.RadiansToDegrees(angles.X),
MathUtil.RadiansToDegrees(angles.Y),
MathUtil.RadiansToDegrees(angles.Z));
}
public static Vector3 Mul(Matrix3x3 m, Vector3 v) {
return new Vector3(
m.M11 * v.X + m.M12 * v.Y + m.M13 * v.Z,
m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z,
m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z);
}
}
| using SharpDX;
using static System.Math;
public static class MathExtensions {
public static double Sqr(double d) {
return d * d;
}
public static double Cube(double d) {
return d * d * d;
}
public static float Sqr(float d) {
return d * d;
}
public static float Cube(float d) {
return d * d * d;
}
public static Quaternion Pow(this Quaternion q, float f) {
return Quaternion.RotationAxis(q.Axis, f * q.Angle);
}
/*
* Return a quaternion q such that v.q == (v.q1).q2, where '.' is Transformation
*/
public static Quaternion Chain(this Quaternion q1, Quaternion q2) {
return q2 * q1;
}
public static double Clamp(double x, double min, double max) {
if (x < min) {
return min;
} else if (x > max) {
return max;
} else {
return x;
}
}
public static float Clamp(float x, float min, float max) {
if (x < min) {
return min;
} else if (x > max) {
return max;
} else {
return x;
}
}
/**
* Properties:
* f[x,c] = x when x is close to 0
* f[x,c] = 0 when Abs[x] > c
*/
public static float TukeysBiweight(float x, float rejectionThreshold) {
float z = x / rejectionThreshold;
if (Abs(z) > 1) {
return 0;
} else {
return x * Sqr(1 - Sqr(z));
}
}
public static Vector3 DegreesToRadians(Vector3 angles) {
return new Vector3(
MathUtil.DegreesToRadians(angles.X),
MathUtil.DegreesToRadians(angles.Y),
MathUtil.DegreesToRadians(angles.Z));
}
public static Vector3 RadiansToDegrees(Vector3 angles) {
return new Vector3(
MathUtil.RadiansToDegrees(angles.X),
MathUtil.RadiansToDegrees(angles.Y),
MathUtil.RadiansToDegrees(angles.Z));
}
}
| mit | C# |
1721ff3c351cf325eef2921d0264e66d88b95f1c | Package Update #CHANGE: Pushed AdamsLair.WinForms 1.0.3 | AdamsLair/winforms,windygu/winforms | WinForms/Properties/AssemblyInfo.cs | WinForms/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("AdamsLair.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdamsLair.WinForms")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2")]
| mit | C# |
60a35cf16eb145335dbce5a7cec4b2e05ecdcef5 | Update Puzz structure with Rotation and Size | Xeeynamo/KingdomHearts | OpenKh.Kh2/Jiminy/Puzz.cs | OpenKh.Kh2/Jiminy/Puzz.cs | using Xe.BinaryMapper;
namespace OpenKh.Kh2.Jiminy
{
public class Puzz
{
public enum Rotation : byte
{
Fixed = 0x0,
Rotatable = 0x1,
}
public enum PuzzleSize : byte
{
Twelve = 0x0,
FourtyEight = 0x1,
}
[Data] public byte Id { get; set; }
[Data] public byte Unk1 { get; set; }
[Data] public ushort Name { get; set; }
[Data] public ushort RewardItem { get; set; }
[Data(Count = 0xA)] public string FileName { get; set; }
public int PieceRotation
{
get => Unk1 >> 4;
set => Unk1 = (byte)((Unk1 & 0x0F) | (value << 4));
}
public int Size
{
get => Unk1 & 0xF;
set => Unk1 = (byte)((Unk1 & 0xF0) | (value & 0xF));
}
}
}
| using Xe.BinaryMapper;
namespace OpenKh.Kh2.Jiminy
{
public class Puzz
{
public enum PieceSize : byte
{
Twelve = 0x0,
FourtyEight = 0x1,
Twelve2 = 0x10,
FourtyEight2 = 0x11
}
[Data] public byte Id { get; set; }
[Data] public PieceSize Pieces { get; set; }
[Data] public ushort Name { get; set; }
[Data] public ushort RewardItem { get; set; }
[Data(Count = 0xA)] public string FileName { get; set; }
}
}
| mit | C# |
74c76994fb4654a8169602b509b43302b6361aaf | Fix issue with RandomCat logging | Lohikar/XenoBot2 | XenoBot2/Commands/Fun.cs | XenoBot2/Commands/Fun.cs | using System;
using System.Net;
using System.Threading.Tasks;
using Discord;
using XenoBot2.Data;
using XenoBot2.Shared;
using Newtonsoft.Json.Linq;
namespace XenoBot2.Commands
{
internal static class Fun
{
private static Random _rnd;
internal static async Task WhatTheCommit(CommandInfo info, User author, Channel channel)
{
if (_rnd == null)
_rnd = new Random();
Utilities.WriteLog(author, "requested a WhatTheCommit message.");
var msg = Strings.WhatTheCommit.GetRandom().Trim()
.Replace("XNAMEX", Strings.Names.GetRandom())
.Replace("XUPPERNAMEX", Strings.Names.GetRandom().ToUpper())
.Replace("XNUMX", _rnd.Next(9000).ToString());
await channel.SendMessage($"*{msg}*");
}
internal static async Task CatFact(CommandInfo info, User author, Channel channel)
{
Utilities.WriteLog(author, "requested a cat fact.");
await channel.SendMessage($"Cat Fact: *{await Shared.Utilities.GetStringAsync("https://cat-facts-as-a-service.appspot.com/fact")}*");
}
internal static async Task EightBall(CommandInfo info, User author, Channel channel)
{
Utilities.WriteLog(author, "consulted the 8 ball.");
if (info.HasArguments)
{
await channel.SendMessage($"{author.NicknameMention} asked: **{string.Join(" ", info.Arguments)}**\n" +
$"The 8 Ball says... *{Strings.EightBall.GetRandom()}*");
}
else
{
await channel.SendMessage($"*{Strings.EightBall.GetRandom()}*");
}
}
internal static async Task RandomCat(CommandInfo info, User author, Channel channel)
{
using (var client = new WebClient())
{
dynamic result = JObject.Parse(await client.DownloadStringTaskAsync("http://random.cat/meow"));
Utilities.WriteLog(author, "requested a random cat.");
await channel.SendMessage($"{author.NicknameMention}: {result.file}");
}
}
}
}
| using System;
using System.Net;
using System.Threading.Tasks;
using Discord;
using XenoBot2.Data;
using XenoBot2.Shared;
using Newtonsoft.Json.Linq;
namespace XenoBot2.Commands
{
internal static class Fun
{
private static Random _rnd;
internal static async Task WhatTheCommit(CommandInfo info, User author, Channel channel)
{
if (_rnd == null)
_rnd = new Random();
Utilities.WriteLog(author, "requested a WhatTheCommit message.");
var msg = Strings.WhatTheCommit.GetRandom().Trim()
.Replace("XNAMEX", Strings.Names.GetRandom())
.Replace("XUPPERNAMEX", Strings.Names.GetRandom().ToUpper())
.Replace("XNUMX", _rnd.Next(9000).ToString());
await channel.SendMessage($"*{msg}*");
}
internal static async Task CatFact(CommandInfo info, User author, Channel channel)
{
Utilities.WriteLog(author, "requested a cat fact.");
await channel.SendMessage($"Cat Fact: *{await Shared.Utilities.GetStringAsync("https://cat-facts-as-a-service.appspot.com/fact")}*");
}
internal static async Task EightBall(CommandInfo info, User author, Channel channel)
{
Utilities.WriteLog(author, "consulted the 8 ball.");
if (info.HasArguments)
{
await channel.SendMessage($"{author.NicknameMention} asked: **{string.Join(" ", info.Arguments)}**\n" +
$"The 8 Ball says... *{Strings.EightBall.GetRandom()}*");
}
else
{
await channel.SendMessage($"*{Strings.EightBall.GetRandom()}*");
}
}
internal static async Task RandomCat(CommandInfo info, User author, Channel channel)
{
using (var client = new WebClient())
{
dynamic result = JObject.Parse(await client.DownloadStringTaskAsync("http://random.cat/meow"));
Utilities.WriteLog("requested a random cat.");
await channel.SendMessage($"{author.NicknameMention}: {result.file}");
}
}
}
}
| mit | C# |
ba3f14b708ea3ddf83aa77bf5995927c5b366bf8 | Implement Export Binary PSBT | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/WalletExplorer/TransactionViewerViewModel.cs | WalletWasabi.Gui/Controls/WalletExplorer/TransactionViewerViewModel.cs | using Avalonia;
using Avalonia.Controls;
using NBitcoin;
using ReactiveUI;
using System;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class TransactionViewerViewModel : WalletActionViewModel
{
private CompositeDisposable Disposables { get; set; }
private string _txid;
private string _psbtJsonText;
private string _psbtHexText;
private string _psbtBase64Text;
private byte[] _psbtBytes;
public ReactiveCommand<Unit, Unit> ExportBinaryPsbtCommand { get; set; }
public string TxId
{
get => _txid;
set => this.RaiseAndSetIfChanged(ref _txid, value);
}
public string PsbtJsonText
{
get => _psbtJsonText;
set => this.RaiseAndSetIfChanged(ref _psbtJsonText, value);
}
public string TransactionHexText
{
get => _psbtHexText;
set => this.RaiseAndSetIfChanged(ref _psbtHexText, value);
}
public string PsbtBase64Text
{
get => _psbtBase64Text;
set => this.RaiseAndSetIfChanged(ref _psbtBase64Text, value);
}
public byte[] PsbtBytes
{
get => _psbtBytes;
set => this.RaiseAndSetIfChanged(ref _psbtBytes, value);
}
public TransactionViewerViewModel(WalletViewModel walletViewModel) : base("Transaction", walletViewModel)
{
ExportBinaryPsbtCommand = ReactiveCommand.CreateFromTask(async () =>
{
try
{
var sfd = new SaveFileDialog();
sfd.DefaultExtension = "psbt";
sfd.InitialFileName = TxId;
string file = await sfd.ShowAsync(Application.Current.MainWindow);
if (!string.IsNullOrWhiteSpace(file))
{
await File.WriteAllBytesAsync(file, PsbtBytes);
}
}
catch (Exception ex)
{
SetWarningMessage(ex.ToTypeMessageString());
Logging.Logger.LogError<TransactionViewerViewModel>(ex);
}
}, outputScheduler: RxApp.MainThreadScheduler);
}
private void OnException(Exception ex)
{
SetWarningMessage(ex.ToTypeMessageString());
}
public override void OnOpen()
{
if (Disposables != null)
{
throw new Exception("Transaction Viewer was opened before it was closed.");
}
Disposables = new CompositeDisposable();
base.OnOpen();
}
public override bool OnClose()
{
Disposables?.Dispose();
Disposables = null;
return base.OnClose();
}
public void Update(BuildTransactionResult result)
{
try
{
TxId = result.Transaction.GetHash().ToString();
PsbtJsonText = result.Psbt.ToString();
TransactionHexText = result.Transaction.Transaction.ToHex();
PsbtBase64Text = result.Psbt.ToBase64();
PsbtBytes = result.Psbt.ToBytes();
}
catch (Exception ex)
{
OnException(ex);
}
}
}
}
| using Avalonia;
using NBitcoin;
using ReactiveUI;
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class TransactionViewerViewModel : WalletActionViewModel
{
private string _psbtJsonText;
private string _psbtHexText;
private string _psbtBase64Text;
private CompositeDisposable Disposables { get; set; }
public string PsbtJsonText
{
get => _psbtJsonText;
set => this.RaiseAndSetIfChanged(ref _psbtJsonText, value);
}
public string TransactionHexText
{
get => _psbtHexText;
set => this.RaiseAndSetIfChanged(ref _psbtHexText, value);
}
public string PsbtBase64Text
{
get => _psbtBase64Text;
set => this.RaiseAndSetIfChanged(ref _psbtBase64Text, value);
}
public TransactionViewerViewModel(WalletViewModel walletViewModel) : base("Transaction", walletViewModel)
{
}
private void OnException(Exception ex)
{
SetWarningMessage(ex.ToTypeMessageString());
}
public override void OnOpen()
{
if (Disposables != null)
{
throw new Exception("Transaction Viewer was opened before it was closed.");
}
Disposables = new CompositeDisposable();
base.OnOpen();
}
public override bool OnClose()
{
Disposables?.Dispose();
Disposables = null;
return base.OnClose();
}
public void Update(BuildTransactionResult result)
{
try
{
PsbtJsonText = result.Psbt.ToString();
TransactionHexText = result.Transaction.Transaction.ToHex();
PsbtBase64Text = result.Psbt.ToBase64();
}
catch (Exception ex)
{
OnException(ex);
}
}
}
}
| mit | C# |
3aa5d68e2e9a70766aefc746a2566d0766a03b58 | fix Thickness.IsDefault. Bottom was ignored (#200) | Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms | Xamarin.Forms.Core/Thickness.cs | Xamarin.Forms.Core/Thickness.cs | using System.Diagnostics;
namespace Xamarin.Forms
{
[DebuggerDisplay("Left={Left}, Top={Top}, Right={Right}, Bottom={Bottom}, HorizontalThickness={HorizontalThickness}, VerticalThickness={VerticalThickness}")]
[TypeConverter(typeof(ThicknessTypeConverter))]
public struct Thickness
{
public double Left { get; set; }
public double Top { get; set; }
public double Right { get; set; }
public double Bottom { get; set; }
public double HorizontalThickness
{
get { return Left + Right; }
}
public double VerticalThickness
{
get { return Top + Bottom; }
}
internal bool IsDefault
{
get { return Left == 0 && Top == 0 && Right == 0 && Bottom == 0; }
}
public Thickness(double uniformSize) : this(uniformSize, uniformSize, uniformSize, uniformSize)
{
}
public Thickness(double horizontalSize, double verticalSize) : this(horizontalSize, verticalSize, horizontalSize, verticalSize)
{
}
public Thickness(double left, double top, double right, double bottom) : this()
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public static implicit operator Thickness(Size size)
{
return new Thickness(size.Width, size.Height, size.Width, size.Height);
}
public static implicit operator Thickness(double uniformSize)
{
return new Thickness(uniformSize);
}
bool Equals(Thickness other)
{
return Left.Equals(other.Left) && Top.Equals(other.Top) && Right.Equals(other.Right) && Bottom.Equals(other.Bottom);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is Thickness && Equals((Thickness)obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = Left.GetHashCode();
hashCode = (hashCode * 397) ^ Top.GetHashCode();
hashCode = (hashCode * 397) ^ Right.GetHashCode();
hashCode = (hashCode * 397) ^ Bottom.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Thickness left, Thickness right)
{
return left.Equals(right);
}
public static bool operator !=(Thickness left, Thickness right)
{
return !left.Equals(right);
}
}
} | using System.Diagnostics;
namespace Xamarin.Forms
{
[DebuggerDisplay("Left={Left}, Top={Top}, Right={Right}, Bottom={Bottom}, HorizontalThickness={HorizontalThickness}, VerticalThickness={VerticalThickness}")]
[TypeConverter(typeof(ThicknessTypeConverter))]
public struct Thickness
{
public double Left { get; set; }
public double Top { get; set; }
public double Right { get; set; }
public double Bottom { get; set; }
public double HorizontalThickness
{
get { return Left + Right; }
}
public double VerticalThickness
{
get { return Top + Bottom; }
}
internal bool IsDefault
{
get { return Left == 0 && Top == 0 && Right == 0 && Left == 0; }
}
public Thickness(double uniformSize) : this(uniformSize, uniformSize, uniformSize, uniformSize)
{
}
public Thickness(double horizontalSize, double verticalSize) : this(horizontalSize, verticalSize, horizontalSize, verticalSize)
{
}
public Thickness(double left, double top, double right, double bottom) : this()
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public static implicit operator Thickness(Size size)
{
return new Thickness(size.Width, size.Height, size.Width, size.Height);
}
public static implicit operator Thickness(double uniformSize)
{
return new Thickness(uniformSize);
}
bool Equals(Thickness other)
{
return Left.Equals(other.Left) && Top.Equals(other.Top) && Right.Equals(other.Right) && Bottom.Equals(other.Bottom);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is Thickness && Equals((Thickness)obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = Left.GetHashCode();
hashCode = (hashCode * 397) ^ Top.GetHashCode();
hashCode = (hashCode * 397) ^ Right.GetHashCode();
hashCode = (hashCode * 397) ^ Bottom.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Thickness left, Thickness right)
{
return left.Equals(right);
}
public static bool operator !=(Thickness left, Thickness right)
{
return !left.Equals(right);
}
}
} | mit | C# |
1421190d94ebadb72ed44856f346de7f6e72e855 | Throw down some pins for the map of the run. | alt234/simple-run | SimpleRun/Views/History/RunPage.cs | SimpleRun/Views/History/RunPage.cs | using System;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
//using Xamarin.Geolocation;
using SimpleRun.Models;
namespace SimpleRun
{
public class RunPage : ContentPage
{
Run run;
Label distanceLabel;
Label averagePaceLabel;
Label durationLabel;
Map map;
public string Name { get; private set; }
public RunPage(Run _run)
{
run = _run;
Title = run.RunDate.ToShortDateString();
var font = Font.SystemFontOfSize(20);
distanceLabel = new Label {
Text = string.Format("Distance: {0} km", run.DistanceInKm.ToString("F")),
Font = font,
};
averagePaceLabel = new Label {
Text = string.Format("Average Pace: {0} per km", run.FriendlyPaceInKm),
Font = font,
};
durationLabel = new Label {
Text = string.Format("Duration: {0}", run.FriendlyDuration),
Font = font,
};
map = new Map();
var lastPosition = new Position(37.79762, -122.40181);
foreach (var pos in run.Positions) {
Position position = new Position(pos.Latitude, pos.Longitude);
map.Pins.Add(new Pin {
Label = string.Format("{0} - {1} per km", pos.PositionCaptureTime, pos.Speed),
Position = position
});
lastPosition = position;
}
map.MoveToRegion(new MapSpan(lastPosition, 0.01, 0.01));
Content = new StackLayout {
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand,
Children = {
new StackLayout {
VerticalOptions = LayoutOptions.Start,
Padding = new Thickness(10),
Children = {
durationLabel,
distanceLabel,
averagePaceLabel,
}
},
map,
}
};
}
}
}
| using System;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using SimpleRun.Models;
namespace SimpleRun
{
public class RunPage : ContentPage
{
Run run;
Label distanceLabel;
Label averagePaceLabel;
Label durationLabel;
Map map;
public string Name { get; private set; }
public RunPage(Run _run)
{
run = _run;
Title = run.RunDate.ToShortDateString();
var font = Font.SystemFontOfSize(20);
distanceLabel = new Label {
Text = string.Format("Distance: {0} km", run.DistanceInKm.ToString("F")),
Font = font,
};
averagePaceLabel = new Label {
Text = string.Format("Average Pace: {0} per km", run.FriendlyPaceInKm),
Font = font,
};
durationLabel = new Label {
Text = string.Format("Duration: {0}", run.FriendlyDuration),
Font = font,
};
map = new Map();
Position position = new Position(37.79762, -122.40181);
map.MoveToRegion(new MapSpan(position, 0.01, 0.01));
map.Pins.Add(new Pin {
Label = "Xamarin",
Position = position
});
Content = new StackLayout {
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand,
Children = {
new StackLayout {
VerticalOptions = LayoutOptions.Start,
Padding = new Thickness(10),
Children = {
durationLabel,
distanceLabel,
averagePaceLabel,
}
},
map,
}
};
}
}
}
| mit | C# |
5e75aa2192f065763ef65135d1a1f91dff28be38 | Update logic for Ninject binding | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/IoC_Example_Installers/NinjectBinder.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/IoC_Example_Installers/NinjectBinder.cs | using System;
using System.Data;
using Ninject;
using Ninject.Extensions.Factory;
using Ninject.Syntax;
using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.IoC_Example_Installers
{
public class NinjectBinder
{
public void Bind(IKernel kernel)
{
kernel.Bind<INinjectDbFactory>().ToFactory(() => new TypeMatchingArgumentInheritanceInstanceProvider());
kernel.Rebind<IDbFactory>().To<DbFactory>().InSingletonScope();
kernel.Bind<IUnitOfWork>().To<Dapper.Repository.UnitOfWork.Data.UnitOfWork>()
.WithConstructorArgument(typeof(IDbFactory))
.WithConstructorArgument(typeof(ISession))
.WithConstructorArgument(typeof(IsolationLevel));
}
[NoIoCFluentRegistration]
internal sealed class DbFactory : IDbFactory
{
private readonly IResolutionRoot _resolutionRoot;
private readonly INinjectDbFactory _factory;
public DbFactory(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
_factory = resolutionRoot.Get<INinjectDbFactory>();
}
public T Create<T>() where T : class, ISession
{
return _factory.Create<T>();
}
public T CreateSession<T>() where T : class, ISession
{
return _factory.Create<T>();
}
public T Create<T>(IDbFactory factory, ISession session) where T : class, IUnitOfWork
{
return _factory.CreateUnitOwWork<T>(factory, session);
}
public T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel)
where T : class, IUnitOfWork
{
return _factory.CreateUnitOwWork<T>(factory, session);
}
public void Release(IDisposable instance)
{
_resolutionRoot.Release(instance);
}
}
}
}
| using System;
using System.Data;
using Ninject;
using Ninject.Extensions.Factory;
using Ninject.Syntax;
using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.IoC_Example_Installers
{
public class NinjectBinder
{
public void Bind(IKernel kernel)
{
kernel.Bind<INinjectDbFactory>().ToFactory(() => new TypeMatchingArgumentInheritanceInstanceProvider());
kernel.Rebind<IDbFactory>().To<DbFactory>().InSingletonScope();
kernel.Bind<IUnitOfWork>().To<Dapper.Repository.UnitOfWork.Data.UnitOfWork>()
.WithConstructorArgument(typeof(IDbFactory))
.WithConstructorArgument(typeof(ISession))
.WithConstructorArgument(typeof(IsolationLevel));
}
}
[NoIoCFluentRegistration]
internal class DbFactory : IDbFactory
{
private readonly IResolutionRoot _resolutionRoot;
private readonly INinjectDbFactory _factory;
public DbFactory(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
_factory= resolutionRoot.Get<INinjectDbFactory>();
}
public T Create<T>() where T : class, ISession
{
return _factory.Create<T>();
}
public T CreateSession<T>() where T : class, ISession
{
return _factory.Create<T>();
}
public T Create<T>(IDbFactory factory, ISession session) where T : class, IUnitOfWork
{
return _factory.CreateUnitOwWork<T>(factory, session);
}
public T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel) where T : class, IUnitOfWork
{
return _factory.CreateUnitOwWork<T>(factory, session);
}
public void Release(IDisposable instance)
{
_resolutionRoot.Release(instance);
}
}
}
| mit | C# |
aed7de07aba67ba84714fb488a545032fb2a51f9 | remove enabled | charlesgriffiths/VoxelPerformance | Assets/VoxelPerformance/Scripts/MapDisplay.cs | Assets/VoxelPerformance/Scripts/MapDisplay.cs | using UnityEngine;
using System.Collections;
// VoxelPerformance/Scripts/MapDisplay.cs
// Copyright 2016 Charles Griffiths
namespace VoxelPerformance
{
// This class is used to display one chunk produced by compute shaders in VoxelPerformance/Shaders
// using a geometry shader found in VoxelPerformance/Shaders/VoxelGeometry.shader
public class MapDisplay : MonoBehaviour
{
Color[] color;
Texture2D sprite;
ComputeBuffer display;
Material material;
public float size { get; private set; }
public Bounds bounds { get; private set; }
public void initialize( Shader geometryShader, Color[] color, float size, Texture2D sprite, ComputeBuffer display )
{
this.color = color;
this.size = size;
this.sprite = sprite;
this.display = display;
material = new Material( geometryShader );
bounds = new Bounds( transform.position + new Vector3( 128, 128, 128 )*size, new Vector3( 256, 256, 256 )*size);
enabled = true;
}
public void releaseDisplayBuffers()
{
display.Release();
}
public bool isVisible()
{
return enabled
&& bounds.SqrDistance( MapGen.mainCamera.transform.position ) < 1.2f * MapGen.mainCamera.farClipPlane * MapGen.mainCamera.farClipPlane
&& GeometryUtility.TestPlanesAABB( MapGen.cameraPlanes, bounds );
}
void OnRenderObject()
{
if (isVisible())
{
//// Shader.globalMaximumLOD = 100;
//// material.shader.maximumLOD = 100;
material.SetPass( 0 );
material.SetColor( "_Color", color[0] );
material.SetColor( "_Color1", color[1] );
material.SetColor( "_Color2", color[2] );
material.SetColor( "_Color3", color[3] );
material.SetColor( "_Color4", color[4] );
material.SetColor( "_Color5", color[5] );
material.SetColor( "_Color6", color[6] );
material.SetVector( "_cameraPosition", MapGen.mainCamera.transform.position );
material.SetVector( "_chunkPosition", transform.position );
material.SetTexture( "_Sprite", sprite );
material.SetFloat( "_Size", size );
material.SetMatrix( "_worldMatrixTransform", transform.localToWorldMatrix );
material.SetBuffer( "_displayPoints", display );
Graphics.DrawProcedural( MeshTopology.Points, display.count );
}
}
}
}
| using UnityEngine;
using System.Collections;
// VoxelPerformance/Scripts/MapDisplay.cs
// Copyright 2016 Charles Griffiths
namespace VoxelPerformance
{
// This class is used to display one chunk produced by compute shaders in VoxelPerformance/Shaders
// using a geometry shader found in VoxelPerformance/Shaders/VoxelGeometry.shader
public class MapDisplay : MonoBehaviour
{
Color[] color;
Texture2D sprite;
ComputeBuffer display;
Material material;
public float size { get; private set; }
public Bounds bounds { get; private set; }
public bool enabled { get; set; }
public void initialize( Shader geometryShader, Color[] color, float size, Texture2D sprite, ComputeBuffer display )
{
this.color = color;
this.size = size;
this.sprite = sprite;
this.display = display;
material = new Material( geometryShader );
bounds = new Bounds( transform.position + new Vector3( 128, 128, 128 )*size, new Vector3( 256, 256, 256 )*size);
enabled = true;
}
public void releaseDisplayBuffers()
{
display.Release();
}
public bool isVisible()
{
return enabled
&& bounds.SqrDistance( MapGen.mainCamera.transform.position ) < 1.2f * MapGen.mainCamera.farClipPlane * MapGen.mainCamera.farClipPlane
&& GeometryUtility.TestPlanesAABB( MapGen.cameraPlanes, bounds );
}
void OnRenderObject()
{
if (isVisible())
{
//// Shader.globalMaximumLOD = 100;
//// material.shader.maximumLOD = 100;
material.SetPass( 0 );
material.SetColor( "_Color", color[0] );
material.SetColor( "_Color1", color[1] );
material.SetColor( "_Color2", color[2] );
material.SetColor( "_Color3", color[3] );
material.SetColor( "_Color4", color[4] );
material.SetColor( "_Color5", color[5] );
material.SetColor( "_Color6", color[6] );
material.SetVector( "_cameraPosition", MapGen.mainCamera.transform.position );
material.SetVector( "_chunkPosition", transform.position );
material.SetTexture( "_Sprite", sprite );
material.SetFloat( "_Size", size );
material.SetMatrix( "_worldMatrixTransform", transform.localToWorldMatrix );
material.SetBuffer( "_displayPoints", display );
Graphics.DrawProcedural( MeshTopology.Points, display.count );
}
}
}
}
| apache-2.0 | C# |
d50784ed99dc47de780e352705acdb623a239538 | Improve code | sakapon/Samples-2016,sakapon/Samples-2016 | CognitiveSample/ComputerVisionWpf/AppModel.cs | CognitiveSample/ComputerVisionWpf/AppModel.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using Reactive.Bindings;
namespace ComputerVisionWpf
{
public class AppModel
{
static string SubscriptionKey { get; } = ConfigurationManager.AppSettings["SubscriptionKey"];
VisionServiceClient Client { get; } = new VisionServiceClient(SubscriptionKey);
const string DefaultImageUrl= "https://model.foto.ne.jp/free/img/images_big/m010078.jpg";
public ReactiveProperty<string> ImageUrl { get; } = new ReactiveProperty<string>(DefaultImageUrl);
public ReactiveProperty<AnalysisResult> Result { get; } = new ReactiveProperty<AnalysisResult>();
public async void Analyze()
{
if (string.IsNullOrWhiteSpace(ImageUrl.Value)) return;
Result.Value = await Client.AnalyzeImageAsync(ImageUrl.Value, (VisualFeature[])Enum.GetValues(typeof(VisualFeature)));
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using Reactive.Bindings;
namespace ComputerVisionWpf
{
public class AppModel
{
static readonly string SubscriptionKey = ConfigurationManager.AppSettings["SubscriptionKey"];
VisionServiceClient Client { get; } = new VisionServiceClient(SubscriptionKey);
public ReactiveProperty<string> ImageUrl { get; } = new ReactiveProperty<string>("");
public ReactiveProperty<AnalysisResult> Result { get; } = new ReactiveProperty<AnalysisResult>();
public async void Analyze()
{
if (string.IsNullOrWhiteSpace(ImageUrl.Value)) return;
Result.Value = await Client.AnalyzeImageAsync(ImageUrl.Value, (VisualFeature[])Enum.GetValues(typeof(VisualFeature)));
}
}
}
| mit | C# |
4beb86f674c3f90392dea27c922383c6d7784f3b | Allow double click to open on junctions when lacking a destination | NickLargen/Junctionizer | Junctionizer/UI/Styles/DataGridStyles.xaml.cs | Junctionizer/UI/Styles/DataGridStyles.xaml.cs | using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Input;
using Junctionizer.Model;
namespace Junctionizer.UI.Styles
{
public partial class DataGridStyles
{
private void DataGridRow_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left) return;
var dataGridRow = sender as DataGridRow;
if (dataGridRow?.Item is GameFolder folder)
{
OpenInFileExplorer(folder);
}
else if (dataGridRow?.Item is GameFolderPair pair)
{
if (pair.DestinationEntry == null || pair.SourceEntry?.IsJunction == false) OpenInFileExplorer(pair.SourceEntry);
if (pair.DestinationEntry != null) OpenInFileExplorer(pair.DestinationEntry);
}
}
private static void OpenInFileExplorer(GameFolder folder)
{
var path = folder.DirectoryInfo.FullName;
ErrorHandling.ThrowIfDirectoryNotFound(path);
Process.Start(path);
}
}
}
| using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Input;
using Junctionizer.Model;
namespace Junctionizer.UI.Styles
{
public partial class DataGridStyles
{
private void DataGridRow_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left) return;
var dataGridRow = sender as DataGridRow;
if (dataGridRow?.Item is GameFolder folder)
{
OpenInFileExplorer(folder);
}
else if (dataGridRow?.Item is GameFolderPair pair)
{
if (pair.SourceEntry?.IsJunction == false) OpenInFileExplorer(pair.SourceEntry);
if (pair.DestinationEntry?.IsJunction == false) OpenInFileExplorer(pair.DestinationEntry);
}
}
private static void OpenInFileExplorer(GameFolder folder)
{
var path = folder.DirectoryInfo.FullName;
ErrorHandling.ThrowIfDirectoryNotFound(path);
Process.Start(path);
}
}
}
| mit | C# |
08c7b70497a55a59541019df1d10305fc63f7ca8 | allow TranslateSize and Point to be overriden. | AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex | src/Avalonia.Controls/Primitives/PopupPositioning/ManagedPopupPositionerPopupImplHelper.cs | src/Avalonia.Controls/Primitives/PopupPositioning/ManagedPopupPositionerPopupImplHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Platform;
namespace Avalonia.Controls.Primitives.PopupPositioning
{
/// <summary>
/// This class is used to simplify integration of IPopupImpl implementations with popup positioner
/// </summary>
public class ManagedPopupPositionerPopupImplHelper : IManagedPopupPositionerPopup
{
private readonly IWindowBaseImpl _parent;
public delegate void MoveResizeDelegate(PixelPoint position, Size size, double scaling);
private readonly MoveResizeDelegate _moveResize;
public ManagedPopupPositionerPopupImplHelper(IWindowBaseImpl parent, MoveResizeDelegate moveResize)
{
_parent = parent;
_moveResize = moveResize;
}
public IReadOnlyList<ManagedPopupPositionerScreenInfo> Screens =>
_parent.Screen.AllScreens.Select(s => new ManagedPopupPositionerScreenInfo(
s.Bounds.ToRect(1), s.WorkingArea.ToRect(1))).ToList();
public Rect ParentClientAreaScreenGeometry
{
get
{
// Popup positioner operates with abstract coordinates, but in our case they are pixel ones
var point = _parent.PointToScreen(default);
var size = PixelSize.FromSize(_parent.ClientSize, _parent.Scaling);
return new Rect(point.X, point.Y, size.Width, size.Height);
}
}
public void MoveAndResize(Point devicePoint, Size virtualSize)
{
_moveResize(new PixelPoint((int)devicePoint.X, (int)devicePoint.Y), virtualSize, _parent.Scaling);
}
public virtual Point TranslatePoint(Point pt) => pt * _parent.Scaling;
public virtual Size TranslateSize(Size size) => size * _parent.Scaling;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Platform;
namespace Avalonia.Controls.Primitives.PopupPositioning
{
/// <summary>
/// This class is used to simplify integration of IPopupImpl implementations with popup positioner
/// </summary>
public class ManagedPopupPositionerPopupImplHelper : IManagedPopupPositionerPopup
{
private readonly IWindowBaseImpl _parent;
public delegate void MoveResizeDelegate(PixelPoint position, Size size, double scaling);
private readonly MoveResizeDelegate _moveResize;
public ManagedPopupPositionerPopupImplHelper(IWindowBaseImpl parent, MoveResizeDelegate moveResize)
{
_parent = parent;
_moveResize = moveResize;
}
public IReadOnlyList<ManagedPopupPositionerScreenInfo> Screens =>
_parent.Screen.AllScreens.Select(s => new ManagedPopupPositionerScreenInfo(
s.Bounds.ToRect(1), s.WorkingArea.ToRect(1))).ToList();
public Rect ParentClientAreaScreenGeometry
{
get
{
// Popup positioner operates with abstract coordinates, but in our case they are pixel ones
var point = _parent.PointToScreen(default);
var size = PixelSize.FromSize(_parent.ClientSize, _parent.Scaling);
return new Rect(point.X, point.Y, size.Width, size.Height);
}
}
public void MoveAndResize(Point devicePoint, Size virtualSize)
{
_moveResize(new PixelPoint((int)devicePoint.X, (int)devicePoint.Y), virtualSize, _parent.Scaling);
}
public Point TranslatePoint(Point pt) => pt * _parent.Scaling;
public Size TranslateSize(Size size) => size * _parent.Scaling;
}
}
| mit | C# |
653b918f8b453040d339f14fcbd9daf851b1670f | Change version number | DaveSenn/Extend | PortableExtensions/Properties/AssemblyInfo.cs | PortableExtensions/Properties/AssemblyInfo.cs | #region Usings
using System.Reflection;
using System.Resources;
#endregion
// General Information about an assembly is controlled through the following set of attributes. Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle( "PortableExtensions" )]
[assembly: AssemblyDescription( "A set of .Net extension methods build as portable class library" )]
#if DEBUG
[assembly: AssemblyConfiguration( "Debug" )]
#else
[assembly: AssemblyConfiguration ( "Release" )]
#endif
[assembly: AssemblyCompany( "Dave Senn" )]
[assembly: AssemblyProduct( "PortableExtensions" )]
[assembly: AssemblyCopyright("Copyright © Dave Senn 2015")]
[assembly: AssemblyTrademark( "PortableExtensions" )]
[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.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")] | #region Usings
using System.Reflection;
using System.Resources;
#endregion
// General Information about an assembly is controlled through the following set of attributes. Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle( "PortableExtensions" )]
[assembly: AssemblyDescription( "A set of .Net extension methods build as portable class library" )]
#if DEBUG
[assembly: AssemblyConfiguration( "Debug" )]
#else
[assembly: AssemblyConfiguration ( "Release" )]
#endif
[assembly: AssemblyCompany( "Dave Senn" )]
[assembly: AssemblyProduct( "PortableExtensions" )]
[assembly: AssemblyCopyright( "Copyright © Dave Senn 2014" )]
[assembly: AssemblyTrademark( "PortableExtensions" )]
[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.19.0" )]
[assembly: AssemblyFileVersion( "1.0.19.0" )] | mit | C# |
6423521fef59286636553e10a8e03198c28e1110 | Add legacy API support | red-gate/RedGate.AppHost,nycdotnet/RedGate.AppHost | RedGate.AppHost.Server/ChildProcessFactory.cs | RedGate.AppHost.Server/ChildProcessFactory.cs | namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, false, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
| namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit = false, bool monitorHostProcess = false)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
// Legacy version of the api
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
| apache-2.0 | C# |
73e58124b83bd0b8b0d22496f695a458c18ebf9e | Revert "Track child metrics" | hinteadan/Metrics.NET.GAReporting | Metrics.Reporters.GoogleAnalytics/Metrics.Reporters.GoogleAnalytics/GoogleAnalyticsReport.cs | Metrics.Reporters.GoogleAnalytics/Metrics.Reporters.GoogleAnalytics/GoogleAnalyticsReport.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Metrics.MetricData;
using Metrics.Reporters.GoogleAnalytics.Tracker;
using Metrics.Reporters.GoogleAnalytics.Mappers;
namespace Metrics.Reporters.GoogleAnalytics
{
public class GoogleAnalyticsReport : MetricsReport
{
private readonly GoogleAnalyticsTracker tracker;
public GoogleAnalyticsReport(string trackingId, string clientId)
{
this.tracker = new GoogleAnalyticsTracker(trackingId, clientId);
}
public void RunReport(MetricsData metricsData, Func<HealthStatus> healthStatus, CancellationToken token)
{
tracker.Track(metricsData.AsGoogleAnalytics(), token).Wait(token);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Metrics.MetricData;
using Metrics.Reporters.GoogleAnalytics.Tracker;
using Metrics.Reporters.GoogleAnalytics.Mappers;
namespace Metrics.Reporters.GoogleAnalytics
{
public class GoogleAnalyticsReport : MetricsReport
{
private readonly GoogleAnalyticsTracker tracker;
public GoogleAnalyticsReport(string trackingId, string clientId)
{
this.tracker = new GoogleAnalyticsTracker(trackingId, clientId);
}
public void RunReport(MetricsData metricsData, Func<HealthStatus> healthStatus, CancellationToken token)
{
var allMetrics = new MetricsData[] { metricsData }.Concat(metricsData.ChildMetrics);
Task.WaitAll(allMetrics.Select(m => tracker.Track(metricsData.AsGoogleAnalytics(), token)).ToArray(), token);
}
}
}
| apache-2.0 | C# |
54bae40f921a4433c5c7caf94ab78e0f7c3f2672 | Change caption of Tool Window | xoriath/atmelstudio-fstack-usage | StackUsageAnalyzer/StackAnalysisToolWindow.cs | StackUsageAnalyzer/StackAnalysisToolWindow.cs | //------------------------------------------------------------------------------
// <copyright file="StackAnalysisToolWindow.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace StackUsageAnalyzer
{
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
/// <summary>
/// This class implements the tool window exposed by this package and hosts a user control.
/// </summary>
/// <remarks>
/// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane,
/// usually implemented by the package implementer.
/// <para>
/// This class derives from the ToolWindowPane class provided from the MPF in order to use its
/// implementation of the IVsUIElementPane interface.
/// </para>
/// </remarks>
[Guid("ffbd67c0-1100-4fa5-8c20-cc10264c540b")]
public class StackAnalysisToolWindow : ToolWindowPane
{
/// <summary>
/// Initializes a new instance of the <see cref="StackAnalysisToolWindow"/> class.
/// </summary>
public StackAnalysisToolWindow() : base(null)
{
this.Caption = "Function Stack Analysis";
// This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
// we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
// the object returned by the Content property.
this.Content = new StackAnalysisToolWindowControl();
}
}
}
| //------------------------------------------------------------------------------
// <copyright file="StackAnalysisToolWindow.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace StackUsageAnalyzer
{
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
/// <summary>
/// This class implements the tool window exposed by this package and hosts a user control.
/// </summary>
/// <remarks>
/// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane,
/// usually implemented by the package implementer.
/// <para>
/// This class derives from the ToolWindowPane class provided from the MPF in order to use its
/// implementation of the IVsUIElementPane interface.
/// </para>
/// </remarks>
[Guid("ffbd67c0-1100-4fa5-8c20-cc10264c540b")]
public class StackAnalysisToolWindow : ToolWindowPane
{
/// <summary>
/// Initializes a new instance of the <see cref="StackAnalysisToolWindow"/> class.
/// </summary>
public StackAnalysisToolWindow() : base(null)
{
this.Caption = "StackAnalysisToolWindow";
// This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
// we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
// the object returned by the Content property.
this.Content = new StackAnalysisToolWindowControl();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.