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 |
|---|---|---|---|---|---|---|---|---|
e306b01895369d35102ab47ad0ea24ccf3def80c | Change so that the minimum hash length is 6 characters and not 10 | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Services/HashingService.cs | src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Services/HashingService.cs | using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces;
using HashidsNet;
namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services
{
public class HashingService : IHashingService
{
public string HashValue(long id)
{
var hashIds = new Hashids("SFA: digital apprenticeship service",6, "46789BCDFGHJKLMNPRSTVWXY");
return hashIds.EncodeLong(id);
}
}
}
| using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces;
using HashidsNet;
namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services
{
public class HashingService : IHashingService
{
public string HashValue(long id)
{
var hashIds = new Hashids("SFA: digital apprenticeship service",10, "46789BCDFGHJKLMNPRSTVWXY");
return hashIds.EncodeLong(id);
}
}
}
| mit | C# |
fe74354e285d981d7fc747f9ace7cdf0b76d17aa | make the bitmap a field for reference passing | Willster419/RelicModManager,Willster419/RelhaxModpack,Willster419/RelhaxModpack | RelhaxModpack/RelhaxModpack/Atlases/Texture.cs | RelhaxModpack/RelhaxModpack/Atlases/Texture.cs | using RelhaxModpack.Database;
using System.Drawing;
namespace RelhaxModpack
{
/// <summary>
/// A Texture is a piece of an atlas file. Contains image data such as the position, size, and bitmap itself.
/// </summary>
public class Texture : IXmlSerializable
{
#region Xml Serialization
public string[] PropertiesForSerializationAttributes()
{
return null;
}
public string[] PropertiesForSerializationElements()
{
return new string[]
{
nameof(Name),
nameof(X),
nameof(Y),
nameof(Width),
nameof(Height)
};
}
#endregion
/// <summary>
/// The file name of where this texture came from
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public string Name { get; set; }
/// <summary>
/// The x position of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int X { get; set; }
/// <summary>
/// The y position of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int Y { get; set; }
/// <summary>
/// The width of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int Width { get; set; }
/// <summary>
/// The height of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int Height { get; set; }
/// <summary>
/// The actual bitmap in memory of the image
/// </summary>
/// <remarks>This is *not* loaded from the xml file and is used internally</remarks>
public Bitmap AtlasImage = null;
}
}
| using RelhaxModpack.Database;
using System.Drawing;
namespace RelhaxModpack
{
/// <summary>
/// A Texture is a piece of an atlas file. Contains image data such as the position, size, and bitmap itself.
/// </summary>
public class Texture : IXmlSerializable
{
#region Xml Serialization
public string[] PropertiesForSerializationAttributes()
{
return null;
}
public string[] PropertiesForSerializationElements()
{
return new string[]
{
nameof(Name),
nameof(X),
nameof(Y),
nameof(Width),
nameof(Height)
};
}
#endregion
/// <summary>
/// The file name of where this texture came from
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public string Name { get; set; }
/// <summary>
/// The x position of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int X { get; set; }
/// <summary>
/// The y position of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int Y { get; set; }
/// <summary>
/// The width of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int Width { get; set; }
/// <summary>
/// The height of the texture in the atlas image
/// </summary>
/// <remarks>This is loaded from the xml file</remarks>
public int Height { get; set; }
/// <summary>
/// The actual bitmap in memory of the image
/// </summary>
/// <remarks>This is *not* loaded from the xml file and is used internally</remarks>
public Bitmap AtlasImage { get; set; }
}
}
| apache-2.0 | C# |
f37d41f06cfacef547dcd6190a228347e896e873 | Add DefaultCommandTimeout on OrmConnectionFactory | SimpleStack/simplestack.orm,SimpleStack/simplestack.orm | src/SimpleStack.Orm/OrmConnectionFactory.cs | src/SimpleStack.Orm/OrmConnectionFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleStack.Orm
{
public class OrmConnectionFactory
{
private readonly IDialectProvider _dialectProvider;
private readonly string _connectionString;
public OrmConnectionFactory(IDialectProvider dialectProvider, string connectionString)
{
_dialectProvider = dialectProvider;
_connectionString = connectionString;
}
/// <summary>
/// Default command timeout (in seconds) set on OrmConnections created from the Factory
/// </summary>
public int DefaultCommandTimeout { get; set; }
public IDialectProvider DialectProvider => _dialectProvider;
public OrmConnection OpenConnection()
{
var conn = _dialectProvider.CreateConnection(_connectionString);
conn.CommandTimeout = DefaultCommandTimeout;
conn.Open();
return conn;
}
public async Task<OrmConnection> OpenConnectionAsync()
{
var conn = _dialectProvider.CreateConnection(_connectionString);
conn.CommandTimeout = DefaultCommandTimeout;
await conn.OpenAsync();
return conn;
}
public override string ToString()
{
return _dialectProvider.GetType().ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleStack.Orm
{
public class OrmConnectionFactory
{
private readonly IDialectProvider _dialectProvider;
private readonly string _connectionString;
public OrmConnectionFactory(IDialectProvider dialectProvider, string connectionString)
{
_dialectProvider = dialectProvider;
_connectionString = connectionString;
}
public IDialectProvider DialectProvider => _dialectProvider;
public OrmConnection OpenConnection()
{
var conn = _dialectProvider.CreateConnection(_connectionString);
conn.Open();
return conn;
}
public async Task<OrmConnection> OpenConnectionAsync()
{
var conn = _dialectProvider.CreateConnection(_connectionString);
await conn.OpenAsync();
return conn;
}
public override string ToString()
{
return _dialectProvider.GetType().ToString();
}
}
}
| bsd-3-clause | C# |
45b9de742b4ebabab44688d9ef3cd2bd230bd4b6 | update signin namespaces | CatalystCode/TerrainFlow-Web,CatalystCode/TerrainFlow-Web,CatalystCode/TerrainFlow-Web | src/TerrainFlow/Views/Account/Signin.cshtml | src/TerrainFlow/Views/Account/Signin.cshtml | @using System.Collections.Generic
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Authentication
@{
ViewData["Title"] = "Log in";
}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Login using...</h3>
</div>
<div class="panel-body signin">
<section>
<p>You can sign in using any of the providers below. We don't save any data or access your accounts - we merely need to confirm your email address.</p>
</section>
<section>
<form action="/signin" method="post">
<input type="hidden" name="Provider" value="Microsoft"/>
<input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl"/>
<button type="submit" class="btn btn-default btn-raised" name="provider" type="submit">Microsoft</button>
</form>
<form action="/signin" method="post">
<input type="hidden" name="Provider" value="Google"/>
<input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl"/>
<button type="submit" class="btn btn-default btn-raised" name="provider" type="submit">Google</button>
</form>
<form action="/signin" method="post">
<input type="hidden" name="Provider" value="Facebook" />
<input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl" />
<button type="submit" class="btn btn-default btn-raised" name="provider" type="submit">Facebook</button>
</form>
</section>
</div>
</div> | @using System.Collections.Generic
@using Microsoft.AspNet.Http
@using Microsoft.AspNet.Http.Authentication
@{
ViewData["Title"] = "Log in";
}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Login using...</h3>
</div>
<div class="panel-body signin">
<section>
<p>You can sign in using any of the providers below. We don't save any data or access your accounts - we merely need to confirm your email address.</p>
</section>
<section>
<form action="/signin" method="post">
<input type="hidden" name="Provider" value="Microsoft"/>
<input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl"/>
<button type="submit" class="btn btn-default btn-raised" name="provider" type="submit">Microsoft</button>
</form>
<form action="/signin" method="post">
<input type="hidden" name="Provider" value="Google"/>
<input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl"/>
<button type="submit" class="btn btn-default btn-raised" name="provider" type="submit">Google</button>
</form>
<form action="/signin" method="post">
<input type="hidden" name="Provider" value="Facebook" />
<input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl" />
<button type="submit" class="btn btn-default btn-raised" name="provider" type="submit">Facebook</button>
</form>
</section>
</div>
</div> | mit | C# |
c1c8054d93777fd1e805d5f159e92df6014442b3 | add more unit tests for CarAdvertMapperTest | mdavid626/artemis | src/Artemis.Web.Tests/CarAdvertMapperTest.cs | src/Artemis.Web.Tests/CarAdvertMapperTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Artemis.Common;
using Artemis.Web.Models;
namespace Artemis.Web.Tests
{
[TestClass]
public class CarAdvertMapperTest
{
[TestMethod]
public void TestValidMapping()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.Fuel = "gasoline";
vm.New = true;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsTrue(result);
}
[TestMethod]
public void TestMissingFuel()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.New = true;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsFalse(result);
}
[TestMethod]
public void TestInvalidFuel()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.Fuel = "adsfdasf";
vm.New = true;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsFalse(result);
}
[TestMethod]
public void TestUsedCar()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.Fuel = "diesel";
vm.New = false;
vm.Mileage = 5000;
vm.FirstRegistration = DateTime.Now;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsTrue(result);
}
[TestMethod]
public void TestInvalidUsedCar()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.Fuel = "diesel";
vm.New = true;
vm.Mileage = 5000;
vm.FirstRegistration = DateTime.Now;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsFalse(result);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Artemis.Common;
using Artemis.Web.Models;
namespace Artemis.Web.Tests
{
[TestClass]
public class CarAdvertMapperTest
{
[TestMethod]
public void TestValidMapping()
{
var vm = new CarAdvertViewModel();
vm.Id = 1;
vm.Title = "Audi";
vm.Price = 5000;
vm.Fuel = "gasoline";
vm.New = false;
var carAdvert = new CarAdvert();
var result = vm.MapTo(carAdvert);
Assert.IsTrue(result);
}
}
}
| mit | C# |
be2f5a26914c97d1d96dcc3fb4ffc969e49e5c36 | implement fallbackOrSkip for converter errors | Pondidum/Stronk,Pondidum/Stronk | src/Stronk/ConfigBuilder.cs | src/Stronk/ConfigBuilder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Stronk.Policies;
using Stronk.PropertySelection;
using Stronk.SourceValueSelection;
using Stronk.ValueConversion;
namespace Stronk
{
public class ConfigBuilder
{
private readonly IStronkOptions _options;
public ConfigBuilder(IStronkOptions options)
{
_options = options;
}
public void Populate(object target, IConfigurationSource configSource)
{
var valueSelectors = _options.ValueSelectors.ToArray();
var availableConverters = _options.ValueConverters.ToArray();
var properties = _options
.PropertySelectors
.SelectMany(selector => selector.Select(target.GetType()));
var args = new ValueSelectorArgs(configSource);
foreach (var property in properties)
{
var value = GetValueFromSource(valueSelectors, args.With(property));
if (value == null)
if (_options.ErrorPolicy.OnSourceValueNotFound == PolicyActions.ThrowException)
throw new SourceValueNotFoundException(valueSelectors, property);
else
continue;
var converters = GetValueConverters(availableConverters, property);
if (converters.Any() == false)
if (_options.ErrorPolicy.OnConverterNotFound == PolicyActions.ThrowException)
throw new ConverterNotFoundException(availableConverters, property);
else
continue;
ApplyConversion(availableConverters, converters, target, property, value);
}
}
private void ApplyConversion(IValueConverter[] availableConverters, IEnumerable<IValueConverter> chosenConverters, object target, PropertyDescriptor property, string value)
{
var exceptions = new List<Exception>();
foreach (var converter in chosenConverters)
{
var vca = new ValueConverterArgs(
availableConverters.Where(x => x != converter),
property.Type,
value
);
try
{
var converted = converter.Map(vca);
property.Assign(target, converted);
return;
}
catch (Exception ex)
{
if (_options.ErrorPolicy.OnConverterException == ConverterExceptionPolicy.ThrowException)
throw new ValueConversionException("Error converting", new[] { ex });
exceptions.Add(ex);
}
}
}
private static IValueConverter[] GetValueConverters(IValueConverter[] converters, PropertyDescriptor property)
{
return converters
.Where(c => c.CanMap(property.Type))
.ToArray();
}
private static string GetValueFromSource(ISourceValueSelector[] sourceValueSelectors, ValueSelectorArgs args)
{
foreach (var filter in sourceValueSelectors)
{
var value = filter.Select(args);
if (value != null)
return value;
}
return null;
}
}
}
| using System;
using System.Linq;
using Stronk.Policies;
using Stronk.PropertySelection;
using Stronk.SourceValueSelection;
using Stronk.ValueConversion;
namespace Stronk
{
public class ConfigBuilder
{
private readonly IStronkOptions _options;
public ConfigBuilder(IStronkOptions options)
{
_options = options;
}
public void Populate(object target, IConfigurationSource configSource)
{
var valueSelectors = _options.ValueSelectors.ToArray();
var converters = _options.ValueConverters.ToArray();
var properties = _options
.PropertySelectors
.SelectMany(selector => selector.Select(target.GetType()));
var args = new ValueSelectorArgs(configSource);
foreach (var property in properties)
{
var value = GetValueFromSource(valueSelectors, args.With(property));
if (value == null)
if (_options.ErrorPolicy.OnSourceValueNotFound == PolicyActions.ThrowException)
throw new SourceValueNotFoundException(valueSelectors, property);
else
continue;
var converter = GetValueConverter(converters, property);
if (converter == null)
if (_options.ErrorPolicy.OnConverterNotFound == PolicyActions.ThrowException)
throw new ConverterNotFoundException(converters, property);
else
continue;
var vca = new ValueConverterArgs(
converters.Where(x => x != converter),
property.Type,
value
);
object converted;
try
{
converted = converter.Map(vca);
}
catch (Exception ex)
{
if (_options.ErrorPolicy.OnConverterException == ConverterExceptionPolicy.ThrowException)
throw new ValueConversionException("Error converting",new [] { ex });
else
continue;
}
property.Assign(target, converted);
}
}
private static IValueConverter GetValueConverter(IValueConverter[] converters, PropertyDescriptor property)
{
foreach (var valueConverter in converters)
{
if (valueConverter.CanMap(property.Type) == false)
continue;
return valueConverter;
}
return null;
}
private static string GetValueFromSource(ISourceValueSelector[] sourceValueSelectors, ValueSelectorArgs args)
{
foreach (var filter in sourceValueSelectors)
{
var value = filter.Select(args);
if (value != null)
return value;
}
return null;
}
}
}
| lgpl-2.1 | C# |
182fda9d34553989e553b143d3b4b1f6e2d968b3 | Add sample of FileSelector with filters | TheBrainTech/xwt,antmicro/xwt,hwthomas/xwt,lytico/xwt,mono/xwt,hamekoz/xwt | TestApps/Samples/Samples/FileSelectorSample.cs | TestApps/Samples/Samples/FileSelectorSample.cs | //
// FileSelector.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// 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 Xwt;
namespace Samples
{
public class FileSelectorSample: VBox
{
public FileSelectorSample ()
{
FileSelector fsel;
Label label;
PackStart (new Label("An open file selector:"));
PackStart (fsel = new FileSelector ());
PackStart (label = new Label ());
fsel.FileChanged += (sender, e) => { label.Text = "File changed: " + fsel.FileName; };
FileSelector fsel2;
Label label2;
PackStart (new Label ("An save file selector:") { MarginTop = 12 });
PackStart (fsel2 = new FileSelector { FileSelectionMode = FileSelectionMode.Save });
PackStart (label2 = new Label ());
fsel2.FileChanged += (sender, e) => label2.Text = "File changed: " + fsel2.FileName;
var pdfFormat = new FileDialogFilter ("PDF", "*.pdf");
var xlsFormat = new FileDialogFilter ("PNG", "*.png");
var fsel3 = new FileSelector { FileSelectionMode = FileSelectionMode.Open };
fsel3.Filters.Add (pdfFormat);
fsel3.Filters.Add (xlsFormat);
Label label3;
PackStart (new Label ("An Open file selector with filters:") { MarginTop = 12 });
PackStart (fsel3);
PackStart (label3 = new Label ());
fsel3.FileChanged += (sender, e) => label3.Text = "File changed: " + fsel3.FileName;
}
}
}
| //
// FileSelector.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// 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 Xwt;
namespace Samples
{
public class FileSelectorSample: VBox
{
public FileSelectorSample ()
{
FileSelector fsel;
Label label;
PackStart (new Label("An open file selector:"));
PackStart (fsel = new FileSelector ());
PackStart (label = new Label ());
fsel.FileChanged += (sender, e) => { label.Text = "File changed: " + fsel.FileName; };
FileSelector fsel2;
Label label2;
PackStart (new Label ("An save file selector:") { MarginTop = 12 });
PackStart (fsel2 = new FileSelector { FileSelectionMode = FileSelectionMode.Save });
PackStart (label2 = new Label ());
fsel2.FileChanged += (sender, e) => label2.Text = "File changed: " + fsel2.FileName;
}
}
}
| mit | C# |
ced176e8f89089a7cad5ae6fbadd94aef2c4df76 | Fix stack overflow | terrajobst/nquery-vnext | src/NQuery/SyntaxWalker.cs | src/NQuery/SyntaxWalker.cs | using System;
namespace NQuery
{
public abstract class SyntaxWalker : SyntaxVisitor
{
public override void DefaultVisit(SyntaxNode node)
{
foreach (var syntaxNodeOrToken in node.ChildNodesAndTokens())
{
if (syntaxNodeOrToken.IsToken)
VisitToken(syntaxNodeOrToken.AsToken());
else
Dispatch(syntaxNodeOrToken.AsNode());
}
}
public virtual void VisitToken(SyntaxToken token)
{
VisitLeadingTrivia(token);
VisitTrailingTrivia(token);
}
public virtual void VisitLeadingTrivia(SyntaxToken token)
{
foreach (var syntaxTrivia in token.LeadingTrivia)
VisitTrivia(syntaxTrivia);
}
public virtual void VisitTrailingTrivia(SyntaxToken token)
{
foreach (var syntaxTrivia in token.TrailingTrivia)
VisitTrivia(syntaxTrivia);
}
public virtual void VisitTrivia(SyntaxTrivia trivia)
{
var structure = trivia.Structure;
if (structure != null)
Dispatch(structure);
}
}
} | using System;
namespace NQuery
{
public abstract class SyntaxWalker : SyntaxVisitor
{
public override void DefaultVisit(SyntaxNode node)
{
foreach (var syntaxNodeOrToken in node.ChildNodesAndTokens())
{
if (syntaxNodeOrToken.IsToken)
VisitToken(syntaxNodeOrToken.AsToken());
else
Dispatch(node);
}
}
public virtual void VisitToken(SyntaxToken token)
{
VisitLeadingTrivia(token);
VisitTrailingTrivia(token);
}
public virtual void VisitLeadingTrivia(SyntaxToken token)
{
foreach (var syntaxTrivia in token.LeadingTrivia)
VisitTrivia(syntaxTrivia);
}
public virtual void VisitTrailingTrivia(SyntaxToken token)
{
foreach (var syntaxTrivia in token.TrailingTrivia)
VisitTrivia(syntaxTrivia);
}
public virtual void VisitTrivia(SyntaxTrivia trivia)
{
var structure = trivia.Structure;
if (structure != null)
Dispatch(structure);
}
}
} | mit | C# |
9f35da223fad4116f8102d64315e7bd6ad6a8ee6 | Update IInputBand.cs | LANDIS-II-Foundation/Landis-Spatial-Modeling-Library | src/RasterIO/IInputBand.cs | src/RasterIO/IInputBand.cs | // Contributors:
// James Domingo, Green Code LLC
namespace Landis.RasterIO
{
/// <summary>
/// Input raster band
/// </summary>
public interface IInputBand
{
/// <summary>
/// Read the value from the raster band into the corresponding band of
/// the buffer pixel.
/// </summary>
void ReadValueIntoBufferPixel();
}
}
| // Copyright 2010 Green Code LLC
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, Green Code LLC
namespace Landis.RasterIO
{
/// <summary>
/// Input raster band
/// </summary>
public interface IInputBand
{
/// <summary>
/// Read the value from the raster band into the corresponding band of
/// the buffer pixel.
/// </summary>
void ReadValueIntoBufferPixel();
}
}
| apache-2.0 | C# |
714c828c12d6f3108d34713815ac27a66ed2916e | exit test 2 | morganwm/reflectionCLI | src/ReflectionCli.Test/Standard/ExitTests.cs | src/ReflectionCli.Test/Standard/ExitTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ReflectionCli.Lib.Enums;
using ReflectionCli.Test.HelperServices;
using Xunit;
using static ReflectionCli.extended.ScriptingCommandSet;
namespace ReflectionCli.Test.Services
{
public class ExitTests
{
private readonly FakeLoggingService _loggingService;
private readonly Exit _exit;
public ExitTests()
{
_loggingService = new FakeLoggingService();
_exit = new Exit(_loggingService);
}
[Fact]
public void Exit_ExitFunction_ShouldSetProgramExitToTrue()
{
_exit.Run();
Assert.True(Program.ShutDown);
}
[Fact]
public void Exit_ExitFunction_ShouldPrintExitText()
{
_exit.Run();
var res = _loggingService.Records
.Where(t => t.RecordType == RecordType.Result)
.ToList();
Assert.Equal(res.Count, 1);
Assert.Equal(res.Single().Message, "Shutting down....");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ReflectionCli.Lib.Enums;
using ReflectionCli.Test.HelperServices;
using Xunit;
using static ReflectionCli.extended.ScriptingCommandSet;
namespace ReflectionCli.Test.Services
{
public class ExitTests
{
private readonly FakeLoggingService _loggingService;
private readonly Exit _exit;
public ExitTests()
{
_loggingService = new FakeLoggingService();
_exit = new Exit(_loggingService);
}
[Fact]
public void Exit_ExitFunction_ShouldSetProgramExitToTrue()
{
_exit.Run();
Assert.True(Program.ShutDown);
}
}
}
| mit | C# |
76154bc360eb9e979207a209fe4294b8198423f9 | Fix swagger schema | amweiss/WeatherLink | src/WeatherLink/Startup.cs | src/WeatherLink/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NSwag.AspNetCore;
using WeatherLink.Models;
using WeatherLink.Services;
using NSwag;
namespace WeatherLink
{
internal class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUi3();
app.UseStaticFiles();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOptions();
// Get config
services.Configure<WeatherLinkSettings>(Configuration);
// Setup token db
services.AddDbContext<SlackWorkspaceAppContext>();
// Add custom services
services.AddTransient<ITrafficAdviceService, WeatherBasedTrafficAdviceService>();
services.AddTransient<IGeocodeService, GoogleMapsGeocodeService>();
services.AddTransient<IDistanceToDurationService, GoogleMapsDistanceToDurationService>();
services.AddTransient<IDarkSkyService, HourlyAndMinutelyDarkSkyService>();
// Configure swagger
services.AddSwaggerDocument(c =>
{
c.Title = "WeatherLink";
c.Description = "An API to get weather based advice.";
c.PostProcess = (document) => document.Schemes = new[] { SwaggerSchema.Https };
});
}
}
} | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NSwag.AspNetCore;
using WeatherLink.Models;
using WeatherLink.Services;
namespace WeatherLink
{
internal class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUi3();
app.UseStaticFiles();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOptions();
// Get config
services.Configure<WeatherLinkSettings>(Configuration);
// Setup token db
services.AddDbContext<SlackWorkspaceAppContext>();
// Add custom services
services.AddTransient<ITrafficAdviceService, WeatherBasedTrafficAdviceService>();
services.AddTransient<IGeocodeService, GoogleMapsGeocodeService>();
services.AddTransient<IDistanceToDurationService, GoogleMapsDistanceToDurationService>();
services.AddTransient<IDarkSkyService, HourlyAndMinutelyDarkSkyService>();
// Configure swagger
services.AddSwaggerDocument(c =>
{
c.Title = "WeatherLink";
c.Description = "An API to get weather based advice.";
});
}
}
} | mit | C# |
929a59ade7f8cf67eb17ac4e7821b86a4ed794fb | Fix of incorrectly implemented interface. Addons GetAll() now returns the summary rather than the details. | lukecahill/alpha,lukecahill/alpha,lukecahill/alpha | Alpha.Infratructure/ViewModels/GameDetails.cs | Alpha.Infratructure/ViewModels/GameDetails.cs | using Alpha.DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alpha.Infrastructure.ViewModels {
public class GameDetails {
public string Title { get; set; }
public string Publisher { get; set; }
public DateTime ReleaseDate { get; set; }
public IEnumerable<Addons> AddonList { get; set; }
public IEnumerable<Accessories> AccessoryList { get; set; }
public GameDetails(Games game) {
this.Title = game.Title;
this.Publisher = game.Publisher.Name;
this.ReleaseDate = game.ReleaseDate;
// return the list of addons associated with the games ID, if any
if (game.Addons.Any(g => g.GameId == game.GameId)) {
this.AddonList = game.Addons.ToList().Where(g => g.GameId == game.GameId && g.IsDeleted == false);
//var ListOfAddons= game.Addons.ToList().Where(g => g.GameId == game.GameId && g.IsDeleted == false);
//foreach(var item in ListOfAddons) {
// var addon = new AddonSummary {
// Title = item.Title,
// AddonId = item.AddonId,
// GameTitle = item.Game.Title,
// Publisher = item.Game.Publisher.Name
// };
// this.AddonList.Add(addon);
//}
}
// return the list of accessories associated with the games ID, if any
if (game.Accessories.Any(g => g.GameId == game.GameId)) {
this.AccessoryList = game.Accessories.ToList().Where(g => g.GameId == game.GameId && g.IsDeleted == false);
}
}
}
}
| using Alpha.DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alpha.Infrastructure.ViewModels {
public class GameDetails {
public string Title { get; set; }
public string Publisher { get; set; }
public DateTime ReleaseDate { get; set; }
public IEnumerable<Addons> AddonList { get; set; }
public IEnumerable<Accessories> AccessoryList { get; set; }
public GameDetails(Games game) {
this.Title = game.Title;
this.Publisher = game.Publisher.Name;
this.ReleaseDate = game.ReleaseDate;
// return the list of addons associated with the games ID, if any
if (game.Addons.Any(g => g.GameId == game.GameId)) {
this.AddonList = game.Addons.ToList().Where(g => g.GameId == game.GameId && g.IsDeleted == false);
//var ListOfAddons= game.Addons.ToList().Where(g => g.GameId == game.GameId && g.IsDeleted == false);
//foreach(var item in ListOfAddons) {
// var addon = new AddonSummary {
// Title = item.Title,
// AddonId = item.AddonId,
// GameTitle = item.Game.Title,
// Publisher = item.Game.Publisher.Name
// };
// this.AddonList.Add(addon);
//}
}
// return the list of accessories associated with the games ID, if any
if (game.Accessories.Any(g => g.GameId == game.GameId)) {
this.AccessoryList = game.Accessories.ToList().Where(g => g.GameId == game.GameId && g.IsDeleted == false);
}
}
}
}
| mit | C# |
89e1141cc250c00e25205b5c87d6ae9d5e14b075 | Enable proper voice grouping for Reyes | overtools/OWLib | DataTool/ToolLogic/Extract/ExtractNPCVoice.cs | DataTool/ToolLogic/Extract/ExtractNPCVoice.cs | using System;
using System.Collections.Generic;
using System.IO;
using DataTool.FindLogic;
using DataTool.Flag;
using DataTool.Helper;
using DataTool.JSON;
using TankLib.STU.Types;
using static DataTool.Helper.STUHelper;
using static DataTool.Helper.IO;
namespace DataTool.ToolLogic.Extract {
[Tool("extract-npc-voice", Description = "Extracts NPC voicelines.", CustomFlags = typeof(ExtractFlags))]
class ExtractNPCVoice : JSONTool, ITool {
private const string Container = "NPCVoice";
private static readonly List<string> WhitelistedNPCs = new List<string> {"OR14-NS", "B73-NS", "Reyes"};
public void Parse(ICLIFlags toolFlags) {
string basePath;
if (toolFlags is ExtractFlags flags) {
basePath = Path.Combine(flags.OutputPath, Container);
} else {
throw new Exception("no output path");
}
foreach (var guid in Program.TrackedFiles[0x5F]) {
var voiceSet = GetInstance<STUVoiceSet>(guid);
if (voiceSet == null) continue;
var npcName = $"{GetString(voiceSet.m_269FC4E9)} {GetString(voiceSet.m_C0835C08)}".Trim();
if (string.IsNullOrEmpty(npcName)) {
continue;
}
var npcFileName = GetValidFilename(npcName);
Logger.Log($"Processing NPC {npcName}");
var info = new Combo.ComboInfo();
var ignoreGroups = !WhitelistedNPCs.Contains(npcName);
ExtractHeroVoiceBetter.SaveVoiceSet(flags, basePath, npcFileName, guid, ref info, ignoreGroups: ignoreGroups);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using DataTool.FindLogic;
using DataTool.Flag;
using DataTool.Helper;
using DataTool.JSON;
using TankLib.STU.Types;
using static DataTool.Helper.STUHelper;
using static DataTool.Helper.IO;
namespace DataTool.ToolLogic.Extract {
[Tool("extract-npc-voice", Description = "Extracts NPC voicelines.", CustomFlags = typeof(ExtractFlags))]
class ExtractNPCVoice : JSONTool, ITool {
private const string Container = "NPCVoice";
private static readonly List<string> WhitelistedNPCs = new List<string> {"OR14-NS", "B73-NS"};
public void Parse(ICLIFlags toolFlags) {
string basePath;
if (toolFlags is ExtractFlags flags) {
basePath = Path.Combine(flags.OutputPath, Container);
} else {
throw new Exception("no output path");
}
foreach (var guid in Program.TrackedFiles[0x5F]) {
var voiceSet = GetInstance<STUVoiceSet>(guid);
if (voiceSet == null) continue;
var npcName = $"{GetString(voiceSet.m_269FC4E9)} {GetString(voiceSet.m_C0835C08)}".Trim();
if (string.IsNullOrEmpty(npcName)) {
continue;
}
var npcFileName = GetValidFilename(npcName);
Logger.Log($"Processing NPC {npcName}");
var info = new Combo.ComboInfo();
var ignoreGroups = !WhitelistedNPCs.Contains(npcName);
ExtractHeroVoiceBetter.SaveVoiceSet(flags, basePath, npcFileName, guid, ref info, ignoreGroups: ignoreGroups);
}
}
}
}
| mit | C# |
b8e07e786c893af6e5ac550021ede9d27fd6d183 | Print source and destination addresses on ICMPv6 packets | zhanleewo/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg | src/bindings/TAPCfgTest.cs | src/bindings/TAPCfgTest.cs |
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start("Device name");
Console.WriteLine("Got device name: {0}", dev.DeviceName);
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
if (frame == null)
break;
if (frame.EtherType == EtherType.IPv6) {
IPv6Packet packet = new IPv6Packet(frame.Payload);
if (packet.NextHeader == ProtocolType.ICMPv6) {
ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
Console.WriteLine("Got ICMPv6 packet type {0}", type);
Console.WriteLine("Src: {0}", packet.Source);
Console.WriteLine("Dst: {0}", packet.Destination);
Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
}
}
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
|
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start("Device name");
Console.WriteLine("Got device name: {0}", dev.DeviceName);
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
if (frame == null)
break;
if (frame.EtherType == EtherType.IPv6) {
IPv6Packet packet = new IPv6Packet(frame.Payload);
if (packet.NextHeader == ProtocolType.ICMPv6) {
ICMPv6Type type = (ICMPv6Type) packet.Payload[0];
Console.WriteLine("Got ICMPv6 packet type {0}", type);
Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload));
}
}
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
| lgpl-2.1 | C# |
2696530c3f159fdd4eb5b98bca387689062a69ff | Add limits to the cards movement | Bigotter/gdggame | Assets/Scripts/SwipeCard.cs | Assets/Scripts/SwipeCard.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeCard : MonoBehaviour {
public GameObject currentCard;
private bool buttonDown = false;
private Vector3 startMousePos;
private Vector3 startPos;
private bool IsButtonDown()
{
if (!buttonDown && Input.GetMouseButtonDown (0)) {
return true;
}
else if (buttonDown && Input.GetMouseButtonUp(0))
{
return false;
}
return buttonDown;
}
void Update ()
{
buttonDown = IsButtonDown();
MoveCard (buttonDown);
}
private void MoveCard(bool buttonDown) {
if (buttonDown) {
Vector3 currentPos = Input.mousePosition;
Vector3 diff = currentPos - startMousePos;
Vector3 currentPosInWorld = Camera.main.ScreenToWorldPoint(currentPos);
Vector3 startMouseInWorld = Camera.main.ScreenToWorldPoint(startMousePos);
Vector3 diffInWorld = currentPosInWorld - startMouseInWorld;
Debug.Log ("down "+diff);
Vector3 newPos = CalculatePosition (currentCard.transform.position, diffInWorld);
Vector3 cardRotation = Vector3.zero;
if (!IsCardXLimit (newPos))
{
cardRotation = calculateRotation (diff);
}
currentCard.transform.position = newPos;
currentCard.transform.Rotate (cardRotation);
startMousePos = currentPos;
} else {
startMousePos = Input.mousePosition;
}
}
private bool IsCardXLimit(Vector3 newPos)
{
return newPos.x == 3.5f || newPos.x == -3.5f;
}
private Vector3 CalculatePosition(Vector3 currentPosition, Vector3 diffInWorld)
{
Vector3 newPos = new Vector3 ();
float newX = currentPosition.x + diffInWorld.x;
if (newX > 3.5f)
{
newX = 3.5f;
}
if (newX < -3.5f)
{
newX = -3.5f;
}
newPos.x = newX;
float newY = currentPosition.y + diffInWorld.y;
if (newY > 1.0f)
{
newY = 1.0f;
}
if (newY < -1.5f)
{
newY = -1.5f;
}
newPos.y = newY;
newPos.z = 0;
return newPos;
}
private Vector3 calculateRotation(Vector3 diff) {
float cardRotation = (diff.x * -90.0f) / Screen.width;
Vector3 newRotation = new Vector3 ();
newRotation.z = cardRotation;
newRotation.x = 0;
newRotation.y = 0;
return newRotation;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeCard : MonoBehaviour {
public GameObject currentCard;
private bool buttonDown = false;
private Vector3 startMousePos;
private Vector3 startPos;
private bool IsButtonDown()
{
if (!buttonDown && Input.GetMouseButtonDown (0)) {
return true;
}
else if (buttonDown && Input.GetMouseButtonUp(0))
{
return false;
}
return buttonDown;
}
void Update ()
{
buttonDown = IsButtonDown();
MoveCard (buttonDown);
}
private void MoveCard(bool buttonDown) {
if (buttonDown) {
Vector3 currentPos = Input.mousePosition;
Vector3 diff = currentPos - startMousePos;
Vector3 currentPosInWorld = Camera.main.ScreenToWorldPoint(currentPos);
Vector3 startMouseInWorld = Camera.main.ScreenToWorldPoint(startMousePos);
Vector3 diffInWorld = currentPosInWorld - startMouseInWorld;
Debug.Log ("down "+diff);
Vector3 newPos = CalculatePosition (currentCard.transform.position, diffInWorld);
Vector3 cardRotation = calculateRotation(diff);
currentCard.transform.position = newPos;
currentCard.transform.Rotate (cardRotation);
startMousePos = currentPos;
} else {
startMousePos = Input.mousePosition;
}
}
private Vector3 CalculatePosition(Vector3 currentPosition, Vector3 diffInWorld)
{
Vector3 newPos = new Vector3 ();
newPos.x = currentPosition.x + diffInWorld.x;
newPos.y = currentPosition.y + diffInWorld.y;
newPos.z = 0;
return newPos;
}
private Vector3 calculateRotation(Vector3 diff) {
float cardRotation = (diff.x * -90.0f) / Screen.width;
Vector3 newRotation = new Vector3 ();
newRotation.z = cardRotation;
newRotation.x = 0;
newRotation.y = 0;
return newRotation;
}
}
| apache-2.0 | C# |
57bcdcadced14cc1d6901a94f93e63729188039c | implement test for stream position | icarus-consulting/Yaapii.Atoms | tests/Yaapii.Atoms.Tests/IO/ZipFilesTest.cs | tests/Yaapii.Atoms.Tests/IO/ZipFilesTest.cs | // MIT License
//
// Copyright(c) 2019 ICARUS Consulting GmbH
//
// 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.IO;
using System.IO.Compression;
using Xunit;
using Yaapii.Atoms.Enumerable;
namespace Yaapii.Atoms.IO.Tests
{
public class ZipFilesTest
{
[Theory]
[InlineData("File1")]
[InlineData("File2")]
[InlineData("File3")]
public void HasData(string expected)
{
Assert.Contains<string>(
expected,
new ZipFiles(
new ResourceOf(
"Assets/Zip/ZipWithThreeFiles.zip",
this.GetType()
)
)
);
}
[Fact]
public void InputStreamPositionZero()
{
var res = new ResourceOf(
"Assets/Zip/ZipWithThreeFiles.zip",
this.GetType());
new ZipFiles(res);
Assert.InRange(res.Stream().Position, 0, 0);
}
}
}
| // MIT License
//
// Copyright(c) 2019 ICARUS Consulting GmbH
//
// 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.IO;
using System.IO.Compression;
using Xunit;
using Yaapii.Atoms.Enumerable;
namespace Yaapii.Atoms.IO.Tests
{
public class ZipFilesTest
{
[Theory]
[InlineData("File1")]
[InlineData("File2")]
[InlineData("File3")]
public void HasData(string expected)
{
Assert.Contains<string>(
expected,
new ZipFiles(
new ResourceOf(
"Assets/Zip/ZipWithThreeFiles.zip",
this.GetType()
)
)
);
}
}
}
| mit | C# |
dbffcc60a3bd0e13577c5d0a40381ac57d2c6455 | Update MvxFormsApp.cs | Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins,Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins | FormsPresenters/Core/MvxFormsApp.cs | FormsPresenters/Core/MvxFormsApp.cs | // MvxFormsApp.cs
// 2015 (c) Copyright Cheesebaron. http://ostebaronen.dk
// Cheesebaron.MvxPlugins.FormsPresenters is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Tomasz Cielecii, @cheesebaron, mvxplugins@ostebaronen.dk
using System;
using Xamarin.Forms;
namespace Cheesebaron.MvxPlugins.FormsPresenters.Core
{
public class MvxFormsApp : Application
{
public event EventHandler Start;
public event EventHandler Sleep;
public event EventHandler Resume;
protected override void OnStart()
{
var handler = Start;
if (handler != null)
handler(this, EventArgs.Empty);
}
protected override void OnSleep()
{
var handler = Sleep;
if (handler != null)
handler(this, EventArgs.Empty);
}
protected override void OnResume()
{
var handler = Resume;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
}
| using System;
using Xamarin.Forms;
namespace Cheesebaron.MvxPlugins.FormsPresenters.Core
{
public class MvxFormsApp : Application
{
public event EventHandler Start;
public event EventHandler Sleep;
public event EventHandler Resume;
protected override void OnStart()
{
var handler = Start;
if (handler != null)
handler(this, EventArgs.Empty);
}
protected override void OnSleep()
{
var handler = Sleep;
if (handler != null)
handler(this, EventArgs.Empty);
}
protected override void OnResume()
{
var handler = Resume;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
}
| apache-2.0 | C# |
a4ec840b77e96125cd134417288cc2e4f9acd9dd | Bump version to 15.2.2.34104 | HearthSim/HearthDb | HearthDb/Properties/AssemblyInfo.cs | HearthDb/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("15.2.2.34104")]
[assembly: AssemblyFileVersion("15.2.2.34104")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("15.2.0.33717")]
[assembly: AssemblyFileVersion("15.2.0.33717")]
| mit | C# |
12e407c8667cb48679feddd1a98b16e8e18db86a | Update Consumable.cs | legitbiz/SealsOfFate,connorkuehl/SealsOfFate,Zonr0/SealsOfFate | Assets/Scripts/Consumable.cs | Assets/Scripts/Consumable.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Consumable : MonoBehaviour, IInteractable {
// public int HealthMod;
// public int ManaMod;
public void Interact()
{
Consume();
}
virtual public void Consume()
{
// GameManager.instance.playerHealth += HealthMod;
// GameManager.instance.playerMana += ManaMod;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Consumable : MonoBehaviour, IInteractable {
// public int HealthMod;
// public int ManaMod;
public void Interact()
{
Consume();
}
virtual public void Consume()
{
// GameManager.instance.playerHealth += HealthMod;
// GameManager.instance.playerMana += ManaMod;
}
}
/*
public class Fish : Consumable {
public Fish()
{
}
public void Consume()
{
}
}*/
| mit | C# |
48ab938e73ea8059de52841dfe46547b54787bdf | initialise ReactiveUI on AfterPlatformServicesSetup hook. | AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,Perspex/Perspex,akrisiun/Perspex | src/Avalonia.ReactiveUI/AppBuilderExtensions.cs | src/Avalonia.ReactiveUI/AppBuilderExtensions.cs | using Avalonia.Controls;
using Avalonia.Threading;
using ReactiveUI;
using Splat;
namespace Avalonia.ReactiveUI
{
public static class AppBuilderExtensions
{
/// <summary>
/// Initializes ReactiveUI framework to use with Avalonia. Registers Avalonia
/// scheduler and Avalonia activation for view fetcher. Always remember to
/// call this method if you are using ReactiveUI in your application.
/// </summary>
public static TAppBuilder UseReactiveUI<TAppBuilder>(this TAppBuilder builder)
where TAppBuilder : AppBuilderBase<TAppBuilder>, new()
{
return builder.AfterPlatformServicesSetup(_ =>
{
RxApp.MainThreadScheduler = AvaloniaScheduler.Instance;
Locator.CurrentMutable.RegisterConstant(new AvaloniaActivationForViewFetcher(), typeof(IActivationForViewFetcher));
Locator.CurrentMutable.RegisterConstant(new AutoDataTemplateBindingHook(), typeof(IPropertyBindingHook));
});
}
}
}
| using Avalonia.Controls;
using Avalonia.Threading;
using ReactiveUI;
using Splat;
namespace Avalonia.ReactiveUI
{
public static class AppBuilderExtensions
{
/// <summary>
/// Initializes ReactiveUI framework to use with Avalonia. Registers Avalonia
/// scheduler and Avalonia activation for view fetcher. Always remember to
/// call this method if you are using ReactiveUI in your application.
/// </summary>
public static TAppBuilder UseReactiveUI<TAppBuilder>(this TAppBuilder builder)
where TAppBuilder : AppBuilderBase<TAppBuilder>, new()
{
return builder.AfterSetup(_ =>
{
RxApp.MainThreadScheduler = AvaloniaScheduler.Instance;
Locator.CurrentMutable.RegisterConstant(new AvaloniaActivationForViewFetcher(), typeof(IActivationForViewFetcher));
Locator.CurrentMutable.RegisterConstant(new AutoDataTemplateBindingHook(), typeof(IPropertyBindingHook));
});
}
}
}
| mit | C# |
c1f7a357931934da10f1af92eccb885cbd9b5eed | Update IProductRepository.cs | ziyasal/Httwrap,Trendyol/Httwrap | Httwrap.Tests/IProductRepository.cs | Httwrap.Tests/IProductRepository.cs | using System.Collections.Generic;
namespace Httwrap.Tests
{
//REFERENCE: http://www.asp.net/web-api/overview/older-versions/creating-a-web-api-that-supports-crud-operations
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
void Remove(int id);
bool Update(Product item);
void ClearAll();
}
}
| using System.Collections.Generic;
namespace Httwrap.Tests
{
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
void Remove(int id);
bool Update(Product item);
void ClearAll();
}
} | mit | C# |
459617e652fa9bb81f790ab95b4060503303defd | Fix DestroyEntitiesPacket for MC:Java | kennyvv/Alex,kennyvv/Alex,kennyvv/Alex,kennyvv/Alex | src/Alex.Networking.Java/Packets/Play/DestroyEntitiesPacket.cs | src/Alex.Networking.Java/Packets/Play/DestroyEntitiesPacket.cs | using System.Threading.Tasks;
using Alex.Networking.Java.Util;
namespace Alex.Networking.Java.Packets.Play
{
public class DestroyEntitiesPacket : Packet<DestroyEntitiesPacket>
{
public DestroyEntitiesPacket()
{
}
public int[] EntityIds;
/// <inheritdoc />
public override async Task DecodeAsync(MinecraftStream stream)
{
int count = await stream.ReadVarIntAsync();
EntityIds = new int[count];
for (int i = 0; i < EntityIds.Length; i++)
{
EntityIds[i] = await stream.ReadVarIntAsync();
}
}
public override void Encode(MinecraftStream stream)
{
}
}
}
| using Alex.Networking.Java.Util;
namespace Alex.Networking.Java.Packets.Play
{
public class DestroyEntitiesPacket : Packet<DestroyEntitiesPacket>
{
public DestroyEntitiesPacket()
{
}
public int[] EntityIds;
public override void Decode(MinecraftStream stream)
{
EntityIds = new int[1];
int count = stream.ReadVarInt();
EntityIds[0] = count;
}
public override void Encode(MinecraftStream stream)
{
}
}
}
| mpl-2.0 | C# |
503a4e962ee84a3ea54ef51dc35f772ae34a08df | upgrade version to 0.6.3239.1 | NetDimension/NanUI,NetDimension/NanUI,NetDimension/NanUI | NetDimension.NanUI/Properties/AssemblyInfo.cs | NetDimension.NanUI/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("NetDimension.NanUI")]
[assembly: AssemblyDescription("Build your WinForm with HTML5/CSS3 and Javascript.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Net Dimension Studio")]
[assembly: AssemblyProduct("NetDimension.NanUI")]
[assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2017 All Rights Reserved.")]
[assembly: AssemblyTrademark("Net Dimension Studio")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7b9b5ce5-1c96-4b61-b8fb-ba3a54eea482")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.6.3239.*")]
[assembly: AssemblyFileVersion("0.6.3239.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("NetDimension.NanUI")]
[assembly: AssemblyDescription("Build your WinForm with HTML5/CSS3 and Javascript.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Net Dimension Studio")]
[assembly: AssemblyProduct("NetDimension.NanUI")]
[assembly: AssemblyCopyright("Copyright © Net Dimension Studio 2017 All Rights Reserved.")]
[assembly: AssemblyTrademark("Net Dimension Studio")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7b9b5ce5-1c96-4b61-b8fb-ba3a54eea482")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.6.2987.*")]
[assembly: AssemblyFileVersion("0.6.2987.13")]
| mit | C# |
d2670344d395ce5e938083743e924a072ca91aa4 | Fix automated build. | ejball/XmlDocMarkdown | tools/Build/Build.cs | tools/Build/Build.cs | using System;
using Faithlife.Build;
using static Faithlife.Build.AppRunner;
internal static class Build
{
public static int Main(string[] args) => BuildRunner.Execute(args, build =>
{
var dotNetBuildSettings = new DotNetBuildSettings
{
NuGetApiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"),
SourceLinkSettings = new SourceLinkSettings
{
ShouldTestPackage = name => name == "XmlDocMarkdown.Core" || name == "Cake.XmlDocMarkdown",
},
};
build.AddDotNetTargets(dotNetBuildSettings);
build.Target("generate-docs")
.Describe("Generates documentation")
.DependsOn("build")
.Does(() => GenerateDocs(dotNetBuildSettings, verify: false));
build.Target("verify-docs")
.Describe("Verifies generated documentation")
.DependsOn("build")
.Does(() => GenerateDocs(dotNetBuildSettings, verify: true));
build.Target("test")
.DependsOn("verify-docs");
});
private static void GenerateDocs(DotNetBuildSettings dotNetBuildSettings, bool verify)
{
var configuration = dotNetBuildSettings.BuildOptions.ConfigurationOption.Value;
var projects = new[]
{
($"tools/XmlDocTarget/bin/{configuration}/net47/XmlDocMarkdown.Core.dll", "src/XmlDocMarkdown.Core/XmlDocSettings.json"),
($"tools/XmlDocTarget/bin/{configuration}/net47/Cake.XmlDocMarkdown.dll", "src/Cake.XmlDocMarkdown/XmlDocSettings.json"),
($"tools/XmlDocTarget/bin/{configuration}/net47/ExampleAssembly.dll", "tools/ExampleAssembly/XmlDocSettings.json"),
};
foreach ((string assemblyPath, string settingsPath) in projects)
RunDotNetFrameworkApp($"src/XmlDocMarkdown/bin/{configuration}/XmlDocMarkdown.exe", assemblyPath, "docs", "--settings", settingsPath, verify ? "--verify" : null);
}
}
| using Faithlife.Build;
using static Faithlife.Build.AppRunner;
internal static class Build
{
public static int Main(string[] args) => BuildRunner.Execute(args, build =>
{
var dotNetBuildSettings = new DotNetBuildSettings
{
SourceLinkSettings = new SourceLinkSettings
{
ShouldTestPackage = name => name == "XmlDocMarkdown.Core" || name == "Cake.XmlDocMarkdown",
},
};
build.AddDotNetTargets(dotNetBuildSettings);
build.Target("generate-docs")
.Describe("Generates documentation")
.DependsOn("build")
.Does(() => GenerateDocs(dotNetBuildSettings, verify: false));
build.Target("verify-docs")
.Describe("Verifies generated documentation")
.DependsOn("build")
.Does(() => GenerateDocs(dotNetBuildSettings, verify: true));
build.Target("test")
.DependsOn("verify-docs");
});
private static void GenerateDocs(DotNetBuildSettings dotNetBuildSettings, bool verify)
{
var configuration = dotNetBuildSettings.BuildOptions.ConfigurationOption.Value;
var projects = new[]
{
($"tools/XmlDocTarget/bin/{configuration}/net47/XmlDocMarkdown.Core.dll", "src/XmlDocMarkdown.Core/XmlDocSettings.json"),
($"tools/XmlDocTarget/bin/{configuration}/net47/Cake.XmlDocMarkdown.dll", "src/Cake.XmlDocMarkdown/XmlDocSettings.json"),
($"tools/XmlDocTarget/bin/{configuration}/net47/ExampleAssembly.dll", "tools/ExampleAssembly/XmlDocSettings.json"),
};
foreach ((string assemblyPath, string settingsPath) in projects)
RunDotNetFrameworkApp($"src/XmlDocMarkdown/bin/{configuration}/XmlDocMarkdown.exe", assemblyPath, "docs", "--settings", settingsPath, verify ? "--verify" : null);
}
}
| mit | C# |
e79ba9a1299fc54728d9762af30e5e38a02f0e4b | Add alwaysShowDecimals param to FormatAccuracy | NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu | osu.Game/Utils/FormatUtils.cs | osu.Game/Utils/FormatUtils.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.
namespace osu.Game.Utils
{
public static class FormatUtils
{
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 1d</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this double accuracy, bool alwaysShowDecimals = false) => accuracy == 1 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00%}";
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 100m</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this decimal accuracy, bool alwaysShowDecimals = false) => accuracy == 100 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00}%";
}
}
| // 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.
namespace osu.Game.Utils
{
public static class FormatUtils
{
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// Omits all decimal places when <paramref name="accuracy"/> equals 1d.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this double accuracy) => accuracy == 1 ? "100%" : $"{accuracy:0.00%}";
/// <summary>
/// Turns the provided accuracy into a percentage with 2 decimal places.
/// Omits all decimal places when <paramref name="accuracy"/> equals 100m.
/// </summary>
/// <param name="accuracy">The accuracy to be formatted</param>
/// <returns>formatted accuracy in percentage</returns>
public static string FormatAccuracy(this decimal accuracy) => accuracy == 100 ? "100%" : $"{accuracy:0.00}%";
}
}
| mit | C# |
bc801f7f8aeab780010d7ada1d7f02e556e675ce | determine transaction type; very oneof abuse | xxami/muppo-things,xxami/muppo-things | Cocopops/Cocopops/Program.cs | Cocopops/Cocopops/Program.cs |
using System.IO;
using Google.Protobuf;
using Cocopops.Model.BaseTransaction;
using Cocopops.Model.ExtendedTransaction;
using Cocopops.Model.Transaction;
using Cocopops.Model.TransactionCollection;
using System;
namespace Cocopops
{
class Program
{
static void Main(string[] args)
{
// Create our first transaction, using the minimal BaseTransaction type
var firstTransaction = new Transaction
{
BaseTransaction =
new BaseTransaction {ExecutingEntityCode = "neko1", TransactionReferenceNumber = "donuts0001"}
};
// A second transaction, using extra fields provided by ExtendedTransaction type
var secondTransaction = new Transaction
{
ExtendedTransaction = new ExtendedTransaction
{
BaseTransaction =
new BaseTransaction {ExecutingEntityCode = "neko2", TransactionReferenceNumber = "cookies0002"},
Comments = "cookies are sometimes better than donuts!",
Extra = "etc."
}
};
// Two transactions is maaaany transactions
var allTheTransactions = new TransactionCollection {Transaction = {firstTransaction, secondTransaction}};
// Serialize all of these things to a file
using (var outputStream = File.Create("SecretTransactions.dat")) allTheTransactions.WriteTo(outputStream);
// Deserialize
TransactionCollection transactionCollection;
using (var inputStream = File.OpenRead("SecretTransactions.dat"))
transactionCollection = TransactionCollection.Parser.ParseFrom(inputStream);
// Does it work?
foreach (var transaction in transactionCollection.Transaction) {
// Oneof determination
switch (transaction.TransactionCase)
{
case Transaction.TransactionOneofCase.BaseTransaction:
Console.WriteLine("{0}/{1}", transaction.BaseTransaction.ExecutingEntityCode, transaction.BaseTransaction.TransactionReferenceNumber);
break;
case Transaction.TransactionOneofCase.ExtendedTransaction:
Console.WriteLine("{0}/{1}/{2}/{3}", transaction.ExtendedTransaction.BaseTransaction.ExecutingEntityCode,
transaction.ExtendedTransaction.BaseTransaction.TransactionReferenceNumber,
transaction.ExtendedTransaction.Comments, transaction.ExtendedTransaction.Extra);
break;
}
}
Console.ReadKey();
}
}
}
|
using System.IO;
using Google.Protobuf;
using Cocopops.Model.BaseTransaction;
using Cocopops.Model.ExtendedTransaction;
using Cocopops.Model.Transaction;
using Cocopops.Model.TransactionCollection;
namespace Cocopops
{
class Program
{
static void Main(string[] args)
{
// Create our first transaction, using the minimal BaseTransaction type
var firstTransaction = new Transaction
{
BaseTransaction =
new BaseTransaction {ExecutingEntityCode = "neko1", TransactionReferenceNumber = "donuts0001"}
};
// A second transaction, using extra fields provided by ExtendedTransaction type
var secondTransaction = new Transaction
{
ExtendedTransaction = new ExtendedTransaction
{
BaseTransaction =
new BaseTransaction {ExecutingEntityCode = "neko2", TransactionReferenceNumber = "cookies0002"},
Comments = "cookies are sometimes better than donuts!",
Extra = "etc."
}
};
// Two transactions is maaaany transactions
var allTheTransactions = new TransactionCollection {Transaction = {firstTransaction, secondTransaction}};
// Serialize all of these things to a file
using (var outputStream = File.Create("SecretTransactions.dat")) allTheTransactions.WriteTo(outputStream);
// Deserialize
TransactionCollection transactionCollection;
using (var inputStream = File.OpenRead("SecretTransactions.dat"))
transactionCollection = TransactionCollection.Parser.ParseFrom(inputStream);
// Does it work?
foreach (var transaction in transactionCollection.Transaction)
{
transaction.TransactionCase
}
}
}
}
| unlicense | C# |
5d66dbd61002e02441420dd6649bd56b8c9ab0e1 | Use DotNetCoreBuild in Cake script. | ryanjfitz/SimpSim.NET | build.cake | build.cake | //////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Build")
.Does(() =>
{
DotNetCoreBuild("SimpSim.NET.sln", new DotNetCoreBuildSettings{Configuration = configuration});
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest();
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
| //////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore("SimpSim.NET.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration));
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./SimpSim.NET.Tests/SimpSim.NET.Tests.csproj");
DotNetCoreTest("./SimpSim.NET.Presentation.Tests/SimpSim.NET.Presentation.Tests.csproj");
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
| mit | C# |
62c7cdea6ea5e88a37a0051a0d114fbe9af20f47 | Use local Nuget to restore packages. | HangfireIO/Cronos | build.cake | build.cake | #addin nuget:?package=Cake.VersionReader
#tool "nuget:?package=xunit.runner.console"
Task("Restore-NuGet-Packages")
.Does(()=>
{
StartProcess(".nuget/NuGet.exe", new ProcessSettings
{
Arguments = "restore Cronos.sln"
});
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(()=>
{
MSBuild("Cronos.sln", new MSBuildSettings
{
ToolVersion = MSBuildToolVersion.VS2017,
Configuration = "Release"
}
.WithProperty("TargetFramework", "net452"));
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var testAssemblies = GetFiles("./tests/**/bin/Release/**/*.Tests.dll");
XUnit2(testAssemblies);
});
Task("Pack")
.IsDependentOn("Test")
.Does(()=>
{
var version = GetVersionNumber("src/Cronos/bin/Release/netstandard1.0/Cronos.dll");
var appveyorRepoTag = EnvironmentVariable("APPVEYOR_REPO_TAG");
var appveyorBuildNumber = EnvironmentVariable("APPVEYOR_BUILD_NUMBER");
if (appveyorRepoTag != "True" && appveyorBuildNumber != null)
{
version += "-build-" + appveyorBuildNumber;
}
var appveyorRepoTagName = EnvironmentVariable("APPVEYOR_REPO_TAG_NAME");
if(appveyorRepoTagName != null && appveyorRepoTagName.StartsWith("v"+version+"-"))
{
version = appveyorRepoTagName.Substring(1);
}
CreateDirectory("build");
CopyFiles(GetFiles("./src/Cronos/bin/**/*.nupkg"), "build");
Zip("./src/Cronos/bin/Release/netstandard1.0", "build/Cronos-" + version +".zip");
});
RunTarget("Pack"); | #addin nuget:?package=Cake.VersionReader
#tool "nuget:?package=xunit.runner.console"
Task("Restore-NuGet-Packages")
.Does(()=>
{
NuGetRestore("Cronos.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(()=>
{
MSBuild("Cronos.sln", new MSBuildSettings
{
ToolVersion = MSBuildToolVersion.VS2017,
Configuration = "Release"
}
.WithProperty("TargetFramework", "net452"));
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var testAssemblies = GetFiles("./tests/**/bin/Release/**/*.Tests.dll");
XUnit2(testAssemblies);
});
Task("Pack")
.IsDependentOn("Test")
.Does(()=>
{
var version = GetVersionNumber("src/Cronos/bin/Release/netstandard1.0/Cronos.dll");
var appveyorRepoTag = EnvironmentVariable("APPVEYOR_REPO_TAG");
var appveyorBuildNumber = EnvironmentVariable("APPVEYOR_BUILD_NUMBER");
if (appveyorRepoTag != "True" && appveyorBuildNumber != null)
{
version += "-build-" + appveyorBuildNumber;
}
var appveyorRepoTagName = EnvironmentVariable("APPVEYOR_REPO_TAG_NAME");
if(appveyorRepoTagName != null && appveyorRepoTagName.StartsWith("v"+version+"-"))
{
version = appveyorRepoTagName.Substring(1);
}
CreateDirectory("build");
CopyFiles(GetFiles("./src/Cronos/bin/**/*.nupkg"), "build");
Zip("./src/Cronos/bin/Release/netstandard1.0", "build/Cronos-" + version +".zip");
});
RunTarget("Pack"); | mit | C# |
42b77cf0fce04fc60997827c389e31237dc80192 | Add method for querying active entities | isurakka/ecs | ECS/EntityComponentSystem.cs | ECS/EntityComponentSystem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ECS
{
public class EntityComponentSystem
{
private EntityManager entityManager;
private SystemManager systemManager;
public EntityComponentSystem()
{
entityManager = new EntityManager();
systemManager = new SystemManager();
systemManager.context = this;
}
public Entity CreateEntity()
{
return entityManager.CreateEntity();
}
public void AddSystem(System system, int priority = 0)
{
systemManager.SetSystem(system, priority);
}
// TODO: Is this needed and is this right place for this method?
public IEnumerable<Entity> QueryActiveEntities(Aspect aspect)
{
return entityManager.GetEntitiesForAspect(aspect);
}
public void Update(float deltaTime)
{
foreach (var systems in systemManager.SystemsByPriority())
{
entityManager.ProcessQueues();
foreach (var system in systems)
{
system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime);
}
}
systemManager.ProcessQueues();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ECS
{
public class EntityComponentSystem
{
private EntityManager entityManager;
private SystemManager systemManager;
public EntityComponentSystem()
{
entityManager = new EntityManager();
systemManager = new SystemManager();
systemManager.context = this;
}
public Entity CreateEntity()
{
return entityManager.CreateEntity();
}
public void AddSystem(System system, int priority = 0)
{
systemManager.SetSystem(system, priority);
}
public void Update(float deltaTime)
{
foreach (var systems in systemManager.SystemsByPriority())
{
entityManager.ProcessQueues();
foreach (var system in systems)
{
system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime);
}
}
systemManager.ProcessQueues();
}
}
}
| apache-2.0 | C# |
e164e67cfe404e51c622c62240e3022cffcff83d | support predispose action | TakeAsh/cs-TakeAshUtility | TakeAshUtility/IDisposableHelper.cs | TakeAshUtility/IDisposableHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TakeAshUtility {
public static class IDisposableHelper {
public static void SafeDispose<T>(this T disposable, Action<T> predispose = null)
where T : IDisposable {
if (disposable == null) {
return;
}
if (predispose != null) {
predispose(disposable);
}
disposable.Dispose();
}
public static void SafeDispose<T>(this IEnumerable<T> disposables, Action<T> predispose = null)
where T : IDisposable {
if (disposables.SafeCount() == 0) {
return;
}
if (predispose == null) {
disposables.Where(disposable => disposable != null)
.ForEach(disposable => disposable.Dispose());
} else {
disposables.Where(disposable => disposable != null)
.ForEach(disposable => {
predispose(disposable);
disposable.Dispose();
});
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TakeAshUtility {
public static class IDisposableHelper {
public static void SafeDispose(this IDisposable disposable) {
if (disposable == null) {
return;
}
disposable.Dispose();
}
public static void SafeDispose<T>(this IEnumerable<T> disposables, Action<T> predispose = null)
where T : IDisposable {
if (disposables.SafeCount() == 0) {
return;
}
if (predispose == null) {
disposables.Where(disposable => disposable != null)
.ForEach(disposable => disposable.Dispose());
} else {
disposables.Where(disposable => disposable != null)
.ForEach(disposable => {
predispose(disposable);
disposable.Dispose();
});
}
}
}
}
| mit | C# |
112070c536e34b31124c68c2a0309d5754a79ed4 | Change remote app version to v0.1 | ascendedguard/starboard-sc2 | starboard-remote/Properties/AssemblyInfo.cs | starboard-remote/Properties/AssemblyInfo.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Starboard">
// Copyright © 2011 All Rights Reserved
// </copyright>
// <summary>
// AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("starboard-remote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ascend")]
[assembly: AssemblyProduct("starboard-remote")]
[assembly: AssemblyCopyright("Copyright © Ascend 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Starboard">
// Copyright © 2011 All Rights Reserved
// </copyright>
// <summary>
// AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("starboard-remote")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("starboard-remote")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
2fa591f2fdef113e89d01cd3c3016fed6508c016 | Document the MsoAnimTriggerType values | NetOfficeFw/NetOffice | Source/PowerPoint/Enums/MsoAnimTriggerType.cs | Source/PowerPoint/Enums/MsoAnimTriggerType.cs | using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.PowerPointApi.Enums
{
/// <summary>
/// The action that triggers the animation effect. The default value is <see cref="msoAnimTriggerOnPageClick"/>.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff743947.aspx </remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum MsoAnimTriggerType
{
/// <summary>
/// Mixed actions.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>-1</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerMixed = -1,
/// <summary>
/// No action associated as the trigger.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerNone = 0,
/// <summary>
/// When a page is clicked.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerOnPageClick = 1,
/// <summary>
/// When the Previous button is clicked.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerWithPrevious = 2,
/// <summary>
/// After the Previous button is clicked.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerAfterPrevious = 3,
/// <summary>
/// When a shape is clicked.
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerOnShapeClick = 4,
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks>5</remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
msoAnimTriggerOnMediaBookmark = 5
}
} | using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.PowerPointApi.Enums
{
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff743947.aspx </remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum MsoAnimTriggerType
{
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>-1</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerMixed = -1,
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerNone = 0,
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerOnPageClick = 1,
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerWithPrevious = 2,
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerAfterPrevious = 3,
/// <summary>
/// SupportByVersion PowerPoint 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersion("PowerPoint", 10,11,12,14,15,16)]
msoAnimTriggerOnShapeClick = 4,
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks>5</remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
msoAnimTriggerOnMediaBookmark = 5
}
} | mit | C# |
2b7690f117c83b7f26cdd3538c872ac97de1281e | Fix most recent issue in #9 (DPI awareness for screen capture tool). | VictorZakharov/pinwin | PinWin/Program.cs | PinWin/Program.cs | using System;
using System.Windows.Forms;
namespace PinWin
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (Environment.OSVersion.Version.Major >= 6)
{
SetProcessDPIAware();
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
/// <summary>
/// Sets process as DPI aware, prevents odd behavior related to auto-scaling.
/// </summary>
/// <remarks>
/// https://stackoverflow.com/questions/13228185/how-to-configure-an-app-to-run-correctly-on-a-machine-with-a-high-dpi-setting-e/13228495#13228495
/// </remarks>
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();
}
} | using System;
using System.Windows.Forms;
namespace PinWin
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
} | mit | C# |
2e1fe14de8705512fccfab590f03f8237ac7da4d | Add missing documentation | DotNetToscana/TranslatorService | Src/TranslatorService/Models/ErrorResponse.cs | Src/TranslatorService/Models/ErrorResponse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TranslatorService.Models
{
/// <summary>
/// Holds information about an error occurred while accessing Microsoft Translator Service.
/// </summary>
internal class ErrorResponse
{
/// <summary>
/// Gets or sets the error message.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets the HTTP status code.
/// </summary>
public int StatusCode { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TranslatorService.Models
{
internal class ErrorResponse
{
public string Message { get; set; }
public int StatusCode { get; set; }
}
}
| mit | C# |
0ce40a61f281a80e5aa48f0fd1a18932fd268c96 | Fix for build | rc1/BowieCode | Components/PivotGizmo3D.cs | Components/PivotGizmo3D.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace BowieCode {
/// <summary>
/// Draws customisable axises like the move tool when the object is not selected.
/// </summary>
[AddComponentMenu("BowieCode/Pivot Gizmo 3D")]
public class PivotGizmo3D : MonoBehaviour {
Transform _transform;
public float arrowSize = 0.25f;
public bool useDefaultColor = true;
public Color color = Color.cyan;
[Range(0.0f, 1.0f)]
public float alpha = 1.0f;
public bool showOnSelected = false;
#if UNITY_EDITOR
public void OnDrawGizmos () {
// Only when selected
if ( !showOnSelected ) {
if ( UnityEditor.Selection.activeGameObject == this.gameObject ) {
return;
}
}
// Cache transform
if ( _transform == null ) {
_transform = transform;
}
Handles.color = useDefaultColor ? ApplyAlpha( Handles.xAxisColor, alpha ) : color;
Handles.ArrowCap( 0, _transform.transform.position, _transform.transform.rotation * Quaternion.Euler( 0, 90, 0 ), arrowSize );
Handles.color = useDefaultColor ? ApplyAlpha( Handles.yAxisColor, alpha ) : color;
Handles.ArrowCap( 0, _transform.transform.position, _transform.transform.rotation * Quaternion.Euler( -90, 0, 0 ), arrowSize );
Handles.color = useDefaultColor ? ApplyAlpha( Handles.zAxisColor, alpha ) : color;
Handles.ArrowCap( 0, _transform.transform.position, _transform.transform.rotation, arrowSize );
}
#endif
public static Color ApplyAlpha ( Color c, float a ) {
c.a = a;
return c;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace BowieCode {
/// <summary>
/// Draws customisable axises like the move tool when the object is not selected.
/// </summary>
[AddComponentMenu("BowieCode/Pivot Gizmo 3D")]
public class PivotGizmo3D : MonoBehaviour {
Transform _transform;
public float arrowSize = 0.25f;
public bool useDefaultColor = true;
public Color color = Color.cyan;
[Range(0.0f, 1.0f)]
public float alpha = 1.0f;
public bool showOnSelected = false;
public void OnDrawGizmos () {
// Only when selected
if ( !showOnSelected ) {
if ( UnityEditor.Selection.activeGameObject == this.gameObject ) {
return;
}
}
// Cache transform
if ( _transform == null ) {
_transform = transform;
}
Handles.color = useDefaultColor ? ApplyAlpha( Handles.xAxisColor, alpha ) : color;
Handles.ArrowCap( 0, _transform.transform.position, _transform.transform.rotation * Quaternion.Euler( 0, 90, 0 ), arrowSize );
Handles.color = useDefaultColor ? ApplyAlpha( Handles.yAxisColor, alpha ) : color;
Handles.ArrowCap( 0, _transform.transform.position, _transform.transform.rotation * Quaternion.Euler( -90, 0, 0 ), arrowSize );
Handles.color = useDefaultColor ? ApplyAlpha( Handles.zAxisColor, alpha ) : color;
Handles.ArrowCap( 0, _transform.transform.position, _transform.transform.rotation, arrowSize );
}
public static Color ApplyAlpha ( Color c, float a ) {
c.a = a;
return c;
}
}
}
| mit | C# |
dd533ae685707a7519c08cd097c1107e0b64b173 | Add documentation for SuppressGCTransition (dotnet/coreclr#27368) (#42006) | shimingsg/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx | src/Common/src/CoreLib/System/Runtime/InteropServices/SuppressGCTransitionAttribute.cs | src/Common/src/CoreLib/System/Runtime/InteropServices/SuppressGCTransitionAttribute.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.
namespace System.Runtime.InteropServices
{
/// <summary>
/// An attribute used to indicate a GC transition should be skipped when making an unmanaged function call.
/// </summary>
/// <example>
/// Example of a valid use case. The Win32 `GetTickCount()` function is a small performance related function
/// that reads some global memory and returns the value. In this case, the GC transition overhead is significantly
/// more than the memory read.
/// <code>
/// using System;
/// using System.Runtime.InteropServices;
/// class Program
/// {
/// [DllImport("Kernel32")]
/// [SuppressGCTransition]
/// static extern int GetTickCount();
/// static void Main()
/// {
/// Console.WriteLine($"{GetTickCount()}");
/// }
/// }
/// </code>
/// </example>
/// <remarks>
/// This attribute is ignored if applied to a method without the <see cref="System.Runtime.InteropServices.DllImportAttribute"/>.
///
/// Forgoing this transition can yield benefits when the cost of the transition is more than the execution time
/// of the unmanaged function. However, avoiding this transition removes some of the guarantees the runtime
/// provides through a normal P/Invoke. When exiting the managed runtime to enter an unmanaged function the
/// GC must transition from Cooperative mode into Preemptive mode. Full details on these modes can be found at
/// https://github.com/dotnet/coreclr/blob/master/Documentation/coding-guidelines/clr-code-guide.md#2.1.8.
/// Suppressing the GC transition is an advanced scenario and should not be done without fully understanding
/// potential consequences.
///
/// One of these consequences is an impact to Mixed-mode debugging (https://docs.microsoft.com/visualstudio/debugger/how-to-debug-in-mixed-mode).
/// During Mixed-mode debugging, it is not possible to step into or set breakpoints in a P/Invoke that
/// has been marked with this attribute. A workaround is to switch to native debugging and set a breakpoint in the native function.
/// In general, usage of this attribute is not recommended if debugging the P/Invoke is important, for example
/// stepping through the native code or diagnosing an exception thrown from the native code.
///
/// The P/Invoke method that this attribute is applied to must have all of the following properties:
/// * Native function always executes for a trivial amount of time (less than 1 microsecond).
/// * Native function does not perform a blocking syscall (e.g. any type of I/O).
/// * Native function does not call back into the runtime (e.g. Reverse P/Invoke).
/// * Native function does not throw exceptions.
/// * Native function does not manipulate locks or other concurrency primitives.
///
/// Consequences of invalid uses of this attribute:
/// * GC starvation.
/// * Immediate runtime termination.
/// * Data corruption.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class SuppressGCTransitionAttribute : Attribute
{
public SuppressGCTransitionAttribute()
{
}
}
} | // 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.
namespace System.Runtime.InteropServices
{
/// <summary>
/// An attribute used to indicate a GC transition should be skipped when making an unmanaged function call.
/// </summary>
/// <remarks>
/// The eventual public attribute should replace this one: https://github.com/dotnet/corefx/issues/40740
/// </remarks>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class SuppressGCTransitionAttribute : Attribute
{
public SuppressGCTransitionAttribute()
{
}
}
} | mit | C# |
e681045315f5fda78c138ffed205c7809fdedf82 | Change method name | mikemajesty/coolvalidator | CoolValidator/Validator.cs | CoolValidator/Validator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace CoolValidator
{
public static class formValidator
{
public static List<TextBox> ValidateTextBox(this Form form, Func<TextBox, bool> predicate = null)
{
var txtList = new List<TextBox>();
var txtInPanel = GetTextBoxInContainer<Panel>(form);
var txtInManyPanel = GetTextBoxInManyContainers<Panel>(form);
var txtInGroupBox = GetTextBoxInContainer<GroupBox>(form);
var txtInManyGroupBox = GetTextBoxInManyContainers<GroupBox>(form);
var txtInForm = GetTextBoxInForm(form);
txtList.AddRange(txtInGroupBox);
txtList.AddRange(txtInManyGroupBox);
txtList.AddRange(txtInPanel);
txtList.AddRange(txtInManyPanel);
txtList.AddRange(txtInForm);
return predicate == null ? txtList.OrderBy(t => t.TabIndex).ToList() : txtList.Where(predicate).OrderBy(t => t.TabIndex).ToList();
}
private static List<TextBox> GetTextBoxInForm(Form form)
{
return form.Controls.OfType<TextBox>().Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInContainer<T>(Form form) where T : Control
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInManyContainers<T>(Form form) where T : Control
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<GroupBox>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace CoolValidator
{
public static class formValidator
{
public static List<TextBox> ValidateTextBox(this Form form, Func<TextBox, bool> predicate = null)
{
var txtList = new List<TextBox>();
var txtInPanel = GetTextBoxInGroupBox<Panel>(form);
var txtInManyPanel = GetInHierarchicalGroupBox<Panel>(form);
var txtInGroupBox = GetTextBoxInGroupBox<GroupBox>(form);
var txtInManyGroupBox = GetInHierarchicalGroupBox<GroupBox>(form);
var txtInForm = GetTextBoxInForm(form);
txtList.AddRange(txtInGroupBox);
txtList.AddRange(txtInManyGroupBox);
txtList.AddRange(txtInPanel);
txtList.AddRange(txtInManyPanel);
txtList.AddRange(txtInForm);
return predicate == null ? txtList.OrderBy(t => t.TabIndex).ToList() : txtList.Where(predicate).OrderBy(t => t.TabIndex).ToList();
}
private static List<TextBox> GetTextBoxInForm(Form form)
{
return form.Controls.OfType<TextBox>().Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInGroupBox<T>(Form form) where T : Control
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetInHierarchicalGroupBox<T>(Form form) where T : Control
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<GroupBox>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
}
}
| mit | C# |
aef31d28ea6c78f326524cf0a0f0f776a1700435 | Add some error checks to `run`. | mono/sdb,mono/sdb | src/Commands/RunCommand.cs | src/Commands/RunCommand.cs | /*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
namespace Mono.Debugger.Client.Commands
{
sealed class RunCommand : Command
{
public override string[] Names
{
get { return new[] { "run", "execute", "launch" }; }
}
public override string Summary
{
get { return "Run a virtual machine locally."; }
}
public override string Syntax
{
get { return "run|execute|launch <path>"; }
}
public override void Process(string args)
{
if (Debugger.State != State.Exited)
{
Log.Error("An inferior process is already being debugged");
return;
}
if (args.Length == 0)
{
Log.Error("No program path given");
return;
}
if (!File.Exists(args))
{
Log.Error("Program executable '{0}' does not exist", args);
return;
}
FileInfo file;
try
{
file = new FileInfo(args);
}
catch (Exception ex)
{
Log.Error("Could not open file '{0}':", args);
Log.Error(ex.ToString());
return;
}
Debugger.Run(file);
}
}
}
| /*
* SDB - Mono Soft Debugger Client
* Copyright 2013 Alex Rønne Petersen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
namespace Mono.Debugger.Client.Commands
{
sealed class RunCommand : Command
{
public override string[] Names
{
get { return new[] { "run", "execute", "launch" }; }
}
public override string Summary
{
get { return "Run a virtual machine locally."; }
}
public override string Syntax
{
get { return "run|execute|launch <path>"; }
}
public override void Process(string args)
{
if (Debugger.State != State.Exited)
{
Log.Error("An inferior process is already being debugged");
return;
}
FileInfo file;
try
{
file = new FileInfo(args);
}
catch (Exception ex)
{
Log.Error("Could not open file '{0}':", args);
Log.Error(ex.ToString());
return;
}
Debugger.Run(file);
}
}
}
| mit | C# |
427c01dac3e33fac8f9b9d8b907e41f74a13ae94 | Update Codec.cs | lailongwei/llbc,lailongwei/llbc,lailongwei/llbc,lailongwei/llbc,lailongwei/llbc | wrap/csllbc/csharp/comm/Codec.cs | wrap/csllbc/csharp/comm/Codec.cs | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// 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.IO;
namespace llbc
{
/// <summary>
/// Library encodable/decodable object interface encapsulation.
/// </summary>
public interface ICoder
{
/// <summary>
/// Encode object to stream.
/// </summary>
/// <param name="stream">stream object</param>
/// <returns>return true if encode success, otherwise return false</returns>
bool Encode(MemoryStream stream);
/// <summary>
/// Decode object from stream.
/// </summary>
/// <param name="stream">stream object</param>
/// <returns>return true if encode success, otherwise return false</returns>
bool Decode(MemoryStream stream);
}
/// <summary>
/// Library global coder interface encapsulation.
/// </summary>
public interface IGlobalCoder
{
/// <summary>
/// Encode object to stream.
/// </summary>
/// <param name="stream">stream</param>
/// <param name="obj">object</param>
/// <returns>return true if encode success, otherwise return false</returns>
bool Encode(MemoryStream stream, object obj);
/// <summary>
/// Decode specific type object from stream.
/// </summary>
/// <param name="stream">stream</param>
/// <param name="cls">object type</param>
/// <returns>decoded object, if decode failed</returns>
object Decode(MemoryStream stream, Type cls);
}
}
| // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// 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.IO;
namespace llbc
{
/// <summary>
/// Library encodable/decodable object interface encapsulation.
/// </summary>
public interface ICoder
{
/// <summary>
/// Encode object to stream.
/// </summary>
/// <param name="stream">stream object</param>
/// <returns>return true if encode success, otherwise return false</returns>
bool Encode(MemoryStream stream);
/// <summary>
/// Decode object from stream.
/// </summary>
/// <param name="stream">stream object</param>
/// <returns>return true if encode success, otherwise return false</returns>
bool Decode(MemoryStream stream);
}
/// <summary>
/// Library global coder interface encapsulation.
/// </summary>
public interface IGlobalCoder
{
/// <summary>
/// Encode object to stream.
/// </summary>
/// <param name="stream">stream</param>
/// <param name="obj">object</param>
/// <returns>return true if encode success, otherwise return false</returns>
bool Encode(MemoryStream stream, object obj);
/// <summary>
/// Decode specific type object from stream.
/// </summary>
/// <param name="stream">stream</param>
/// <param name="cls">object type</param>
/// <returns>decoded object, if decode failed</returns>
object Decode(MemoryStream stream, Type cls);
}
} | mit | C# |
1f531c2df1346deb0154154a4648a3759a0ecaa4 | store the host/port | mlittle/avaya-moagent-client | AvayaMoagentClient/AvayaDialer.cs | AvayaMoagentClient/AvayaDialer.cs | using AvayaMoagentClient.Commands;
namespace AvayaMoagentClient
{
public class AvayaDialer
{
private MoagentClient _client;
private string _host;
private int _port;
public event MoagentClient.MessageReceivedHandler MessageReceived;
public AvayaDialer(string host, int port)
{
_host = host;
_port = port;
}
void _client_MessageReceived(object sender, MessageReceivedEventArgs e)
{
if (MessageReceived != null)
MessageReceived(this, e);
}
void _client_ConnectComplete(object sender, System.EventArgs e)
{
//do something?
}
public void Connect()
{
_client = new MoagentClient(_host, _port);
_client.ConnectComplete += _client_ConnectComplete;
_client.MessageReceived += _client_MessageReceived;
_client.StartConnectAsync();
}
public void Login(string username, string password)
{
_client.Send(new Logon(username, password));
}
public void ReserveHeadset(string extension)
{
_client.Send(new ReserveHeadset(extension));
}
public void ConnectHeadset()
{
_client.Send(CommandCache.ConnectHeadset);
}
public void ListState()
{
_client.Send(CommandCache.ListState);
}
public void ListJobs()
{
_client.Send(CommandCache.ListAllJobs);
}
public void ListActiveJobs()
{
_client.Send(new ListJobs(Commands.ListJobs.JobListingType.All, Commands.ListJobs.JobStatus.Active));
}
public void DisconnectHeadset()
{
_client.Send(CommandCache.DisconnectHeadset);
}
public void Logoff()
{
_client.Send(CommandCache.LogOff);
}
public void Disconnect()
{
_client.Disconnect();
_client.ConnectComplete -= _client_ConnectComplete;
_client.MessageReceived -= _client_MessageReceived;
_client = null;
}
public void SendCommand(Message command)
{
_client.Send(command);
}
}
}
| using AvayaMoagentClient.Commands;
namespace AvayaMoagentClient
{
public class AvayaDialer
{
private MoagentClient _client;
private string _host;
private int _port;
public event MoagentClient.MessageReceivedHandler MessageReceived;
public AvayaDialer(string host, int port)
{
_host = host;
_port = port;
}
void _client_MessageReceived(object sender, MessageReceivedEventArgs e)
{
if (MessageReceived != null)
MessageReceived(this, e);
}
void _client_ConnectComplete(object sender, System.EventArgs e)
{
//do something?
}
public void Connect()
{
_client = new MoagentClient(_host, _port);
_client.ConnectComplete += _client_ConnectComplete;
_client.MessageReceived += _client_MessageReceived;
_client.StartConnectAsync();
}
public void Login(string username, string password)
{
_client.Send(new Logon(username, password));
}
public void ReserveHeadset(string extension)
{
_client.Send(new ReserveHeadset(extension));
}
public void ConnectHeadset()
{
_client.Send(CommandCache.ConnectHeadset);
}
public void ListState()
{
_client.Send(CommandCache.ListState);
}
public void ListJobs()
{
_client.Send(CommandCache.ListAllJobs);
}
public void ListActiveJobs()
{
_client.Send(new ListJobs(Commands.ListJobs.JobListingType.All, Commands.ListJobs.JobStatus.Active));
}
public void DisconnectHeadset()
{
_client.Send(CommandCache.DisconnectHeadset);
}
public void Logoff()
{
_client.Send(CommandCache.LogOff);
}
public void Disconnect()
{
_client.Disconnect();
_client.ConnectComplete -= _client_ConnectComplete;
_client.MessageReceived -= _client_MessageReceived;
_client = null;
}
public void SendCommand(Message command)
{
_client.Send(command);
}
}
}
| bsd-2-clause | C# |
268d20106b95075c716ba8951a2bcd34a1110242 | Add System.Threading.Thread serialization | rahku/corefx,rubo/corefx,stephenmichaelf/corefx,ViktorHofer/corefx,lggomez/corefx,ViktorHofer/corefx,krytarowski/corefx,JosephTremoulet/corefx,Petermarcu/corefx,rubo/corefx,shimingsg/corefx,Jiayili1/corefx,stone-li/corefx,DnlHarvey/corefx,parjong/corefx,Jiayili1/corefx,mazong1123/corefx,ptoonen/corefx,the-dwyer/corefx,yizhang82/corefx,marksmeltzer/corefx,mmitche/corefx,richlander/corefx,ravimeda/corefx,alexperovich/corefx,rubo/corefx,YoupHulsebos/corefx,zhenlan/corefx,parjong/corefx,elijah6/corefx,the-dwyer/corefx,DnlHarvey/corefx,elijah6/corefx,Ermiar/corefx,Jiayili1/corefx,ravimeda/corefx,seanshpark/corefx,weltkante/corefx,ptoonen/corefx,rahku/corefx,twsouthwick/corefx,krk/corefx,mmitche/corefx,DnlHarvey/corefx,YoupHulsebos/corefx,jlin177/corefx,jlin177/corefx,weltkante/corefx,elijah6/corefx,dotnet-bot/corefx,rubo/corefx,fgreinacher/corefx,billwert/corefx,ravimeda/corefx,dotnet-bot/corefx,ericstj/corefx,axelheer/corefx,yizhang82/corefx,nchikanov/corefx,stephenmichaelf/corefx,wtgodbe/corefx,ptoonen/corefx,nchikanov/corefx,krytarowski/corefx,lggomez/corefx,cydhaselton/corefx,nchikanov/corefx,parjong/corefx,ericstj/corefx,richlander/corefx,alexperovich/corefx,Jiayili1/corefx,JosephTremoulet/corefx,lggomez/corefx,BrennanConroy/corefx,stone-li/corefx,krytarowski/corefx,jlin177/corefx,Jiayili1/corefx,zhenlan/corefx,wtgodbe/corefx,tijoytom/corefx,axelheer/corefx,rahku/corefx,dhoehna/corefx,rahku/corefx,billwert/corefx,rjxby/corefx,wtgodbe/corefx,weltkante/corefx,mazong1123/corefx,lggomez/corefx,seanshpark/corefx,nbarbettini/corefx,twsouthwick/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,elijah6/corefx,dhoehna/corefx,ravimeda/corefx,ravimeda/corefx,parjong/corefx,cydhaselton/corefx,nbarbettini/corefx,the-dwyer/corefx,alexperovich/corefx,YoupHulsebos/corefx,gkhanna79/corefx,ptoonen/corefx,the-dwyer/corefx,MaggieTsang/corefx,the-dwyer/corefx,zhenlan/corefx,stone-li/corefx,tijoytom/corefx,Ermiar/corefx,shimingsg/corefx,dhoehna/corefx,rahku/corefx,krk/corefx,billwert/corefx,twsouthwick/corefx,alexperovich/corefx,shimingsg/corefx,DnlHarvey/corefx,mmitche/corefx,twsouthwick/corefx,wtgodbe/corefx,richlander/corefx,dhoehna/corefx,ravimeda/corefx,zhenlan/corefx,stephenmichaelf/corefx,gkhanna79/corefx,dhoehna/corefx,ViktorHofer/corefx,krk/corefx,axelheer/corefx,krk/corefx,ViktorHofer/corefx,MaggieTsang/corefx,shimingsg/corefx,dhoehna/corefx,Jiayili1/corefx,marksmeltzer/corefx,ViktorHofer/corefx,richlander/corefx,rahku/corefx,ptoonen/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,rjxby/corefx,BrennanConroy/corefx,krytarowski/corefx,weltkante/corefx,stone-li/corefx,yizhang82/corefx,parjong/corefx,ericstj/corefx,jlin177/corefx,cydhaselton/corefx,MaggieTsang/corefx,rjxby/corefx,stephenmichaelf/corefx,billwert/corefx,dotnet-bot/corefx,mmitche/corefx,yizhang82/corefx,jlin177/corefx,lggomez/corefx,cydhaselton/corefx,JosephTremoulet/corefx,dhoehna/corefx,zhenlan/corefx,mmitche/corefx,lggomez/corefx,YoupHulsebos/corefx,ptoonen/corefx,nchikanov/corefx,MaggieTsang/corefx,parjong/corefx,seanshpark/corefx,BrennanConroy/corefx,elijah6/corefx,fgreinacher/corefx,fgreinacher/corefx,the-dwyer/corefx,jlin177/corefx,YoupHulsebos/corefx,gkhanna79/corefx,seanshpark/corefx,dotnet-bot/corefx,axelheer/corefx,seanshpark/corefx,ViktorHofer/corefx,alexperovich/corefx,elijah6/corefx,marksmeltzer/corefx,billwert/corefx,shimingsg/corefx,weltkante/corefx,ptoonen/corefx,ericstj/corefx,zhenlan/corefx,ericstj/corefx,billwert/corefx,Jiayili1/corefx,cydhaselton/corefx,MaggieTsang/corefx,mazong1123/corefx,JosephTremoulet/corefx,stephenmichaelf/corefx,seanshpark/corefx,weltkante/corefx,tijoytom/corefx,richlander/corefx,Petermarcu/corefx,nbarbettini/corefx,wtgodbe/corefx,nbarbettini/corefx,mmitche/corefx,DnlHarvey/corefx,tijoytom/corefx,JosephTremoulet/corefx,axelheer/corefx,Ermiar/corefx,krytarowski/corefx,Petermarcu/corefx,cydhaselton/corefx,elijah6/corefx,marksmeltzer/corefx,dotnet-bot/corefx,Petermarcu/corefx,yizhang82/corefx,nbarbettini/corefx,lggomez/corefx,richlander/corefx,billwert/corefx,nchikanov/corefx,MaggieTsang/corefx,yizhang82/corefx,JosephTremoulet/corefx,krk/corefx,mazong1123/corefx,parjong/corefx,ericstj/corefx,rjxby/corefx,wtgodbe/corefx,marksmeltzer/corefx,richlander/corefx,ericstj/corefx,marksmeltzer/corefx,gkhanna79/corefx,alexperovich/corefx,DnlHarvey/corefx,Petermarcu/corefx,krytarowski/corefx,rjxby/corefx,rjxby/corefx,rubo/corefx,yizhang82/corefx,shimingsg/corefx,tijoytom/corefx,marksmeltzer/corefx,rahku/corefx,krk/corefx,mazong1123/corefx,ViktorHofer/corefx,jlin177/corefx,rjxby/corefx,gkhanna79/corefx,MaggieTsang/corefx,krytarowski/corefx,shimingsg/corefx,the-dwyer/corefx,JosephTremoulet/corefx,tijoytom/corefx,gkhanna79/corefx,Petermarcu/corefx,nchikanov/corefx,ravimeda/corefx,Ermiar/corefx,stone-li/corefx,axelheer/corefx,nbarbettini/corefx,Ermiar/corefx,nchikanov/corefx,stone-li/corefx,Ermiar/corefx,cydhaselton/corefx,Ermiar/corefx,seanshpark/corefx,mmitche/corefx,twsouthwick/corefx,twsouthwick/corefx,fgreinacher/corefx,Petermarcu/corefx,krk/corefx,gkhanna79/corefx,mazong1123/corefx,twsouthwick/corefx,nbarbettini/corefx,YoupHulsebos/corefx,alexperovich/corefx,dotnet-bot/corefx,weltkante/corefx,zhenlan/corefx,stone-li/corefx,wtgodbe/corefx,mazong1123/corefx,tijoytom/corefx | src/System.Threading.Thread/src/System/Threading/ThreadAbortException.cs | src/System.Threading.Thread/src/System/Threading/ThreadAbortException.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.Runtime.Serialization;
namespace System.Threading
{
// Thread.Abort() is not supported in .NET core, so this is currently just a stub to make the type available at compile time
[Serializable]
public sealed class ThreadAbortException : SystemException
{
private ThreadAbortException()
{
}
internal ThreadAbortException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public object ExceptionState => null;
}
}
| // 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.
namespace System.Threading
{
// Thread.Abort() is not supported in .NET core, so this is currently just a stub to make the type available at compile time
public sealed class ThreadAbortException : SystemException
{
private ThreadAbortException()
{
}
public object ExceptionState => null;
}
}
| mit | C# |
10cc9ba0745d07e5616b58133ec60dd1b220482d | Fix compilation error in sample | tomba/Toolkit,sharpdx/Toolkit,sharpdx/Toolkit | Samples/Toolkit/Desktop/MiniCube/Program.cs | Samples/Toolkit/Desktop/MiniCube/Program.cs | // Copyright (c) 2010-2012 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace MiniCube
{
/// <summary>
/// Simple MiniCube application using SharpDX.Toolkit.
/// </summary>
class Program
{
/// <summary>
/// Defines the entry point of the application.
/// </summary>
#if NETFX_CORE
[MTAThread]
#else
[STAThread]
#endif
static void Main()
{
using (var program = new MiniCubeGame())
program.Run();
}
}
}
| // Copyright (c) 2010-2012 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace MiniCube
{
/// <summary>
/// Simple MiniCube application using SharpDX.Toolkit.
/// </summary>
class Program
{
/// <summary>
/// Defines the entry point of the application.
/// </summary>
#if NETFX_CORE
[MTAThread]
#else
[STAThread]
#endif
static void Main()
{
using (var program = new SphereGame())
program.Run();
}
}
}
| mit | C# |
0e77345707b9260e6418f855722431179cb7f66d | Improve code documentation in the IStorageEngine interface | openchain/openchain | src/Openchain.Abstractions/IStorageEngine.cs | src/Openchain.Abstractions/IStorageEngine.cs | // Copyright 2015 Coinprism, 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.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Openchain
{
/// <summary>
/// Represents a data store for key-value pairs.
/// </summary>
public interface IStorageEngine : IDisposable
{
/// <summary>
/// Initializes the storage engine.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task Initialize();
/// <summary>
/// Adds multiple transactions to the store.
/// Either all transactions are committed or none are.
/// </summary>
/// <param name="transactions">A collection of serialized <see cref="Transaction"/> objects to add to the store.</param>
/// <exception cref="ConcurrentMutationException">A record has been mutated and the transaction is no longer valid.</exception>
/// <returns>The task object representing the asynchronous operation.</returns>
Task AddTransactions(IEnumerable<ByteString> transactions);
/// <summary>
/// Gets the current records for a set of keys.
/// </summary>
/// <param name="keys">The keys to query.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<Record>> GetRecords(IEnumerable<ByteString> keys);
/// <summary>
/// Gets the hash of the last transaction in the ledger.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ByteString> GetLastTransaction();
/// <summary>
/// Gets an ordered list of transactions from a given point.
/// </summary>
/// <param name="from">The hash of the transaction to start from.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<ByteString>> GetTransactions(ByteString from);
}
}
| // Copyright 2015 Coinprism, 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.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Openchain
{
/// <summary>
/// Represents a data store for key-value pairs.
/// </summary>
public interface IStorageEngine : IDisposable
{
/// <summary>
/// Initializes the storage engine.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task Initialize();
/// <summary>
/// Adds a transaction to the store.
/// </summary>
/// <param name="transactions">A collection of serialized <see cref="Transaction"/> to add to the store.</param>
/// <exception cref="ConcurrentMutationException">A record has been mutated and the transaction is no longer valid.</exception>
/// <returns>The task object representing the asynchronous operation.</returns>
Task AddTransactions(IEnumerable<ByteString> transactions);
/// <summary>
/// Gets the current records for a set of keys.
/// </summary>
/// <param name="keys">The keys to query.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<Record>> GetRecords(IEnumerable<ByteString> keys);
/// <summary>
/// Gets the hash of the last transaction in the ledger.
/// </summary>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ByteString> GetLastTransaction();
/// <summary>
/// Get an ordered list of transactions from a given point.
/// </summary>
/// <param name="from">The hash of the transaction to start from.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IReadOnlyList<ByteString>> GetTransactions(ByteString from);
}
}
| apache-2.0 | C# |
90f7e83a68dc2372b3b648f228768c0f4d38902e | Implement scanning assemblies for function types | manisero/DSLExecutor | dev/Manisero.DSLExecutor.Parser.SampleDSL/ExpressionGeneration/FunctionExpressionGeneration/FunctionTypeResolvers/TypeSamplesAndSuffixConventionBasedFunctionTypeResolver.cs | dev/Manisero.DSLExecutor.Parser.SampleDSL/ExpressionGeneration/FunctionExpressionGeneration/FunctionTypeResolvers/TypeSamplesAndSuffixConventionBasedFunctionTypeResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Manisero.DSLExecutor.Domain.FunctionsDomain;
using Manisero.DSLExecutor.Extensions;
using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens;
namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers
{
public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver
{
private readonly IEnumerable<Type> _functionTypeSamples;
private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap;
public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples)
{
_functionTypeSamples = functionTypeSamples;
_functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap);
}
public Type Resolve(FunctionCall functionCall)
{
Type result;
return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result)
? null
: result;
}
private IDictionary<string, Type> InitializeFunctionNameToTypeMap()
{
var result = new Dictionary<string, Type>();
var assembliesToScan = _functionTypeSamples.Select(x => x.Assembly).Distinct();
var typesToScan = assembliesToScan.SelectMany(x => x.GetTypes());
foreach (var type in typesToScan)
{
var functionDefinitionImplementation = type.GetGenericInterfaceDefinitionImplementation(typeof(IFunction<>));
if (functionDefinitionImplementation == null)
{
continue;
}
// TODO: Fill result with type names without "Function" suffix
}
return result;
}
}
}
| using System;
using System.Collections.Generic;
using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens;
namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers
{
public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver
{
private readonly IEnumerable<Type> _functionTypeSamples;
private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap;
public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples)
{
_functionTypeSamples = functionTypeSamples;
_functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap);
}
public Type Resolve(FunctionCall functionCall)
{
Type result;
return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result)
? null
: result;
}
private IDictionary<string, Type> InitializeFunctionNameToTypeMap()
{
var result = new Dictionary<string, Type>();
foreach (var functionTypeSample in _functionTypeSamples)
{
// TODO: Scan sample's assembly for function types
// TODO: Fill result with type names without "Function" suffix
}
return result;
}
}
}
| mit | C# |
6232e372397f04a9e7252564d39edb2880aa3b61 | Bump to v0.8.0 | danielwertheim/mynatsclient,danielwertheim/mynatsclient | buildconfig.cake | buildconfig.cake | public class BuildConfig
{
private const string Version = "0.8.0";
private const bool IsPreRelease = false;
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string SemVer { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty),
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
}
| public class BuildConfig
{
private const string Version = "0.7.0";
private const bool IsPreRelease = false;
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string SemVer { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty),
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
}
| mit | C# |
ed714c20d53528d4f69af884ac0f17cf862a538f | Fix build..... | sitofabi/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,sitofabi/duplicati,duplicati/duplicati,duplicati/duplicati,sitofabi/duplicati,sitofabi/duplicati,mnaiman/duplicati,sitofabi/duplicati,mnaiman/duplicati | Duplicati/UnitTest/WebApiTests.cs | Duplicati/UnitTest/WebApiTests.cs | // Copyright (C) 2018, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using NUnit.Framework;
using Duplicati.Library.Backend.WebApi;
namespace Duplicati.UnitTest
{
public static class WebApiUrlTests
{
[Test]
[Category("WebApi")]
public static void GoogleCloudPutUrl()
{
string bucketId = "my_bucket";
string putUrl = $"https://www.googleapis.com/upload/storage/v1/b/{bucketId}/o?uploadType=resumable";
Assert.AreEqual(putUrl, GoogleCloudStorage.PutUrl(bucketId));
}
[Test]
[Category("WebApi")]
public static void CreateFolderUrl()
{
var url = "https://www.googleapis.com/drive/v2/files?supportsTeamDrives=true";
Assert.AreEqual(url, GoogleDrive.CreateFolderUrl(""));
}
[Test]
[Category("WebApi")]
public static void AboutInfoUrl()
{
var url = "https://www.googleapis.com/drive/v2/about";
Assert.AreEqual(url, GoogleDrive.AboutInfoUrl());
}
}
}
| // Copyright (C) 2018, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using NUnit.Framework;
using Duplicati.Library.Backend.WebApi;
namespace Duplicati.UnitTest
{
public static class WebApiUrlTests
{
[Test]
[Category("WebApi")]
public static void GoogleCloudPutUrl()
{
string bucketId = "my_bucket";
string putUrl = $"https://www.googleapis.com/upload/storage/v1/b/{bucketId}/o?uploadType=resumable";
Assert.AreEqual(putUrl, GoogleCloudStorage.PutUrl(bucketId));
}
[Test]
[Category("WebApi")]
public static void CreateFolderUrl()
{
var url = "https://www.googleapis.com/drive/v2/files?supportsTeamDrives=true";
Assert.AreEqual(url, GoogleDrive.CreateFolderUrl(true));
}
[Test]
[Category("WebApi")]
public static void AboutInfoUrl()
{
var url = "https://www.googleapis.com/drive/v2/about";
Assert.AreEqual(url, GoogleDrive.AboutInfoUrl());
}
}
}
| lgpl-2.1 | C# |
e688044f7660d59749ffcec8bbadc9ac8bef32a6 | Add ReadScalar extensions to IDbConnection | vjacquet/WmcSoft | WmcSoft.Core/Data/DbConnectionExtensions.cs | WmcSoft.Core/Data/DbConnectionExtensions.cs | #region Licence
/****************************************************************************
Copyright 1999-2015 Vincent J. Jacquet. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
****************************************************************************/
#endregion
using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
namespace WmcSoft.Data.Common
{
public static class DbConnectionExtensions
{
public static DbConnection OpenConnection(this ConnectionStringSettings connectionStringSettings) {
var factory = DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);
var connection = factory.CreateConnection();
connection.ConnectionString = connectionStringSettings.ConnectionString;
connection.Open();
return connection;
}
public static IDbCommand CreateCommand(this IDbConnection connection, string commandText, CommandType commandType = CommandType.Text, TimeSpan? timeout = null, IDbTransaction transaction = null, object parameters = null) {
var command = connection.CreateCommand();
command.CommandType = commandType;
command.CommandText = commandText;
command.Transaction = transaction;
command.AddReflectedParameters(parameters);
if (timeout != null) {
command.CommandTimeout = (int)Math.Max(timeout.GetValueOrDefault().TotalSeconds, 1d);
}
return command;
}
public static T ReadScalar<T>(this IDbConnection connection, string commandText, CommandType commandType = CommandType.Text, TimeSpan? timeout = null, IDbTransaction transaction = null, object parameters = null) {
using (var command = connection.CreateCommand(commandText, commandType, timeout, transaction, parameters)) {
var result = command.ExecuteScalar();
return (T)Convert.ChangeType(result, typeof(T));
}
}
public static T ReadScalarOrDefault<T>(this IDbConnection connection, string commandText, CommandType commandType = CommandType.Text, TimeSpan? timeout = null, IDbTransaction transaction = null, object parameters = null) {
using (var command = connection.CreateCommand(commandText, commandType, timeout, transaction, parameters)) {
var result = command.ExecuteScalar();
if (result == null || DBNull.Value.Equals(result))
return default(T);
return (T)Convert.ChangeType(result, typeof(T));
}
}
public static T? ReadNullableScalar<T>(this IDbConnection connection, string commandText, CommandType commandType = CommandType.Text, TimeSpan? timeout = null, IDbTransaction transaction = null, object parameters = null) where T : struct {
using (var command = connection.CreateCommand(commandText, commandType, timeout, transaction, parameters)) {
var result = command.ExecuteScalar();
if (result == null || DBNull.Value.Equals(result))
return null;
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
}
| #region Licence
/****************************************************************************
Copyright 1999-2015 Vincent J. Jacquet. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
****************************************************************************/
#endregion
using System.Configuration;
using System.Data;
using System.Data.Common;
namespace WmcSoft.Data.Common
{
public static class DbConnectionExtensions
{
public static IDbConnection OpenConnection(this ConnectionStringSettings connectionStringSettings) {
var factory = DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);
var connection = factory.CreateConnection();
connection.ConnectionString = connectionStringSettings.ConnectionString;
connection.Open();
return connection;
}
}
}
| mit | C# |
be1da07b4fba9fc6bd34a299668cfd7dcb13fb17 | Update GameStateManager with basic game flow | ChrisMa130/SpellCraft,ChrisMa130/SpellCraft | Assets/Scripts/GameState/GameStateManager.cs | Assets/Scripts/GameState/GameStateManager.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameStateManager : MonoBehaviour {
public GameObject player;
public GameObject manager;
public bool gameStarted;
// define possible game states
public enum GameStatus
{
Start,
Waiting,
Playing,
Loses,
End
}
public GameStatus currentState = GameStatus.Start;
// store corresponding Scenes/UI for each game state
public GameObject waitingCanvas;
public GameObject inGameCanvas;
public GameObject winnerCanvas;
public GameObject loserCanvas;
public GameObject restartButton;
void start() {
gameStarted = false;
// Manager need to have tag "Manager"
if (manager == null)
manager = GameObject.FindWithTag("Manager");
// Player is the "Main Camera"
if (player == null)
player = GameObject.FindWithTag("Main Camera")
// set game-over canvases as inactive
waitingCanvas.SetActive(true);
inGameCanvas.SetActive(false);
winnerCanvas.SetActive(false);
loserCanvas.SetActive(false);
restartButton.SetActive(false);
// set current status to waiting (for multi-player connections)
currentState = GameStatus.Waiting;
}
void update() {
switch(currentState)
{
/** Waiting: waiting for one of more players to connect.
***** player should click "Start" button to switch state to playing
***** need a seperate button script
*/
case GameStatus.Waiting:
if (gameStarted) {
waitingCanvas.SetActive(false);
inGameCanvas.SetActive(true);
}
break;
/** Playing: game started. While player is alive, simultaneously
check on all players' life status. If player is not alive,
swtich game state to Loses. If all other player died ahead of
time, then this player won.
**/
case GameStatus.Playing:
// Player is alive
if (player.GetComponent<Player>().alive){
/* Looks like PickUpManager will take care of spawning
if (isPrimary()) {
PrepareOrbs();
}
*/
// all other player died
if () {
inGameCanvas.SetActive(false);
winnerCanvas.SetActive(true);
currentState = GameStatus.End;
}
}
// Player is dead
else {
inGameCanvas.SetActive(false);
loserCanvas.SetActive(true);
CustomMessages.Instance.SendDeathMessage();
currentState = GameStatus.Loses;
}
break;
// Player lost and waiting for other players to finish.
case GameStatus.Loses:
if ( /* all players are finished */ ) {
currentState = GameStatus.End;
}
break;
// All players are finished. Prompt for restart.
case GameStatus.End:
restartButton.SetActive(true);
break;
}
}
void isPrimary(){
Manager.GetComponent<CustomMessages>().isPrimary();
}
// call spawning method in OrbManager
void PrepareOrbs() {
// might not need this method
}
// call UIManager to switch to In-Game Scene
void StartGame() {
}
| using UnityEngine;
using System.Collections;
public class GameStateManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit | C# |
f9b2ec8c6d5145c701f42e9456d9b23d89c4bdac | Build script correction | bt-skyrise/OrionLib | Build/build.cake | Build/build.cake | var target = Argument("target", "Default");
var slnPath = "../Source/Orion.Lib.sln";
var nugerPackagesOutputPath = "../Nuget";
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore(slnPath);
});
Task("Clean")
.Does(() =>
{
CleanDirectories("../Source/**/bin");
CleanDirectories("../Source/**/obj");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
MSBuild(slnPath, settings => settings.SetConfiguration("Release"));
});
Task("Create-NuGet-Package")
.IsDependentOn("Build")
.Does(() =>
{
CreateDirectory(nugerPackagesOutputPath);
NuGetPack("../Source/OrionLib/OrionLib.csproj", new NuGetPackSettings
{
Authors = new[] {"Ryszard Tarajkowski, Damian Krychowski"},
Owners = new[] {"Parkanizer"},
OutputDirectory = nugerPackagesOutputPath,
Version = EnvironmentVariable("APPVEYOR_BUILD_VERSION"),
IncludeReferencedProjects = true,
ArgumentCustomization = args => args.Append("-Prop Configuration=Release")
});
});
Task("Push-NuGet-Package")
.IsDependentOn("Create-NuGet-Package")
.Does(() =>
{
var allNugetPackages = GetFiles(nugerPackagesOutputPath + "/*.nupkg");
foreach(var nugetPackage in allNugetPackages)
{
NuGetPush(nugetPackage, new NuGetPushSettings
{
Source = "https://nuget.org/",
ApiKey = EnvironmentVariable("NUGET_API_KEY")
});
}
});
Task("Default")
.IsDependentOn("Push-NuGet-Package")
.Does(() =>
{
Information("Orion.Lib building finished.");
});
RunTarget(target); | var target = Argument("target", "Default");
var slnPath = "../Source/Orion.Lib.sln";
var nugerPackagesOutputPath = "../Nuget";
Task("Restore-NuGet-Packages")
.Does(() =>
{
NuGetRestore(slnPath);
});
Task("Clean")
.Does(() =>
{
CleanDirectories("../Source/**/bin");
CleanDirectories("../Source/**/obj");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
MSBuild(slnPath, settings => settings.SetConfiguration("Release"));
});
Task("Create-NuGet-Package")
.IsDependentOn("Build")
.Does(() =>
{
CreateDirectory(nugerPackagesOutputPath);
NuGetPack("../Source/OrionLib/OrionLib.csproj", new NuGetPackSettings
{
OutputDirectory = nugerPackagesOutputPath,
Version = EnvironmentVariable("APPVEYOR_BUILD_VERSION"),
IncludeReferencedProjects = true,
ArgumentCustomization = args => args.Append("-Prop Configuration=Release")
});
});
Task("Push-NuGet-Package")
.IsDependentOn("Create-NuGet-Package")
.Does(() =>
{
var allNugetPackages = GetFiles(nugerPackagesOutputPath + "/*.nupkg");
foreach(var nugetPackage in allNugetPackages)
{
NuGetPush(nugetPackage, new NuGetPushSettings
{
Authors = new[] {"Ryszard Tarajkowski, Damian Krychowski"},
Owners = new[] {"Parkanizer"},
Source = "https://nuget.org/",
ApiKey = EnvironmentVariable("NUGET_API_KEY")
});
}
});
Task("Default")
.IsDependentOn("Push-NuGet-Package")
.Does(() =>
{
Information("Orion.Lib building finished.");
});
RunTarget(target); | mit | C# |
6bbd0ecfac9fc77ae680064ec61b29f2409380e8 | Remove unused lock object | ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,peppy/osu,peppy/osu-new | osu.Game/Online/Multiplayer/MultiplayerRoom.cs | osu.Game/Online/Multiplayer/MultiplayerRoom.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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json;
using osu.Framework.Allocation;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// A multiplayer room.
/// </summary>
[Serializable]
public class MultiplayerRoom
{
/// <summary>
/// The ID of the room, used for database persistence.
/// </summary>
public readonly long RoomID;
/// <summary>
/// The current state of the room (ie. whether it is in progress or otherwise).
/// </summary>
public MultiplayerRoomState State { get; set; }
/// <summary>
/// All currently enforced game settings for this room.
/// </summary>
public MultiplayerRoomSettings Settings { get; set; } = new MultiplayerRoomSettings();
/// <summary>
/// All users currently in this room.
/// </summary>
public List<MultiplayerRoomUser> Users { get; set; } = new List<MultiplayerRoomUser>();
/// <summary>
/// The host of this room, in control of changing room settings.
/// </summary>
public MultiplayerRoomUser? Host { get; set; }
[JsonConstructor]
public MultiplayerRoom(in long roomId)
{
RoomID = roomId;
}
private object updateLock = new object();
private ManualResetEventSlim freeForWrite = new ManualResetEventSlim(true);
/// <summary>
/// Request a lock on this room to perform a thread-safe update.
/// </summary>
public IDisposable LockForUpdate()
{
// ReSharper disable once InconsistentlySynchronizedField
freeForWrite.Wait();
lock (updateLock)
{
freeForWrite.Wait();
freeForWrite.Reset();
return new ValueInvokeOnDisposal<MultiplayerRoom>(this, r => freeForWrite.Set());
}
}
public override string ToString() => $"RoomID:{RoomID} Host:{Host?.UserID} Users:{Users.Count} State:{State} Settings: [{Settings}]";
}
}
| // 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json;
using osu.Framework.Allocation;
namespace osu.Game.Online.Multiplayer
{
/// <summary>
/// A multiplayer room.
/// </summary>
[Serializable]
public class MultiplayerRoom
{
/// <summary>
/// The ID of the room, used for database persistence.
/// </summary>
public readonly long RoomID;
/// <summary>
/// The current state of the room (ie. whether it is in progress or otherwise).
/// </summary>
public MultiplayerRoomState State { get; set; }
/// <summary>
/// All currently enforced game settings for this room.
/// </summary>
public MultiplayerRoomSettings Settings { get; set; } = new MultiplayerRoomSettings();
/// <summary>
/// All users currently in this room.
/// </summary>
public List<MultiplayerRoomUser> Users { get; set; } = new List<MultiplayerRoomUser>();
/// <summary>
/// The host of this room, in control of changing room settings.
/// </summary>
public MultiplayerRoomUser? Host { get; set; }
private object writeLock = new object();
[JsonConstructor]
public MultiplayerRoom(in long roomId)
{
RoomID = roomId;
}
private object updateLock = new object();
private ManualResetEventSlim freeForWrite = new ManualResetEventSlim(true);
/// <summary>
/// Request a lock on this room to perform a thread-safe update.
/// </summary>
public IDisposable LockForUpdate()
{
// ReSharper disable once InconsistentlySynchronizedField
freeForWrite.Wait();
lock (updateLock)
{
freeForWrite.Wait();
freeForWrite.Reset();
return new ValueInvokeOnDisposal<MultiplayerRoom>(this, r => freeForWrite.Set());
}
}
public override string ToString() => $"RoomID:{RoomID} Host:{Host?.UserID} Users:{Users.Count} State:{State} Settings: [{Settings}]";
}
}
| mit | C# |
baceadb0bda88f48c77d8595ffe266a8642a01f4 | tweak to system message regex | thesmallbang/EverquestOpenParser | OpenParser/Constants/Misc.cs | OpenParser/Constants/Misc.cs | namespace OpenParser.Constants
{
public static class Misc
{
public const string FactionRegex =
@"\AYour faction standing with (.+?) (has been adjusted by (-?)(.+)|could not possibly get any (better|worse)).$";
public const string ExperienceRegex = @"\AYou gain (?:(party) )?experience!!$";
public const string SpellWoreRegex = @"\AYour (.+?) spell has worn off.$";
public const string SystemMessageRegex = @"\A<SYSTEMWIDE_MESSAGE>: ?(.+?)$";
}
} | namespace OpenParser.Constants
{
public static class Misc
{
public const string FactionRegex =
@"\AYour faction standing with (.+?) (has been adjusted by (-?)(.+)|could not possibly get any (better|worse)).$";
public const string ExperienceRegex = @"\AYou gain (?:(party) )?experience!!$";
public const string SpellWoreRegex = @"\AYour (.+?) spell has worn off.$";
public const string SystemMessageRegex = @"\A<SYSTEMWIDE_MESSAGE>: (.+?)$";
}
} | mit | C# |
cea145b7fa24e1883d468e36353610f16b90a610 | Update WeaponThrow.cs | Notulp/Pluton,Notulp/Pluton | Pluton/Events/WeaponThrow.cs | Pluton/Events/WeaponThrow.cs | namespace Pluton.Events
{
public class WeaponThrow : CountedInstance
{
private ThrownWeapon _w;
private BaseEntity.RPCMessage _msg;
private Player _player;
public WeaponThrow(ThrownWeapon thrownWeapon, BaseEntity.RPCMessage msg)
{
this._msg = msg;
this._w = thrownWeapon;
this._player = new Player(msg.player);
}
public BaseEntity.RPCMessage RPCMessage
{
get { return this._msg; }
}
public ThrownWeapon Weapon
{
get { return this._w; }
}
public Player Player
{
get { return this._player; }
}
}
}
|
namespace Pluton.Events
{
public class WeaponThrow
{
private ThrownWeapon _w;
private BaseEntity.RPCMessage _msg;
private Player _player;
public WeaponThrow(ThrownWeapon thrownWeapon, BaseEntity.RPCMessage msg)
{
this._msg = msg;
this._w = thrownWeapon;
this._player = new Player(msg.player);
}
public BaseEntity.RPCMessage RPCMessage
{
get { return this._msg; }
}
public ThrownWeapon Weapon
{
get { return this._w; }
}
public Player Player
{
get { return this._player; }
}
}
}
| mit | C# |
4aebb587bb80bbca68fdd856cf200d39eb4c4442 | add a new element type | patrickpissurno/samecitysameshit | GGJ2016/Assets/Scripts/Domain/ElementType.cs | GGJ2016/Assets/Scripts/Domain/ElementType.cs | using UnityEngine;
using System.Collections;
public enum ElementType {
Player,
Taxi,
Rebu,
RebuBG,
Bike,
Metro,
Limit
}
| using UnityEngine;
using System.Collections;
public enum ElementType {
Player,
Taxi,
Rebu,
Bike,
Metro,
Limit
}
| cc0-1.0 | C# |
2188c50ee44b4b42a5d27c0342776364ecb30413 | Add missing copyright header text. | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.Services/InputSystem/DefaultRaycastProvider.cs | Assets/MixedRealityToolkit.Services/InputSystem/DefaultRaycastProvider.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Physics;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// The default implementation of IMixedRealityRaycastProvider.
/// </summary>
public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider
{
public DefaultRaycastProvider(
IMixedRealityServiceRegistrar registrar,
IMixedRealityInputSystem inputSystem,
MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile)
{ }
/// <inheritdoc />
public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo)
{
var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit);
hitInfo = new MixedRealityRaycastHit(physicsHit);
return result;
}
/// <inheritdoc />
public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo)
{
var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit);
hitInfo = new MixedRealityRaycastHit(physicsHit);
return result;
}
}
}
| using Microsoft.MixedReality.Toolkit.Physics;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// The default implementation of IMixedRealityRaycastProvider.
/// </summary>
public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider
{
public DefaultRaycastProvider(
IMixedRealityServiceRegistrar registrar,
IMixedRealityInputSystem inputSystem,
MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile)
{ }
/// <inheritdoc />
public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo)
{
var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit);
hitInfo = new MixedRealityRaycastHit(physicsHit);
return result;
}
/// <inheritdoc />
public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo)
{
var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit);
hitInfo = new MixedRealityRaycastHit(physicsHit);
return result;
}
}
}
| mit | C# |
ca378d1f9994bee331907edd97130794ff783759 | Add a test for a simple method call | gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib.Tests/TypeHandlers/ROOT/TypeHanlderROOTTest.cs | LINQToTTree/LINQToTTreeLib.Tests/TypeHandlers/ROOT/TypeHanlderROOTTest.cs | // <copyright file="TypeHanlderROOTTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright>
using System;
using System.Linq.Expressions;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Tests;
using LINQToTTreeLib.Utils;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.TypeHandlers.ROOT
{
/// <summary>This class contains parameterized unit tests for TypeHanlderROOT</summary>
[PexClass(typeof(TypeHandlerROOT))]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class TypeHanlderROOTTest
{
[TestInitialize]
public void Setup()
{
MEFUtilities.MyClassInit();
MEFUtilities.AddPart(new QVResultOperators());
MEFUtilities.Compose(new TypeHandlerCache());
}
[TestCleanup]
public void Cleanup()
{
MEFUtilities.MyClassDone();
}
/// <summary>Test stub for CanHandle(Type)</summary>
[PexMethod]
public bool CanHandle([PexAssumeUnderTest]TypeHandlerROOT target, Type t)
{
bool result = target.CanHandle(t);
return result;
// TODO: add assertions to method TypeHanlderROOTTest.CanHandle(TypeHanlderROOT, Type)
}
/// <summary>Test stub for ProcessConstantReference(ConstantExpression, IGeneratedCode)</summary>
[PexMethod]
public IValue ProcessConstantReference(
[PexAssumeUnderTest]TypeHandlerROOT target,
[PexAssumeNotNull] ConstantExpression expr,
[PexAssumeNotNull] IGeneratedCode codeEnv
)
{
IValue result = target.ProcessConstantReference(expr, codeEnv, null, null);
Assert.IsNotNull(result);
return result;
}
[TestMethod]
public void TestROOTMethodReference()
{
var expr = Expression.Variable(typeof(ROOTNET.NTH1F), "myvar");
var getEntriesMethod = typeof(ROOTNET.NTH1F).GetMethod("GetEntries", new Type[0]);
var theCall = Expression.Call(expr, getEntriesMethod);
var target = new TypeHandlerROOT();
IValue resultOfCall;
var gc = new GeneratedCode();
var cc = new CodeContext();
var returned = target.ProcessMethodCall(theCall, out resultOfCall, gc, cc, MEFUtilities.MEFContainer);
Assert.AreEqual("(*myvar).GetEntries()", resultOfCall.RawValue, "call is incorrect");
}
}
}
| // <copyright file="TypeHanlderROOTTest.cs" company="Microsoft">Copyright Microsoft 2010</copyright>
using System;
using System.Linq.Expressions;
using LinqToTTreeInterfacesLib;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.TypeHandlers.ROOT
{
/// <summary>This class contains parameterized unit tests for TypeHanlderROOT</summary>
[PexClass(typeof(TypeHandlerROOT))]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class TypeHanlderROOTTest
{
/// <summary>Test stub for CanHandle(Type)</summary>
[PexMethod]
public bool CanHandle([PexAssumeUnderTest]TypeHandlerROOT target, Type t)
{
bool result = target.CanHandle(t);
return result;
// TODO: add assertions to method TypeHanlderROOTTest.CanHandle(TypeHanlderROOT, Type)
}
/// <summary>Test stub for ProcessConstantReference(ConstantExpression, IGeneratedCode)</summary>
[PexMethod]
public IValue ProcessConstantReference(
[PexAssumeUnderTest]TypeHandlerROOT target,
[PexAssumeNotNull] ConstantExpression expr,
[PexAssumeNotNull] IGeneratedCode codeEnv
)
{
IValue result = target.ProcessConstantReference(expr, codeEnv, null, null);
Assert.IsNotNull(result);
return result;
}
}
}
| lgpl-2.1 | C# |
743eb959820a55643805d1ef4d5ef19ef6194526 | Fix NoContentChangedOnLoad - skip load if null | jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl | Library/Providers/FileSystem/McxContainer.cs | Library/Providers/FileSystem/McxContainer.cs | /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MatterHackers.DataConverters3D;
namespace MatterHackers.MatterControl.Library
{
public class McxContainer : LibraryContainer
{
private IObject3D sourceItem;
public McxContainer()
{
}
public McxContainer(ILibraryAsset libraryAsset)
{
sourceItem = libraryAsset.CreateContent(null).Result;
this.Name = sourceItem.Name;
}
public override void Load()
{
try
{
this.ChildContainers = new List<ILibraryContainerLink>();
if (sourceItem != null)
{
this.Items = sourceItem.Children.Select(m => new InMemoryLibraryItem(m)).ToList<ILibraryItem>();
}
}
catch (Exception ex)
{
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = new List<ILibraryItem>()
{
new MessageItem("Error loading container - " + ex.Message)
};
}
}
}
}
| /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MatterHackers.DataConverters3D;
namespace MatterHackers.MatterControl.Library
{
public class McxContainer : LibraryContainer
{
private IObject3D sourceItem;
public McxContainer()
{
}
public McxContainer(ILibraryAsset libraryAsset)
{
sourceItem = libraryAsset.CreateContent(null).Result;
this.Name = sourceItem.Name;
}
public override void Load()
{
try
{
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = sourceItem.Children.Select(m => new InMemoryLibraryItem(m)).ToList<ILibraryItem>();
}
catch (Exception ex)
{
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = new List<ILibraryItem>()
{
new MessageItem("Error loading container - " + ex.Message)
};
}
}
}
}
| bsd-2-clause | C# |
a5e7002ddc42771fc84c71aa629b8942eb505e4d | Test is inconvenient | Fubineva/NOps.Instance | NOps.Instance.Tests/InstanceRegistryTests.cs | NOps.Instance.Tests/InstanceRegistryTests.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Fubineva.NOps.Instance;
using NUnit.Framework;
namespace NOps.Instance.Tests
{
[TestFixture]
public class InstanceRegistryTests
{
// ToDo: Test this some other way...
[Test]
[Explicit("The file often does exist and I want to keep it...")]
public void NoRegistryFile_should_throw()
{
// arrange
// act
try
{
var result = InstanceRegistry.Current;
}
catch (FileNotFoundException ex)
{
var expectedPathString = Path.GetFullPath(Path.Combine(GetAppDir(), "..\\..\\.."));
Assert.That(ex.FileName.Contains(expectedPathString), "Expected on the exception: " + ex.FileName);
return;
}
// assert
Assert.Fail("Expected an exception.");
}
private static string GetAppDir()
{
var dir = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
return Path.GetDirectoryName(dir);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Fubineva.NOps.Instance;
using NUnit.Framework;
namespace NOps.Instance.Tests
{
[TestFixture]
public class InstanceRegistryTests
{
[Test]
public void NoRegistryFile_should_throw()
{
// arrange
// act
try
{
var result = InstanceRegistry.Current;
}
catch (FileNotFoundException ex)
{
var expectedPathString = Path.GetFullPath(Path.Combine(GetAppDir(), "..\\..\\.."));
Assert.That(ex.FileName.Contains(expectedPathString), "Expected on the exception: " + ex.FileName);
return;
}
// assert
Assert.Fail("Expected an exception.");
}
private static string GetAppDir()
{
var dir = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
return Path.GetDirectoryName(dir);
}
}
}
| mit | C# |
64cbb1df1720a49dfdd1884024a3aabaa9f5815c | Bump to v2.8.0.0 | Silv3rPRO/proshine | PROShine/Properties/AssemblyInfo.cs | PROShine/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// 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("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.8.0.0")]
[assembly: AssemblyFileVersion("2.8.0.0")]
[assembly: NeutralResourcesLanguage("en")]
| using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// 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("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.7.2.0")]
[assembly: AssemblyFileVersion("2.7.2.0")]
[assembly: NeutralResourcesLanguage("en")]
| mit | C# |
4147336a0a2876383007f8c9b0eb0d14d3862f99 | Fix for issue #362 | johnkors/azure-sdk-tools,DinoV/azure-sdk-tools,antonba/azure-sdk-tools,johnkors/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools,johnkors/azure-sdk-tools,akromm/azure-sdk-tools,hyonholee/azure-sdk-tools-1,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,hyonholee/azure-sdk-tools-1,markcowl/azure-sdk-tools,alpon/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools,alpon/azure-sdk-tools,johnkors/azure-sdk-tools,Madhukarc/azure-sdk-tools,markcowl/azure-sdk-tools,antonba/azure-sdk-tools,alpon/azure-sdk-tools,hyonholee/azure-sdk-tools-1,johnkors/azure-sdk-tools,alpon/azure-sdk-tools,antonba/azure-sdk-tools,markcowl/azure-sdk-tools,antonba/azure-sdk-tools,hyonholee/azure-sdk-tools-1,Madhukarc/azure-sdk-tools,antonba/azure-sdk-tools,hyonholee/azure-sdk-tools-1,Madhukarc/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,alpon/azure-sdk-tools | WindowsAzurePowershell/src/Management/Utilities/ConfigurationConstants.cs | WindowsAzurePowershell/src/Management/Utilities/ConfigurationConstants.cs | // ----------------------------------------------------------------------------------
//
// Copyright 2011 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities
{
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
public static class ConfigurationConstants
{
public const string ServiceManagementEndpoint = "https://management.core.windows.net";
public static Binding WebHttpBinding(int maxStringContentLength)
{
var binding = new WebHttpBinding(WebHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
binding.ReaderQuotas.MaxStringContentLength =
maxStringContentLength > 0 ?
maxStringContentLength :
67108864;
binding.MaxReceivedMessageSize = Int64.MaxValue;
return binding;
}
}
} | // ----------------------------------------------------------------------------------
//
// Copyright 2011 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities
{
using System.ServiceModel;
using System.ServiceModel.Channels;
public static class ConfigurationConstants
{
public const string ServiceManagementEndpoint = "https://management.core.windows.net";
public static Binding WebHttpBinding(int maxStringContentLength)
{
var binding = new WebHttpBinding(WebHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
binding.ReaderQuotas.MaxStringContentLength =
maxStringContentLength > 0 ?
maxStringContentLength :
67108864;
return binding;
}
}
} | apache-2.0 | C# |
04446b0633116305a02376c0787526467be409db | Save trip before dismissing summary. | Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving | XamarinApp/MyTrips/MyTrips.iOS/Screens/Trips/TripSummaryViewController.cs | XamarinApp/MyTrips/MyTrips.iOS/Screens/Trips/TripSummaryViewController.cs | using System;
using UIKit;
namespace MyTrips.iOS
{
public partial class TripSummaryViewController : UIViewController
{
public ViewModel.CurrentTripViewModel ViewModel { get; set; }
public TripSummaryViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}";
lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}";
lblDuration.Text = ViewModel.ElapsedTime;
lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}";
lblDistance.Alpha = 0;
lblDuration.Alpha = 0;
lblTopSpeed.Alpha = 0;
lblFuelConsumed.Alpha = 0;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
lblDistance.FadeIn(0.4, 0.1f);
lblDuration.FadeIn(0.4, 0.2f);
lblTopSpeed.FadeIn(0.4, 0.3f);
lblFuelConsumed.FadeIn(0.4, 0.4f);
}
async partial void BtnClose_TouchUpInside(UIButton sender)
{
await ViewModel.SaveRecordingTripAsync();
await DismissViewControllerAsync(true);
}
}
} | using System;
using UIKit;
namespace MyTrips.iOS
{
public partial class TripSummaryViewController : UIViewController
{
public ViewModel.CurrentTripViewModel ViewModel { get; set; }
public TripSummaryViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}";
lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}";
lblDuration.Text = ViewModel.ElapsedTime;
lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}";
lblDistance.Alpha = 0;
lblDuration.Alpha = 0;
lblTopSpeed.Alpha = 0;
lblFuelConsumed.Alpha = 0;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
lblDistance.FadeIn(0.4, 0.1f);
lblDuration.FadeIn(0.4, 0.2f);
lblTopSpeed.FadeIn(0.4, 0.3f);
lblFuelConsumed.FadeIn(0.4, 0.4f);
}
async partial void BtnClose_TouchUpInside(UIButton sender)
{
await DismissViewControllerAsync(true);
await ViewModel.SaveRecordingTripAsync();
}
}
} | mit | C# |
d5b08201b646221275e056612f466b4f9c6fe179 | add link.Title to aria-label | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Views/stockportgov/Shared/Semantic/Showcase/SocialMediaLinks.cshtml | src/StockportWebapp/Views/stockportgov/Shared/Semantic/Showcase/SocialMediaLinks.cshtml | @model StockportWebapp.ViewModels.SocialMediaLinksViewModel
<section>
<h2>@Model.SocialMediaLinksSubheading</h2>
<div class="showcase-button-container">
@foreach (var link in Model.SocialMediaLinks)
{
<a as-link="true" class="showcase-button" href="@link.Url">
<span class="@link.Icon fa 2x" aria-label="@link.Title"></span>
<span aria-hidden="true">@link.Title</span>
</a>
}
</div>
</section>
| @model StockportWebapp.ViewModels.SocialMediaLinksViewModel
<section>
<h2>@Model.SocialMediaLinksSubheading</h2>
<div class="showcase-button-container">
@foreach (var link in Model.SocialMediaLinks)
{
<a as-link="true" class="showcase-button" href="@link.Url">
<span class="@link.Icon fa 2x" aria-hidden="true"></span>
<span>@link.Title</span>
</a>
}
</div>
</section>
| mit | C# |
933ebbca5630c8c8aeb9f44df9bad7634823540a | Fix quotes symbols in contacts | ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/fornever.me | ForneverMind/views/Contact.cshtml | ForneverMind/views/Contact.cshtml | @using RazorEngine.Templating
@inherits TemplateBase
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Контакты";
}
<p>
<a class="so-badge" href="http://stackoverflow.com/users/2684760/fornever">
<img src="http://stackoverflow.com/users/flair/2684760.png"
width="208"
height="58"
alt="мой профиль на Stack Overflow"
title="мой профиль на Stack Overflow" />
</a>
</p>
<p>Я в «социальных» сетях:</p>
<ul>
<li><a href="https://github.com/ForNeVeR">GitHub</a></li>
<li><a href="https://bitbucket.org/ForNeVeR">Bitbucket</a></li>
<li><a href="https://twitter.com/fvnever">Twitter</a></li>
</ul>
<p>На Хабрахабре: <a href="http://habrahabr.ru/users/ForNeVeR/">ForNeVeR</a>.</p>
<p>
Пишите мне по почте (<a href="mailto:friedrich@fornever.me"
class="email">friedrich@fornever.me</a>) или в
Jabber
(<a href="xmpp:fornever@codingteam.org.ru">fornever@codingteam.org.ru</a>).
</p>
<p>
Меня проще всего найти в нашем XMPP-сообществе:
<a href="xmpp:codingteam@conference.jabber.ru">codingteam@conference.jabber.ru</a>.
</p>
| @using RazorEngine.Templating
@inherits TemplateBase
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Контакты";
}
<p>
<a class="so-badge" href="http://stackoverflow.com/users/2684760/fornever">
<img src="http://stackoverflow.com/users/flair/2684760.png"
width="208"
height="58"
alt="мой профиль на Stack Overflow"
title="мой профиль на Stack Overflow" />
</a>
</p>
<p>Я в “социальных” сетях:</p>
<ul>
<li><a href="https://github.com/ForNeVeR">GitHub</a></li>
<li><a href="https://bitbucket.org/ForNeVeR">Bitbucket</a></li>
<li><a href="https://twitter.com/fvnever">Twitter</a></li>
</ul>
<p>На Хабрахабре: <a href="http://habrahabr.ru/users/ForNeVeR/">ForNeVeR</a>.</p>
<p>
Пишите мне по почте (<a href="mailto:friedrich@fornever.me"
class="email">friedrich@fornever.me</a>) или в
Jabber
(<a href="xmpp:fornever@codingteam.org.ru">fornever@codingteam.org.ru</a>).
</p>
<p>
Меня проще всего найти в нашем XMPP-сообществе:
<a href="xmpp:codingteam@conference.jabber.ru">codingteam@conference.jabber.ru</a>.
</p>
| mit | C# |
9141c54138bfb13eef6f2a14aff41620c55052d8 | Update to versión 1.7.0 | hossmi/qtfk | QTFK.DBMigrations/Properties/AssemblyInfo.cs | QTFK.DBMigrations/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("QTFK.DBMigrations")]
[assembly: AssemblyDescription("Quick Tools for Funny Database Koding")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Blacksmith Projects")]
[assembly: AssemblyProduct("QTFK.DBMigrations")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("200f8a2c-e9f3-42a9-b813-339083a77344")]
// 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: AssemblyInformationalVersion("1.7.0")]
[assembly: AssemblyFileVersion("1.7.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("QTFK.DBMigrations")]
[assembly: AssemblyDescription("Quick Tools for Funny Database Koding")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Blacksmith Projects")]
[assembly: AssemblyProduct("QTFK.DBMigrations")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("200f8a2c-e9f3-42a9-b813-339083a77344")]
// 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: AssemblyInformationalVersion("1.6.3")]
[assembly: AssemblyFileVersion("1.6.3")]
| mit | C# |
2086025ebd3d5df8548fda2035a357b6bf8fdc86 | Update NotifyArgs.cs | gsp8181/FairExchange | FEClient/API/NotifyArgs.cs | FEClient/API/NotifyArgs.cs | using System;
namespace FEClient.API
{
[Obsolete] //TODO: transition
public class NotifyArgs
{
public bool HasSet { get; set; }
}
}
| using System;
namespace FEClient.API
{
[Obsolete]
public class NotifyArgs
{
public bool HasSet { get; set; }
}
} | apache-2.0 | C# |
80883df9674abf036715c3904739065de93f2e22 | Update SNOMED link | endeavourhealth/FHIR-Tools,endeavourhealth/FHIR-Tools,endeavourhealth/FHIR-Tools | FhirProfilePublisher/FhirProfilePublisher.Specification/Utilities/Snomed/SnomedHelper.cs | FhirProfilePublisher/FhirProfilePublisher.Specification/Utilities/Snomed/SnomedHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FhirProfilePublisher.Engine
{
public static class SnomedHelper
{
public static bool IsSnomedSystemUri(string uri)
{
return uri.ToLower().Contains("snomed.info/sct");
}
public static string GetBrowserUrl()
{
return GetBrowserUrl("138875005");
}
public static string GetBrowserUrl(string conceptId)
{
string release = "v20161001";
string langRefSet = "900000000000508004";
return string.Format("http://browser.ihtsdotools.org/?perspective=full&conceptId1={0}&edition=uk-edition&acceptLicense=true&release={1}&server=https://prod-browser-exten.ihtsdotools.org/api/snomed&langRefset={2}", conceptId, release, langRefSet);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FhirProfilePublisher.Engine
{
public static class SnomedHelper
{
public static bool IsSnomedSystemUri(string uri)
{
return uri.ToLower().Contains("snomed.info/sct");
}
public static string GetBrowserUrl()
{
return GetBrowserUrl("138875005");
}
public static string GetBrowserUrl(string conceptId)
{
return string.Format(@"http://browser.ihtsdotools.org/?perspective=full&conceptId1={0}&acceptLicense=true&edition=uk-edition&release=v20151001&server=https://browser-aws-1.ihtsdotools.org/&langRefset=999001251000000103", conceptId);
}
}
}
| apache-2.0 | C# |
04b5f157a2ce9fa43d6b614f51a55a4f921195ba | Remove unseless comment | fredatgithub/InterClubBadminton | InterClubBadminton/FormOptions.cs | InterClubBadminton/FormOptions.cs | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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.Windows.Forms;
namespace InterClubBadminton
{
internal partial class FormOptions : Form
{
internal FormOptions(ConfigurationOptions configurationOptions)
{
if (configurationOptions == null)
{
ConfigurationOptions2 = new ConfigurationOptions();
}
else
{
ConfigurationOptions2 = configurationOptions;
}
InitializeComponent();
checkBoxOption1.Checked = ConfigurationOptions2.Option1Name;
checkBoxOption2.Checked = ConfigurationOptions2.Option2Name;
}
public ConfigurationOptions ConfigurationOptions2 { get; set; }
private void buttonOptionsOK_Click(object sender, EventArgs e)
{
ConfigurationOptions2.Option1Name = checkBoxOption1.Checked;
ConfigurationOptions2.Option2Name = checkBoxOption2.Checked;
Close();
}
private void buttonOptionsCancel_Click(object sender, EventArgs e)
{
Close();
}
private void FormOptions_Load(object sender, EventArgs e)
{
// take care of language
//buttonOptionsCancel.Text = _languageDicoEn["Cancel"];
}
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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.Windows.Forms;
namespace InterClubBadminton
{
internal partial class FormOptions : Form
{
internal FormOptions(ConfigurationOptions configurationOptions)
{
if (configurationOptions == null)
{
//throw new ArgumentNullException(nameof(configurationOptions));
ConfigurationOptions2 = new ConfigurationOptions();
}
else
{
ConfigurationOptions2 = configurationOptions;
}
InitializeComponent();
checkBoxOption1.Checked = ConfigurationOptions2.Option1Name;
checkBoxOption2.Checked = ConfigurationOptions2.Option2Name;
}
internal ConfigurationOptions ConfigurationOptions2 { get; }
private void buttonOptionsOK_Click(object sender, EventArgs e)
{
ConfigurationOptions2.Option1Name = checkBoxOption1.Checked;
ConfigurationOptions2.Option2Name = checkBoxOption2.Checked;
Close();
}
private void buttonOptionsCancel_Click(object sender, EventArgs e)
{
Close();
}
private void FormOptions_Load(object sender, EventArgs e)
{
// take care of language
//buttonOptionsCancel.Text = _languageDicoEn["Cancel"];
}
}
} | mit | C# |
8a8fba0bc7a969569b22ef9d71241645efef3e88 | Update Enum.cs | balarvs2002/FeatureToggle | FeatureToggle.Core/Enum.cs | FeatureToggle.Core/Enum.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FeatureToggle.Core
{
public class Enum
{
public enum ToggleType
{
AlwaysOnFeature,
AlwaysOffFeature,
DateFromFeature,
TillDateFeature,
DateRangeFeature,
UserFeature,
ProfileFeature,
CountryFeature,
ReleaeFeature,
ReleaeFeature2,
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FeatureToggle.Core
{
public class Enum
{
public enum ToggleType
{
AlwaysOnFeature,
AlwaysOffFeature,
DateFromFeature,
TillDateFeature,
DateRangeFeature,
UserFeature,
ProfileFeature,
CountryFeature,
ReleaeFeature,
}
}
}
| apache-2.0 | C# |
830fc7900b5807f10790e0f134313f994f0f0c1e | Fix off by one bug | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Io/MutexIoManager.cs | WalletWasabi/Io/MutexIoManager.cs | using Nito.AsyncEx;
using WalletWasabi.Crypto;
namespace WalletWasabi.Io
{
public class MutexIoManager : IoManager
{
public MutexIoManager(string filePath) : base(filePath)
{
var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(0, 7);
// https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
// On a server that is running Terminal Services, a named system mutex can have two levels of visibility.
// If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions.
// If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created.
// In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server.
// If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\".
// Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes,
// and both are visible to all processes in the terminal server session.
// That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.
Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}");
}
public AsyncMutex Mutex { get; }
}
}
| using Nito.AsyncEx;
using WalletWasabi.Crypto;
namespace WalletWasabi.Io
{
public class MutexIoManager : IoManager
{
public MutexIoManager(string filePath) : base(filePath)
{
var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(1, 7);
// https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
// On a server that is running Terminal Services, a named system mutex can have two levels of visibility.
// If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions.
// If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created.
// In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server.
// If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\".
// Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes,
// and both are visible to all processes in the terminal server session.
// That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.
Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}");
}
public AsyncMutex Mutex { get; }
}
}
| mit | C# |
66ca8c1eb5ce1e89eafa7f4a32650ff74d33725a | Fix argb color parsing, #203 | Kagamia/WzComparerR2 | WzComparerR2.MapRender/UI/ColorWConverter.cs | WzComparerR2.MapRender/UI/ColorWConverter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EmptyKeys.UserInterface.Media;
namespace WzComparerR2.MapRender.UI
{
public class ColorWConverter
{
public static bool TryParse(string s, out ColorW colorW)
{
if (s != null)
{
if (s.Length == 6) //RGB
{
if (uint.TryParse(s, System.Globalization.NumberStyles.HexNumber,null, out uint rgb))
{
colorW = new ColorW((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)(rgb), 0xff);
return true;
}
}
else if (s.Length == 8) //ARGB
{
if (uint.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out uint argb))
{
colorW = new ColorW((byte)(argb >> 16), (byte)(argb >> 8), (byte)(argb), (byte)(argb>>24));
return true;
}
}
}
colorW = ColorW.TransparentBlack;
return false;
}
public static string ToString(ColorW colorW)
{
return colorW.PackedValue.ToString("x8");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EmptyKeys.UserInterface.Media;
namespace WzComparerR2.MapRender.UI
{
public class ColorWConverter
{
public static bool TryParse(string s, out ColorW colorW)
{
if (s != null)
{
if (s.Length == 6) //RGB
{
if (uint.TryParse(s, System.Globalization.NumberStyles.HexNumber,null, out uint rgb))
{
colorW = new ColorW(rgb)
{
A = 255
};
return true;
}
}
else if (s.Length == 8) //ARGB
{
if (uint.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out uint packedValue))
{
colorW = new ColorW(packedValue);
return true;
}
}
}
colorW = ColorW.TransparentBlack;
return false;
}
public static string ToString(ColorW colorW)
{
return colorW.PackedValue.ToString("x8");
}
}
}
| mit | C# |
6c584f82c43c281812c0aab1af74dbae7aa7b25c | refactor then remove netwonsoft references (uneeded), and add interface into ctor for automagic injection | YoloDev/YOBAO | Source/Yobao/YobaoModule.cs | Source/Yobao/YobaoModule.cs | using System.Linq;
using Nancy;
namespace Yobao
{
public class YobaoModule : Nancy.NancyModule
{
public YobaoModule(IYobao<SampleDatabase> yobao)
{
Get["/"] = _ =>
{
return Response.AsJson(yobao.Configurations.ToList());
};
Get["/{type}/list"] = _ =>
{
//ick..
var queryable = yobao.GetQueryable((string)_.type); //todo can we get strongly typed params?
var result = queryable.ToList();
//now with the config for this "type", how can we build an IQueryable to access it?
//we know we have the type that the query is from, and we have the func to run it..
//var result = config.Query.ToList();
return Response.AsJson(result);
};
}
}
} | using System.Linq;
using Newtonsoft.Json;
namespace Yobao
{
public class YobaoModule : Nancy.NancyModule
{
public YobaoModule(Yobao<SampleDatabase> yobao) // push this up to module creation... some how..
{
Get["/"] = _ =>
{
return JsonConvert.SerializeObject(yobao.Configurations.ToList());
};
Get["/{type}/list"] = _ =>
{
//ick..
var queryable = yobao.GetQueryable((string)_.type); //todo can we get strongly typed params?
var result = queryable.ToList();
//now with the config for this "type", how can we build an IQueryable to access it?
//we know we have the type that the query is from, and we have the func to run it..
//var result = config.Query.ToList();
return JsonConvert.SerializeObject(result);
};
}
}
} | mit | C# |
4e460cc258a95ca4aa7bac1448a5e7afd97e5e3e | Add Keyword class | whampson/bft-spec,whampson/cascara | Src/WHampson.Bft/Keyword.cs | Src/WHampson.Bft/Keyword.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
namespace WHampson.Bft
{
internal class Keyword : IEquatable<string>
{
public Keyword(string value)
{
Value = value;
}
public string Value { get; }
public bool Equals(string value)
{
return string.Equals(Value, value);
}
public override bool Equals(object obj)
{
if (!(obj is Keyword))
{
return false;
}
Keyword other = obj as Keyword;
return Equals(other.Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return Value;
}
public static bool operator ==(Keyword a, Keyword b)
{
if ((object) a == null || (object) b == null)
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(Keyword a, Keyword b)
{
return !a.Equals(b);
}
public static implicit operator string(Keyword keyword)
{
return keyword.Value;
}
}
}
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
namespace WHampson.Bft
{
internal class Keyword : IEquatable<string>
{
public Keyword(string value)
{
Value = value;
}
public string Value { get; }
public bool Equals(string value)
{
return string.Equals(Value, value);
}
public override bool Equals(object obj)
{
Keyword other = obj as Keyword;
if (other == null)
{
return false;
}
return Equals(other.Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public static implicit operator string(Keyword keyword)
{
return keyword.Value;
}
}
}
| mit | C# |
bc75bd34f6222c5fa3ccd5678d745700061e10a4 | Fix caret width having changed | 2yangk23/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,EVAST9919/osu | osu.Game/Graphics/UserInterface/OsuTextBox.cs | osu.Game/Graphics/UserInterface/OsuTextBox.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class OsuTextBox : BasicTextBox
{
protected override float LeftRightPadding => 10;
protected override float CaretWidth => 3;
protected override SpriteText CreatePlaceholder() => new OsuSpriteText
{
Font = OsuFont.GetFont(italics: true),
Colour = new Color4(180, 180, 180, 255),
Margin = new MarginPadding { Left = 2 },
};
public OsuTextBox()
{
Height = 40;
TextContainer.Height = 0.5f;
CornerRadius = 5;
LengthLimit = 1000;
Current.DisabledChanged += disabled => { Alpha = disabled ? 0.3f : 1; };
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundUnfocused = Color4.Black.Opacity(0.5f);
BackgroundFocused = OsuColour.Gray(0.3f).Opacity(0.8f);
BackgroundCommit = BorderColour = colour.Yellow;
}
protected override Color4 SelectionColour => new Color4(249, 90, 255, 255);
protected override void OnFocus(FocusEvent e)
{
BorderThickness = 3;
base.OnFocus(e);
}
protected override void OnFocusLost(FocusLostEvent e)
{
BorderThickness = 0;
base.OnFocusLost(e);
}
protected override Drawable GetDrawableCharacter(char c) => new OsuSpriteText { Text = c.ToString(), Font = OsuFont.GetFont(size: CalculatedTextSize) };
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class OsuTextBox : BasicTextBox
{
protected override float LeftRightPadding => 10;
protected override SpriteText CreatePlaceholder() => new OsuSpriteText
{
Font = OsuFont.GetFont(italics: true),
Colour = new Color4(180, 180, 180, 255),
Margin = new MarginPadding { Left = 2 },
};
public OsuTextBox()
{
Height = 40;
TextContainer.Height = 0.5f;
CornerRadius = 5;
LengthLimit = 1000;
Current.DisabledChanged += disabled => { Alpha = disabled ? 0.3f : 1; };
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundUnfocused = Color4.Black.Opacity(0.5f);
BackgroundFocused = OsuColour.Gray(0.3f).Opacity(0.8f);
BackgroundCommit = BorderColour = colour.Yellow;
}
protected override Color4 SelectionColour => new Color4(249, 90, 255, 255);
protected override void OnFocus(FocusEvent e)
{
BorderThickness = 3;
base.OnFocus(e);
}
protected override void OnFocusLost(FocusLostEvent e)
{
BorderThickness = 0;
base.OnFocusLost(e);
}
protected override Drawable GetDrawableCharacter(char c) => new OsuSpriteText { Text = c.ToString(), Font = OsuFont.GetFont(size: CalculatedTextSize) };
}
}
| mit | C# |
318b8a4157b53831e7196671f3f8ede918ca64a4 | Add CollidableRectangle class | McIntireEvan/FusionLib | FusionLib/FusionLib/Shapes/CollidableRectangle.cs | FusionLib/FusionLib/Shapes/CollidableRectangle.cs | using FusionLib.Collision;
using Microsoft.Xna.Framework;
namespace FusionLib.Shapes
{
public class CollidableRectangle : ICollidable
{
private Rectangle rectangle;
public CollidableRectangle(Rectangle rectangle)
{
this.rectangle = rectangle;
}
public Rectangle GetHitbox()
{
return rectangle;
}
public void OnCollision(ICollidable o)
{
}
}
} | mit | C# | |
08e7955daaf5aef63c5d8c0a4a4ea99a93886041 | add Account int BankOfKurtovoKonare | ivayloivanof/OOP.CSharp,ivayloivanof/OOP.CSharp | 04.EncapsulationAndPolymorphism/EncapsulationAndPolimophism/BankOfKurtovoKonare/Class/Accounts.cs | 04.EncapsulationAndPolymorphism/EncapsulationAndPolimophism/BankOfKurtovoKonare/Class/Accounts.cs | namespace BankOfKurtovoKonare.Class
{
class Accounts
{
private string customer;
}
}
| cc0-1.0 | C# | |
aaf8ec3895e548cdf94dbc56b1081644747a6ef7 | Sort chars by freq - monad | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | LeetCode/remote/sort_characters_by_frequency.cs | LeetCode/remote/sort_characters_by_frequency.cs | // https://leetcode.com/problems/sort-characters-by-frequency/
// https://leetcode.com/submissions/detail/83684155/
//
// Submission Details
// 34 / 34 test cases passed.
// Status: Accepted
// Runtime: 188 ms
// Submitted: 0 minutes ago
public class Solution {
public string FrequencySort(string s) {
return s.Aggregate(new Dictionary<char, int>(), (acc, x) => {
if (!acc.ContainsKey(x)) {
acc[x] = 0;
}
acc[x]++;
return acc;
})
.OrderByDescending(x => x.Value)
.Aggregate(new StringBuilder(), (acc, x) => {
acc.Append(new String(x.Key, x.Value));
return acc;
})
.ToString();
}
}
| mit | C# | |
96d3db522b46221b286c484ab010bdba3cb8c07a | Add knownfile.cs | Ackara/Daterpillar | src/Tests.Daterpillar/Globals/KnownFile.cs | src/Tests.Daterpillar/Globals/KnownFile.cs | namespace Tests.Daterpillar.Globals
{
public static class KnownFile
{
public const string XDDL = "xddl.xsd";
public const string x86SQLiteInterop = "x86\\SQLite.Interop.dll";
public const string x64SQLiteInterop = "x64\\SQLite.Interop.dll";
public const string SongCSV = "songs.csv";
public const string DataTypesCSV = "data_types.csv";
public const string MockSchemaXML = "mock-schema.xml";
public const string DataSoftXDDL = "datasoft.xddl.xml";
public const string TextFormatCSV = "text_formats.csv";
}
} | mit | C# | |
7c14bc2f3c5f5dda6af8c07d8123ae752bb2d362 | Create MessageBodyDeserializer.cs | Azure/azure-stream-analytics | CustomDeserializers/Protobuf/MessageBodyDeserializer.cs | CustomDeserializers/Protobuf/MessageBodyDeserializer.cs | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System.Collections.Generic;
using System.IO;
using Microsoft.Azure.StreamAnalytics;
using Microsoft.Azure.StreamAnalytics.Serialization;
namespace MessageBodyProto
{
public class MessageBodyDeserializer : StreamDeserializer<SimulatedTemperatureSensor.MessageBodyProto>
{
public override IEnumerable<SimulatedTemperatureSensor.MessageBodyProto> Deserialize(Stream stream)
{
while (stream.Position < stream.Length)
{
var e = SimulatedTemperatureSensor.MessageBodyProto.Parser.ParseDelimitedFrom(stream);
yield return e;
}
}
public override void Initialize(StreamingContext streamingContext)
{
}
}
}
| mit | C# | |
2582754e31a0dd53d81a18b9b81c23817b9ccc71 | Fix inverted documentation between two methods | ravimeda/corefx,Yanjing123/corefx,weltkante/corefx,shahid-pk/corefx,lggomez/corefx,mazong1123/corefx,vrassouli/corefx,dotnet-bot/corefx,erpframework/corefx,gabrielPeart/corefx,erpframework/corefx,alexandrnikitin/corefx,tstringer/corefx,thiagodin/corefx,shmao/corefx,manu-silicon/corefx,manu-silicon/corefx,shahid-pk/corefx,MaggieTsang/corefx,janhenke/corefx,Jiayili1/corefx,nelsonsar/corefx,the-dwyer/corefx,mokchhya/corefx,benpye/corefx,josguil/corefx,jcme/corefx,Chrisboh/corefx,SGuyGe/corefx,shmao/corefx,parjong/corefx,viniciustaveira/corefx,the-dwyer/corefx,stephenmichaelf/corefx,alexperovich/corefx,billwert/corefx,comdiv/corefx,nelsonsar/corefx,JosephTremoulet/corefx,cnbin/corefx,rahku/corefx,arronei/corefx,zmaruo/corefx,misterzik/corefx,JosephTremoulet/corefx,fffej/corefx,alphonsekurian/corefx,krytarowski/corefx,spoiledsport/corefx,uhaciogullari/corefx,ellismg/corefx,mellinoe/corefx,pgavlin/corefx,twsouthwick/corefx,jeremymeng/corefx,rajansingh10/corefx,richlander/corefx,ptoonen/corefx,CloudLens/corefx,jlin177/corefx,twsouthwick/corefx,weltkante/corefx,jhendrixMSFT/corefx,brett25/corefx,rahku/corefx,cartermp/corefx,MaggieTsang/corefx,SGuyGe/corefx,benjamin-bader/corefx,Jiayili1/corefx,Alcaro/corefx,stone-li/corefx,mmitche/corefx,shimingsg/corefx,fffej/corefx,jlin177/corefx,benpye/corefx,Chrisboh/corefx,gkhanna79/corefx,andyhebear/corefx,Petermarcu/corefx,gregg-miskelly/corefx,cnbin/corefx,elijah6/corefx,anjumrizwi/corefx,wtgodbe/corefx,the-dwyer/corefx,scott156/corefx,stephenmichaelf/corefx,KrisLee/corefx,alphonsekurian/corefx,zhangwenquan/corefx,manu-silicon/corefx,tijoytom/corefx,mokchhya/corefx,krk/corefx,richlander/corefx,fgreinacher/corefx,billwert/corefx,scott156/corefx,SGuyGe/corefx,nchikanov/corefx,bpschoch/corefx,Yanjing123/corefx,krytarowski/corefx,tstringer/corefx,JosephTremoulet/corefx,cartermp/corefx,rahku/corefx,gabrielPeart/corefx,jmhardison/corefx,dtrebbien/corefx,twsouthwick/corefx,zhenlan/corefx,zhangwenquan/corefx,mokchhya/corefx,CherryCxldn/corefx,alexperovich/corefx,vidhya-bv/corefx-sorting,cydhaselton/corefx,CloudLens/corefx,dsplaisted/corefx,VPashkov/corefx,mafiya69/corefx,khdang/corefx,khdang/corefx,rjxby/corefx,ViktorHofer/corefx,marksmeltzer/corefx,dhoehna/corefx,EverlessDrop41/corefx,seanshpark/corefx,Ermiar/corefx,popolan1986/corefx,shana/corefx,dtrebbien/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,mellinoe/corefx,mokchhya/corefx,iamjasonp/corefx,chenxizhang/corefx,claudelee/corefx,manu-silicon/corefx,cnbin/corefx,nchikanov/corefx,billwert/corefx,fernando-rodriguez/corefx,nbarbettini/corefx,axelheer/corefx,nchikanov/corefx,janhenke/corefx,twsouthwick/corefx,cydhaselton/corefx,jhendrixMSFT/corefx,nbarbettini/corefx,thiagodin/corefx,gkhanna79/corefx,elijah6/corefx,josguil/corefx,parjong/corefx,mazong1123/corefx,cartermp/corefx,thiagodin/corefx,fffej/corefx,mafiya69/corefx,alphonsekurian/corefx,matthubin/corefx,kyulee1/corefx,shana/corefx,yizhang82/corefx,VPashkov/corefx,dhoehna/corefx,seanshpark/corefx,elijah6/corefx,tijoytom/corefx,SGuyGe/corefx,alphonsekurian/corefx,xuweixuwei/corefx,zhenlan/corefx,shiftkey-tester/corefx,comdiv/corefx,stone-li/corefx,iamjasonp/corefx,SGuyGe/corefx,FiveTimesTheFun/corefx,stone-li/corefx,vidhya-bv/corefx-sorting,uhaciogullari/corefx,DnlHarvey/corefx,rubo/corefx,shrutigarg/corefx,akivafr123/corefx,chaitrakeshav/corefx,dtrebbien/corefx,shimingsg/corefx,shiftkey-tester/corefx,Jiayili1/corefx,PatrickMcDonald/corefx,dhoehna/corefx,zmaruo/corefx,stone-li/corefx,mellinoe/corefx,jlin177/corefx,Ermiar/corefx,ravimeda/corefx,iamjasonp/corefx,mafiya69/corefx,jcme/corefx,huanjie/corefx,dotnet-bot/corefx,bitcrazed/corefx,tstringer/corefx,khdang/corefx,rajansingh10/corefx,690486439/corefx,rjxby/corefx,yizhang82/corefx,weltkante/corefx,khdang/corefx,Ermiar/corefx,yizhang82/corefx,zmaruo/corefx,zhenlan/corefx,marksmeltzer/corefx,gregg-miskelly/corefx,jeremymeng/corefx,jhendrixMSFT/corefx,alexandrnikitin/corefx,axelheer/corefx,pallavit/corefx,gkhanna79/corefx,mazong1123/corefx,larsbj1988/corefx,dtrebbien/corefx,ravimeda/corefx,billwert/corefx,josguil/corefx,benjamin-bader/corefx,benpye/corefx,stormleoxia/corefx,misterzik/corefx,iamjasonp/corefx,stephenmichaelf/corefx,bpschoch/corefx,vijaykota/corefx,shmao/corefx,Frank125/corefx,rahku/corefx,claudelee/corefx,elijah6/corefx,alexperovich/corefx,stephenmichaelf/corefx,jlin177/corefx,rjxby/corefx,kyulee1/corefx,wtgodbe/corefx,heXelium/corefx,brett25/corefx,rubo/corefx,vs-team/corefx,ViktorHofer/corefx,twsouthwick/corefx,dkorolev/corefx,destinyclown/corefx,josguil/corefx,zhenlan/corefx,yizhang82/corefx,BrennanConroy/corefx,andyhebear/corefx,shrutigarg/corefx,Chrisboh/corefx,jcme/corefx,andyhebear/corefx,heXelium/corefx,shimingsg/corefx,FiveTimesTheFun/corefx,parjong/corefx,claudelee/corefx,oceanho/corefx,nchikanov/corefx,cartermp/corefx,rjxby/corefx,chenxizhang/corefx,kyulee1/corefx,YoupHulsebos/corefx,larsbj1988/corefx,dsplaisted/corefx,SGuyGe/corefx,rubo/corefx,shana/corefx,mmitche/corefx,lggomez/corefx,ellismg/corefx,jcme/corefx,lydonchandra/corefx,ViktorHofer/corefx,spoiledsport/corefx,Ermiar/corefx,cydhaselton/corefx,alexperovich/corefx,s0ne0me/corefx,Yanjing123/corefx,jmhardison/corefx,mafiya69/corefx,jeremymeng/corefx,alexandrnikitin/corefx,benjamin-bader/corefx,lggomez/corefx,destinyclown/corefx,YoupHulsebos/corefx,khdang/corefx,gregg-miskelly/corefx,benpye/corefx,kkurni/corefx,nbarbettini/corefx,shmao/corefx,CloudLens/corefx,popolan1986/corefx,690486439/corefx,Alcaro/corefx,jlin177/corefx,shmao/corefx,stone-li/corefx,kkurni/corefx,MaggieTsang/corefx,popolan1986/corefx,MaggieTsang/corefx,tstringer/corefx,nchikanov/corefx,ericstj/corefx,adamralph/corefx,JosephTremoulet/corefx,dhoehna/corefx,zhangwenquan/corefx,bitcrazed/corefx,cartermp/corefx,twsouthwick/corefx,xuweixuwei/corefx,shimingsg/corefx,n1ghtmare/corefx,viniciustaveira/corefx,DnlHarvey/corefx,oceanho/corefx,alexperovich/corefx,ericstj/corefx,wtgodbe/corefx,s0ne0me/corefx,chenkennt/corefx,KrisLee/corefx,dhoehna/corefx,seanshpark/corefx,yizhang82/corefx,twsouthwick/corefx,Petermarcu/corefx,tijoytom/corefx,stone-li/corefx,DnlHarvey/corefx,parjong/corefx,alphonsekurian/corefx,bpschoch/corefx,mazong1123/corefx,krk/corefx,tijoytom/corefx,marksmeltzer/corefx,andyhebear/corefx,yizhang82/corefx,s0ne0me/corefx,dkorolev/corefx,cydhaselton/corefx,mafiya69/corefx,MaggieTsang/corefx,adamralph/corefx,ellismg/corefx,gkhanna79/corefx,weltkante/corefx,lggomez/corefx,Winsto/corefx,huanjie/corefx,n1ghtmare/corefx,wtgodbe/corefx,BrennanConroy/corefx,lydonchandra/corefx,benjamin-bader/corefx,claudelee/corefx,rjxby/corefx,690486439/corefx,CherryCxldn/corefx,shmao/corefx,zhenlan/corefx,scott156/corefx,vijaykota/corefx,richlander/corefx,rahku/corefx,Alcaro/corefx,elijah6/corefx,Priya91/corefx-1,dotnet-bot/corefx,krytarowski/corefx,dkorolev/corefx,bitcrazed/corefx,khdang/corefx,rahku/corefx,matthubin/corefx,billwert/corefx,vijaykota/corefx,rubo/corefx,cydhaselton/corefx,shimingsg/corefx,Chrisboh/corefx,kkurni/corefx,akivafr123/corefx,seanshpark/corefx,shimingsg/corefx,dhoehna/corefx,Priya91/corefx-1,gkhanna79/corefx,jhendrixMSFT/corefx,Petermarcu/corefx,richlander/corefx,krytarowski/corefx,fgreinacher/corefx,stormleoxia/corefx,pallavit/corefx,gkhanna79/corefx,shahid-pk/corefx,bitcrazed/corefx,axelheer/corefx,pgavlin/corefx,josguil/corefx,krk/corefx,Petermarcu/corefx,ellismg/corefx,DnlHarvey/corefx,marksmeltzer/corefx,seanshpark/corefx,matthubin/corefx,CloudLens/corefx,huanjie/corefx,ericstj/corefx,uhaciogullari/corefx,ptoonen/corefx,weltkante/corefx,n1ghtmare/corefx,kkurni/corefx,yizhang82/corefx,pgavlin/corefx,nchikanov/corefx,zhangwenquan/corefx,alexperovich/corefx,MaggieTsang/corefx,nbarbettini/corefx,ravimeda/corefx,mazong1123/corefx,shahid-pk/corefx,YoupHulsebos/corefx,vidhya-bv/corefx-sorting,manu-silicon/corefx,JosephTremoulet/corefx,pallavit/corefx,krytarowski/corefx,ravimeda/corefx,shimingsg/corefx,ptoonen/corefx,ellismg/corefx,jmhardison/corefx,dotnet-bot/corefx,heXelium/corefx,bpschoch/corefx,vrassouli/corefx,DnlHarvey/corefx,jlin177/corefx,benjamin-bader/corefx,ViktorHofer/corefx,brett25/corefx,shiftkey-tester/corefx,vrassouli/corefx,Chrisboh/corefx,zhenlan/corefx,dkorolev/corefx,stormleoxia/corefx,Frank125/corefx,richlander/corefx,jhendrixMSFT/corefx,rjxby/corefx,690486439/corefx,rajansingh10/corefx,seanshpark/corefx,rajansingh10/corefx,mmitche/corefx,CherryCxldn/corefx,pgavlin/corefx,fgreinacher/corefx,fgreinacher/corefx,akivafr123/corefx,matthubin/corefx,misterzik/corefx,benjamin-bader/corefx,shiftkey-tester/corefx,Jiayili1/corefx,ericstj/corefx,gabrielPeart/corefx,gregg-miskelly/corefx,krk/corefx,Petermarcu/corefx,dotnet-bot/corefx,Winsto/corefx,mazong1123/corefx,nbarbettini/corefx,dhoehna/corefx,shahid-pk/corefx,mokchhya/corefx,huanjie/corefx,gabrielPeart/corefx,destinyclown/corefx,axelheer/corefx,alexperovich/corefx,krytarowski/corefx,mmitche/corefx,mellinoe/corefx,adamralph/corefx,ViktorHofer/corefx,marksmeltzer/corefx,alphonsekurian/corefx,janhenke/corefx,comdiv/corefx,PatrickMcDonald/corefx,marksmeltzer/corefx,iamjasonp/corefx,alphonsekurian/corefx,PatrickMcDonald/corefx,xuweixuwei/corefx,lydonchandra/corefx,uhaciogullari/corefx,rahku/corefx,nbarbettini/corefx,the-dwyer/corefx,cartermp/corefx,nelsonsar/corefx,mmitche/corefx,ViktorHofer/corefx,FiveTimesTheFun/corefx,Yanjing123/corefx,s0ne0me/corefx,elijah6/corefx,erpframework/corefx,Priya91/corefx-1,n1ghtmare/corefx,scott156/corefx,Priya91/corefx-1,ericstj/corefx,jmhardison/corefx,tijoytom/corefx,weltkante/corefx,chenxizhang/corefx,mmitche/corefx,mmitche/corefx,spoiledsport/corefx,janhenke/corefx,rjxby/corefx,manu-silicon/corefx,wtgodbe/corefx,pallavit/corefx,viniciustaveira/corefx,vrassouli/corefx,viniciustaveira/corefx,vs-team/corefx,chaitrakeshav/corefx,bitcrazed/corefx,wtgodbe/corefx,EverlessDrop41/corefx,arronei/corefx,rubo/corefx,chenkennt/corefx,lggomez/corefx,wtgodbe/corefx,vidhya-bv/corefx-sorting,chaitrakeshav/corefx,larsbj1988/corefx,the-dwyer/corefx,benpye/corefx,ptoonen/corefx,vidhya-bv/corefx-sorting,axelheer/corefx,Jiayili1/corefx,ptoonen/corefx,marksmeltzer/corefx,Frank125/corefx,josguil/corefx,stephenmichaelf/corefx,stormleoxia/corefx,alexandrnikitin/corefx,alexandrnikitin/corefx,cydhaselton/corefx,stone-li/corefx,fernando-rodriguez/corefx,iamjasonp/corefx,ravimeda/corefx,PatrickMcDonald/corefx,CherryCxldn/corefx,ptoonen/corefx,tstringer/corefx,n1ghtmare/corefx,krk/corefx,PatrickMcDonald/corefx,janhenke/corefx,Priya91/corefx-1,billwert/corefx,chaitrakeshav/corefx,vs-team/corefx,comdiv/corefx,mazong1123/corefx,arronei/corefx,kyulee1/corefx,zmaruo/corefx,heXelium/corefx,DnlHarvey/corefx,krytarowski/corefx,mokchhya/corefx,ptoonen/corefx,chenkennt/corefx,JosephTremoulet/corefx,anjumrizwi/corefx,VPashkov/corefx,YoupHulsebos/corefx,oceanho/corefx,EverlessDrop41/corefx,VPashkov/corefx,elijah6/corefx,lydonchandra/corefx,gkhanna79/corefx,pallavit/corefx,Petermarcu/corefx,jhendrixMSFT/corefx,thiagodin/corefx,Priya91/corefx-1,larsbj1988/corefx,billwert/corefx,weltkante/corefx,zhenlan/corefx,jcme/corefx,fernando-rodriguez/corefx,mellinoe/corefx,parjong/corefx,seanshpark/corefx,ViktorHofer/corefx,stephenmichaelf/corefx,Yanjing123/corefx,690486439/corefx,KrisLee/corefx,pallavit/corefx,anjumrizwi/corefx,nbarbettini/corefx,nelsonsar/corefx,stephenmichaelf/corefx,brett25/corefx,anjumrizwi/corefx,vs-team/corefx,Chrisboh/corefx,dotnet-bot/corefx,janhenke/corefx,lggomez/corefx,Petermarcu/corefx,Frank125/corefx,richlander/corefx,ellismg/corefx,the-dwyer/corefx,ravimeda/corefx,mafiya69/corefx,krk/corefx,lggomez/corefx,MaggieTsang/corefx,KrisLee/corefx,jeremymeng/corefx,nchikanov/corefx,jeremymeng/corefx,akivafr123/corefx,the-dwyer/corefx,cnbin/corefx,dsplaisted/corefx,kkurni/corefx,jlin177/corefx,YoupHulsebos/corefx,Ermiar/corefx,jhendrixMSFT/corefx,Winsto/corefx,akivafr123/corefx,erpframework/corefx,tijoytom/corefx,YoupHulsebos/corefx,benpye/corefx,Jiayili1/corefx,mellinoe/corefx,tijoytom/corefx,parjong/corefx,shana/corefx,cydhaselton/corefx,BrennanConroy/corefx,axelheer/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,Alcaro/corefx,ericstj/corefx,oceanho/corefx,fffej/corefx,ericstj/corefx,krk/corefx,Ermiar/corefx,shmao/corefx,shahid-pk/corefx,parjong/corefx,richlander/corefx,Ermiar/corefx,kkurni/corefx,shrutigarg/corefx,Jiayili1/corefx,tstringer/corefx,jcme/corefx,shrutigarg/corefx,iamjasonp/corefx,manu-silicon/corefx | src/System.ComponentModel/src/System/ComponentModel/IEditableObject.cs | src/System.ComponentModel/src/System/ComponentModel/IEditableObject.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.ComponentModel
{
/// <summary>
/// Provides functionality to commit or rollback changes to an object that is used as a data source.
/// </summary>
public interface IEditableObject
{
/// <summary>
/// Begins an edit on an object.
/// </summary>
void BeginEdit();
/// <summary>
/// Pushes changes since the last BeginEdit into the underlying object.
/// </summary>
void EndEdit();
/// <summary>
/// Discards changes since the last BeginEdit call.
/// </summary>
void CancelEdit();
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.ComponentModel
{
/// <summary>
/// Provides functionality to commit or rollback changes to an object that is used as a data source.
/// </summary>
public interface IEditableObject
{
/// <summary>
/// Begins an edit on an object.
/// </summary>
void BeginEdit();
/// <summary>
/// Discards changes since the last BeginEdit call.
/// </summary>
void EndEdit();
/// <summary>
/// Pushes changes since the last BeginEdit into the underlying object.
/// </summary>
void CancelEdit();
}
}
| mit | C# |
4bd5b4e7bd742ff91d5c41798fc5f12fdf63472a | Implement the DependencyResolver class | openchain/openchain | src/Openchain.Server/Models/DependencyResolver.cs | src/Openchain.Server/Models/DependencyResolver.cs | // Copyright 2015 Coinprism, 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Configuration;
using System.Linq.Expressions;
namespace Openchain.Server.Models
{
public class DependencyResolver<T>
where T : class
{
private ConstructorInfo constructor;
private object[] invokeParameters;
public DependencyResolver(IAssemblyLoadContextAccessor assemblyLoader, string assemblyName, IDictionary<string, string> parameters)
{
Assembly assembly = assemblyLoader.Default.Load(assemblyName);
if (assembly != null)
FindConstructor(assembly, parameters);
}
public static DependencyResolver<T> Create(IConfiguration config, IAssemblyLoadContextAccessor assemblyLoader)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
foreach (IConfigurationSection section in config.GetSection("settings").GetChildren())
parameters.Add(section.Key, section.Value);
return new DependencyResolver<T>(assemblyLoader, config["type"], parameters);
}
public T Build()
{
if (constructor == null)
return null;
else
return (T)constructor.Invoke(invokeParameters);
}
private void FindConstructor(Assembly assembly, IDictionary<string, string> parameters)
{
Type type = assembly.GetTypes().FirstOrDefault(item => typeof(T).IsAssignableFrom(item));
if (type == null)
return;
foreach (ConstructorInfo constructor in type.GetConstructors())
{
object[] result = Activate(constructor, parameters);
if (result != null)
{
this.constructor = constructor;
this.invokeParameters = result;
return;
}
}
}
private static object[] Activate(ConstructorInfo constructor, IDictionary<string, string> parameters)
{
ParameterInfo[] constructorParameters = constructor.GetParameters();
object[] invokeParameters = new object[constructorParameters.Length];
for (int i = 0; i < constructorParameters.Length; i++)
{
string value;
if (!parameters.TryGetValue(constructorParameters[i].Name, out value))
return null;
if (constructorParameters[i].ParameterType == typeof(string))
{
invokeParameters[i] = value;
}
else
{
return null;
}
}
return invokeParameters;
}
}
}
| apache-2.0 | C# | |
b285cf598b0f2b142cc818ec5dfaba6df6a0e452 | Add tests for ParseIntoWords() | KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog | src/StructuredLogger.Tests/ParseIntoWordsTests.cs | src/StructuredLogger.Tests/ParseIntoWordsTests.cs | using System.Collections.Generic;
using System.Text;
using Xunit;
namespace StructuredLogger.Tests
{
public class ParseIntoWordsTests
{
[Fact]
public void TestParseIntoWords()
{
T("a b", "a", "b");
T("a \"b c\"", "a", "b c");
T("a \"b\" c\"", "a", "b", "c\"");
T("a (b c)", "a", "(b c)");
T("a (b\" c)", "a", "(b\" c)");
T("a (b\"f\" c)", "a", "(b\"f\" c)");
T("a \"b(\"", "a", "b(");
T("a \"b)\"", "a", "b)");
T("a \"(b\"", "a", "(b");
T("a \")b\"", "a", ")b");
T("a \")b(\"", "a", ")b(");
T("a \"(b)\"", "a", "(b)");
}
private static void T(string query, params string[] expectedParts)
{
var actualParts = ParseIntoWords(query);
Assert.Equal(expectedParts, actualParts);
}
private static List<string> ParseIntoWords(string query)
{
var result = new List<string>();
StringBuilder currentWord = new StringBuilder();
bool isInParentheses = false;
bool isInQuotes = false;
for (int i = 0; i < query.Length; i++)
{
char c = query[i];
switch (c)
{
case ' ' when !isInParentheses && !isInQuotes:
result.Add(TrimQuotes(currentWord.ToString()));
currentWord.Clear();
break;
case '(' when !isInParentheses && !isInQuotes:
isInParentheses = true;
currentWord.Append(c);
break;
case ')' when isInParentheses && !isInQuotes:
isInParentheses = false;
currentWord.Append(c);
break;
case '"' when !isInParentheses:
isInQuotes = !isInQuotes;
currentWord.Append(c);
break;
default:
currentWord.Append(c);
break;
}
}
result.Add(TrimQuotes(currentWord.ToString()));
return result;
}
private static string TrimQuotes(string word)
{
if (word.Length > 2 && word[0] == '"' && word[word.Length - 1] == '"')
{
word = word.Substring(1, word.Length - 2);
}
return word;
}
}
}
| mit | C# | |
8b4619173867972466ca60df30f7e229755cc544 | Add test coverage for `RemoveAndDisposeImmediately()` | peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework | osu.Framework.Tests/Containers/TestSceneSyncDisposal.cs | osu.Framework.Tests/Containers/TestSceneSyncDisposal.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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.Containers
{
[HeadlessTest]
public class TestSceneSyncDisposal : FrameworkTestScene
{
[Test]
public void TestRemoveAndDisposeImmediatelyFromComposite()
{
TestComposite composite = null;
AddStep("create composite", () => Child = composite = new TestComposite());
AddAssert("immediate removal and disposal succeeds", () =>
{
composite.CompositeChild.RemoveAndDisposeImmediately();
return composite.CompositeChild.Parent == null && composite.CompositeChild.IsDisposed && composite.InternalChildren.Count == 0;
});
}
[Test]
public void TestRemoveAndDisposeImmediatelyFromPlainContainer()
{
TestContainer container = null;
AddStep("create container", () => Child = container = new TestContainer());
AddAssert("immediate removal and disposal succeeds", () =>
{
container.ContainerChild.RemoveAndDisposeImmediately();
return container.ContainerChild.Parent == null && container.ContainerChild.IsDisposed && container.InternalChildren.Count == 0;
});
}
[Test]
public void TestRemoveAndDisposeImmediatelyContentChildFromContainerWithOverriddenContent()
{
TestContainerWithCustomContent container = null;
AddStep("create container", () => Child = container = new TestContainerWithCustomContent());
AddAssert("immediate removal and disposal succeeds", () =>
{
container.ContentChild.RemoveAndDisposeImmediately();
return container.ContentChild.Parent == null
&& container.ContentChild.IsDisposed
&& container.InternalChildren.Count == 2
&& container.ContentContainer.InternalChildren.Count == 0;
});
}
[Test]
public void TestRemoveAndDisposeImmediatelyNonContentChildFromContainerWithOverriddenContent()
{
TestContainerWithCustomContent container = null;
AddStep("create container", () => Child = container = new TestContainerWithCustomContent());
AddAssert("immediate removal and disposal succeeds", () =>
{
container.NonContentChild.RemoveAndDisposeImmediately();
return container.NonContentChild.Parent == null
&& container.NonContentChild.IsDisposed
&& container.InternalChildren.Count == 1
&& container.ContentContainer.InternalChildren.Count == 1;
});
}
[Test]
public void TestRemoveAndDisposeImmediatelyUnattachedDrawable()
{
Container container = null;
AddStep("create container", () => container = new Container());
AddAssert("immediate removal and disposal succeeds", () =>
{
container.RemoveAndDisposeImmediately();
return container.IsDisposed;
});
}
private class TestComposite : CompositeDrawable
{
public readonly Drawable CompositeChild;
public TestComposite()
{
InternalChild = CompositeChild = new Container();
}
}
private class TestContainer : Container
{
public readonly Drawable ContainerChild;
public TestContainer()
{
Child = ContainerChild = new Container();
}
}
private class TestContainerWithCustomContent : Container
{
public readonly Drawable NonContentChild;
public readonly Drawable ContentChild;
public readonly Container ContentContainer;
protected override Container<Drawable> Content => ContentContainer;
public TestContainerWithCustomContent()
{
AddRangeInternal(new[]
{
NonContentChild = new Container(),
ContentContainer = new Container
{
Child = ContentChild = new Container()
}
});
}
}
}
}
| mit | C# | |
3789ce6e27b969eae41c4402e1bba14b38652be5 | Add a new repository interface to deal with counting of elements from the data store | reexmonkey/xmisc | solution/xmisc.backbone.repositories.contracts/count.cs | solution/xmisc.backbone.repositories.contracts/count.cs | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace reexmonkey.xmisc.backbone.repositories.contracts
{
/// <summary>
/// Specifies a repository that counts the data models of a data store.
/// </summary>
/// <typeparam name="TModel">The type of data model to count.</typeparam>
public interface ICountRepository<TModel>
{
/// <summary>
/// Counts all data models in the data store.
/// </summary>
/// <returns>The total number of data models in the data store.</returns>
long Count();
/// <summary>
/// Counts the specified data models in the data store that satisfy the given predicate.
/// </summary>
/// <param name="predicate">The condition for a data model that when evaluated to true, includes the data model in the count.</param>
/// <returns>The total number of data models that satisfy the given predicate.</returns>
long Count(Expression<Func<TModel, bool>> predicate);
/// <summary>
/// Asynchronously counts all data models in the data store.
/// </summary>
/// <param name="token">Propagates the notification that the asynchronous operation should be cancelled.</param>
/// <returns>The total number of data models in the data store.</returns>
Task<long> CountAsync(CancellationToken token = default(CancellationToken));
/// <summary>
/// Asynchronously counts the specified data models in the data store that satisfy the given predicate.
/// </summary>
/// <param name="predicate">The condition for a data model that when evaluated to true, includes the data model in the count.</param>
/// <param name="token">Propagates the notification that the asynchronous operation should be cancelled.</param>
/// <returns>The total number of data models that satisfy the given predicate.</returns>
Task<long> CountAsync(Expression<Func<TModel, bool>> predicate, CancellationToken token = default(CancellationToken));
}
}
| mit | C# | |
4a08826812a88af41b7390ff69b56bdb76d76394 | Disable tests parallelization. We are ocasionally getting `MqttCommunicationException ` with message `The Write method cannot be called when another write operation is pending.` and I can't find any obvious overlap within the given test. So it's probably because of several tests executing at once. | GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | iot/api/CloudIotMqttExampleTest/AssemblyInfo.cs | iot/api/CloudIotMqttExampleTest/AssemblyInfo.cs | /*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
| apache-2.0 | C# | |
f12ae23de291a0fdb3b59eb1c009189406c70055 | Check if an array is preorder | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | GeeksForGeeks/check_if_array_is_preorder.cs | GeeksForGeeks/check_if_array_is_preorder.cs | // http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/
//
// Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree,
// else return false. Expected time complexity is O(n).
//
using System;
using System.Collections.Generic;
static class Program
{
static bool IsTraversal(this int[] a)
{
var stack = new Stack<int>();
var root = int.MinValue;
foreach (var node in a)
{
if (node < root)
{
return false;
}
while (stack.Count != 0 && stack.Peek() < node)
{
root = stack.Pop();
}
stack.Push(node);
}
return true;
}
static void Main()
{
if (!new [] {2, 4, 3}.IsTraversal())
{
throw new Exception("You are weak, expected true");
}
if (!new [] {40, 30, 35, 80, 100}.IsTraversal())
{
throw new Exception("You are weak, expected true");
}
if (new [] {2, 4, 1}.IsTraversal())
{
throw new Exception("You are weak, expected false");
}
if (new [] {40, 30, 35, 20, 80, 100}.IsTraversal())
{
throw new Exception("You are weak, expected false");
}
Console.WriteLine("All appears to be well");
}
}
| mit | C# | |
f34f1c55c17b2aae58ffbedcd5fa4a5e76d569e6 | Create qmodule.cs | QetriX/CS | libs/qmodule.cs | libs/qmodule.cs | namespace com.qetrix.libs
{
/* Copyright (c) QetriX.com. Licensed under MIT License, see /LICENSE.txt file.
* 18.08.22 | QetriX Module C# class
*/
using components;
public class QModule
{
protected DataStore _ds; // Primary DataStore
protected DataStore varDS; // Variable files DataStore (logs, temps)
protected DataStore dataDS; // Data DataStore
protected DataStore contentDS; // Content DataStore (for PHP always FileSystem)
public QModuleStage _stage;
protected QPage _page;
protected string heading = "";
/** Class Constructor */
public QModule(QPage page)
{
this._page = page;
this._ds = this.page().ds();
this._stage = this.page().stage();
}
public string main(Dict args)
{
return "It works! Now please add your custom implementation of method " + this.GetType().Name + ".main(Dict args):string.";
}
public DataStore ds()
{
return this._ds;
}
public QPage page()
{
return this._page;
}
protected object QPage(Dict args, string content, string heading, string style)
{
var page = new QView();
page.heading(heading == "" ? this.heading : heading);
page.add(content);
return page.convert("page");
}
public QModuleStage stage()
{
return this._stage;
}
public Dict init(Dict args)
{
return args;
}
}
}
| mit | C# | |
6d1b654283a67e1508851e5e8867fe0bb033f675 | Change UIView.Animate to UIView.Transition, bug #4422 fix | sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,YOTOV-LIMITED/monotouch-samples,YOTOV-LIMITED/monotouch-samples,a9upam/monotouch-samples,robinlaide/monotouch-samples,davidrynn/monotouch-samples,iFreedive/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,a9upam/monotouch-samples,YOTOV-LIMITED/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,andypaul/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,kingyond/monotouch-samples,davidrynn/monotouch-samples,hongnguyenpro/monotouch-samples,hongnguyenpro/monotouch-samples,nervevau2/monotouch-samples,markradacz/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,xamarin/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,haithemaraissia/monotouch-samples,sakthivelnagarajan/monotouch-samples,xamarin/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,albertoms/monotouch-samples,iFreedive/monotouch-samples,albertoms/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,W3SS/monotouch-samples,albertoms/monotouch-samples,haithemaraissia/monotouch-samples,sakthivelnagarajan/monotouch-samples,markradacz/monotouch-samples,W3SS/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,labdogg1003/monotouch-samples,hongnguyenpro/monotouch-samples,andypaul/monotouch-samples | CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs | CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs | using System;
using System.Drawing;
using MonoTouch.CoreFoundation;
using MonoTouch.UIKit;
namespace Example_CoreAnimation.Screens.iPad.ViewTransitions
{
public class Controller : UIViewController, IDetailView
{
public event EventHandler ContentsButtonClicked;
private TransitionViewController transitionViewController;
private BackTransitionViewController backViewController;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
View.BackgroundColor = UIColor.White;
var mainFrame = new RectangleF (0f, 44f, View.Frame.Width, View.Frame.Height - 44f);
transitionViewController = new TransitionViewController ();
transitionViewController.View.Frame = mainFrame;
backViewController = new BackTransitionViewController ();
backViewController.View.Frame = mainFrame;
View.AddSubview (transitionViewController.View);
transitionViewController.SetToolbarVisibility (InterfaceOrientation);
transitionViewController.TransitionClicked += (s, e) => {
UIView.Transition(transitionViewController.View, backViewController.View, 0.75,
transitionViewController.SelectedTransition, null);
};
transitionViewController.ContentsClicked += () => {
if (ContentsButtonClicked != null) {
ContentsButtonClicked (null, null);
}
};
backViewController.BackClicked += (s, e) => {
UIView.Transition(backViewController.View, transitionViewController.View, 0.75,
transitionViewController.SelectedTransition, null);
};
}
public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration)
{
transitionViewController.SetToolbarVisibility (toInterfaceOrientation);
base.WillRotate (toInterfaceOrientation, duration);
}
public override void ViewWillAppear (bool animated)
{
transitionViewController.SetToolbarVisibility (InterfaceOrientation);
base.ViewWillAppear (animated);
}
}
}
| using System;
using System.Drawing;
using MonoTouch.CoreFoundation;
using MonoTouch.UIKit;
namespace Example_CoreAnimation.Screens.iPad.ViewTransitions
{
public class Controller : UIViewController, IDetailView
{
public event EventHandler ContentsButtonClicked;
private TransitionViewController transitionViewController;
private BackTransitionViewController backViewController;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
View.BackgroundColor = UIColor.White;
var mainFrame = new RectangleF (0f, 44f, View.Frame.Width, View.Frame.Height - 44f);
transitionViewController = new TransitionViewController ();
transitionViewController.View.Frame = mainFrame;
backViewController = new BackTransitionViewController ();
backViewController.View.Frame = mainFrame;
View.AddSubview (transitionViewController.View);
transitionViewController.SetToolbarVisibility (InterfaceOrientation);
transitionViewController.TransitionClicked += (s, e) => {
UIView.Animate (1, 0, transitionViewController.SelectedTransition, () => {
transitionViewController.View.RemoveFromSuperview ();
View.AddSubview (backViewController.View);
}, null);
UIView.BeginAnimations ("ViewChange");
};
transitionViewController.ContentsClicked += () => {
if (ContentsButtonClicked != null) {
ContentsButtonClicked (null, null);
}
};
backViewController.BackClicked += (s, e) => {
UIView.Animate (.75, 0, transitionViewController.SelectedTransition, () => {
backViewController.View.RemoveFromSuperview ();
View.AddSubview (transitionViewController.View);
}, null);
};
}
public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration)
{
transitionViewController.SetToolbarVisibility (toInterfaceOrientation);
base.WillRotate (toInterfaceOrientation, duration);
}
public override void ViewWillAppear (bool animated)
{
transitionViewController.SetToolbarVisibility (InterfaceOrientation);
base.ViewWillAppear (animated);
}
}
}
| mit | C# |
c4b63872ccc1754f592dd22b38f1fd82e67e82c7 | Add entities interface | Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife | PhotoLife/PhotoLife.Data/Contracts/IPhotoLifeEntities.cs | PhotoLife/PhotoLife.Data/Contracts/IPhotoLifeEntities.cs | using System.Data.Entity;
namespace PhotoLife.Data.Contracts
{
public interface IPhotoLifeEntities
{
IDbSet<TEntity> DbSet<TEntity>()
where TEntity : class;
int SaveChanges();
void SetAdded<TEntry>(TEntry entity)
where TEntry : class;
void SetDeleted<TEntry>(TEntry entity)
where TEntry : class;
void SetUpdated<TEntry>(TEntry entity)
where TEntry : class;
}
}
| mit | C# | |
70ae49c838dc63b03e2eaeb099b4cf79ff9e80b0 | Return null if DefaultProfile or context does not exist, move error writing to ExecuteCmdlet | AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell | src/ResourceManager/Profile/Commands.Profile/Context/GetAzureRMContext.cs | src/ResourceManager/Profile/Commands.Profile/Context/GetAzureRMContext.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.WindowsAzure.Commands.Common;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Profile
{
/// <summary>
/// Cmdlet to get current context.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AzureRmContext")]
[OutputType(typeof(PSAzureContext))]
public class GetAzureRMContextCommand : AzureRMCmdlet
{
/// <summary>
/// Gets the current default context.
/// </summary>
protected override AzureContext DefaultContext
{
get
{
if (DefaultProfile == null || DefaultProfile.Context == null)
{
return null;
}
return DefaultProfile.Context;
}
}
public override void ExecuteCmdlet()
{
var context = (PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context;
if (context == null)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Run Login-AzureRmAccount to login."),
string.Empty,
ErrorCategory.AuthenticationError,
null));
}
WriteObject(context);
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.WindowsAzure.Commands.Common;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Profile
{
/// <summary>
/// Cmdlet to get current context.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AzureRmContext")]
[OutputType(typeof(PSAzureContext))]
public class GetAzureRMContextCommand : AzureRMCmdlet
{
/// <summary>
/// Gets the current default context.
/// </summary>
protected override AzureContext DefaultContext
{
get
{
if (DefaultProfile == null || DefaultProfile.Context == null)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Run Login-AzureRmAccount to login."),
string.Empty,
ErrorCategory.AuthenticationError,
null));
}
return DefaultProfile.Context;
}
}
public override void ExecuteCmdlet()
{
WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context);
}
}
}
| apache-2.0 | C# |
154f6b98d1a347af4970f3d43d57563ee9fd51ea | Create OptionsWindow.cs | hallstromsimon/wearables | OptionsWindow.cs | OptionsWindow.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
namespace OpenVoice
{
/// <summary>
/// Interaction logic for OptionsWindow.xaml
/// </summary>
public partial class OptionsWindow : Window
{
public OptionsWindow()
{
InitializeComponent();
}
private void TriggersButton_Click(object sender, RoutedEventArgs e)
{
(new TriggersWindow()).Show();
}
}
}
| apache-2.0 | C# | |
e03bae28bbd6c903d285786939da69fd9437266c | Enable soft delete on server | lindydonna/app-service-mobile-dotnet-todo-list-files,Azure-Samples/app-service-mobile-dotnet-todo-list-files | src/service/MobileAppsFileSampleService/Controllers/TodoItemController.cs | src/service/MobileAppsFileSampleService/Controllers/TodoItemController.cs | using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using MobileAppsFileSampleService.DataObjects;
using MobileAppsFileSampleService.Models;
namespace MobileAppsFileSampleService.Controllers
{
public class TodoItemController : TableController<TodoItem>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MobileAppsFileSampleContext context = new MobileAppsFileSampleContext();
DomainManager = new EntityDomainManager<TodoItem>(context, Request, enableSoftDelete: true);
}
// GET tables/TodoItem
public IQueryable<TodoItem> GetAllTodoItems()
{
return Query();
}
// GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<TodoItem> GetTodoItem(string id)
{
return Lookup(id);
}
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<TodoItem> PatchTodoItem(string id, Delta<TodoItem> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/TodoItem
public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
{
TodoItem current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteTodoItem(string id)
{
return DeleteAsync(id);
}
}
} | using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using MobileAppsFileSampleService.DataObjects;
using MobileAppsFileSampleService.Models;
namespace MobileAppsFileSampleService.Controllers
{
public class TodoItemController : TableController<TodoItem>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MobileAppsFileSampleContext context = new MobileAppsFileSampleContext();
DomainManager = new EntityDomainManager<TodoItem>(context, Request);
}
// GET tables/TodoItem
public IQueryable<TodoItem> GetAllTodoItems()
{
return Query();
}
// GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<TodoItem> GetTodoItem(string id)
{
return Lookup(id);
}
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<TodoItem> PatchTodoItem(string id, Delta<TodoItem> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/TodoItem
public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
{
TodoItem current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteTodoItem(string id)
{
return DeleteAsync(id);
}
}
} | mit | C# |
0734e4fa97754b7e3f76da6e51b83dbcd7bc9650 | Create kod.cs | Juchnowski/testrep | kod.cs | kod.cs |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RozliczeniePracownikow
{
public class Rozliczenia
{
public virtual double kosztPrzejazduSamochod(int kilometry, float spalanie, float cenaLitr, float dodatkowe)
{
return Math.Round((kilometry / 100) * spalanie * cenaLitr + dodatkowe,2);
}
public decimal chorobowe(int liczbaDni, float wynagrodzenie, float stawkaChorobowa = 0.8f)
{
return Math.Round((decimal)( (wynagrodzenie*12/360)*liczbaDni*stawkaChorobowa ),1);
}
}
}
| mit | C# | |
df02e1adbc29b484f101c89b018963a1dc8c5452 | Add INativeTexture interface | ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework | osu.Framework/Graphics/Rendering/INativeTexture.cs | osu.Framework/Graphics/Rendering/INativeTexture.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Visualisation;
namespace osu.Framework.Graphics.Rendering
{
internal interface INativeTexture : IDisposable
{
/// <summary>
/// An identifier for this texture, to show up in the <see cref="TextureVisualiser"/>.
/// </summary>
string Identifier { get; }
/// <summary>
/// Maximum texture size in any direction.
/// </summary>
int MaxSize { get; }
/// <summary>
/// The width of the texture.
/// </summary>
int Width { get; set; }
/// <summary>
/// The height of the texture.
/// </summary>
int Height { get; set; }
/// <summary>
/// Whether the texture is in a usable state.
/// </summary>
bool Available { get; }
/// <summary>
/// By default, texture uploads are queued for upload at the beginning of each frame, allowing loading them ahead of time.
/// When this is true, this will be bypassed and textures will only be uploaded on use. Should be set for every-frame texture uploads
/// to avoid overloading the global queue.
/// </summary>
bool BypassTextureUploadQueueing { get; set; }
/// <summary>
/// Whether the latest data has been uploaded.
/// </summary>
bool UploadComplete { get; }
/// <summary>
/// Whether the texture is currently queued for upload.
/// </summary>
bool IsQueuedForUpload { get; set; }
/// <summary>
/// Flush any unprocessed uploads without actually uploading.
/// </summary>
void FlushUploads();
/// <summary>
/// Sets the pixel data of the texture.
/// </summary>
/// <param name="upload">The <see cref="ITextureUpload"/> containing the data.</param>
void SetData(ITextureUpload upload);
bool Upload();
bool Bind(int unit, WrapMode wrapModeS, WrapMode wrapModeT);
/// <summary>
/// The size of this texture in bytes.
/// </summary>
int GetByteSize();
}
}
| mit | C# | |
bdb5399fd684911fcbab2b64db9e5aa87bde99d6 | Add Device Model Extenstion | cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings | DynThings.Data.Models/ModelsExtensions/Device.cs | DynThings.Data.Models/ModelsExtensions/Device.cs | /////////////////////////////////////////////////////////////////
// Created by : Caesar Moussalli //
// TimeStamp : 3-2-2016 //
// Content : Extend the properties of Device Model //
// Notes : Don't add Behavior in this class //
/////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DynThings.Data.Models
{
public partial class Device
{
private DynThingsEntities db = new DynThingsEntities();
}
}
| mit | C# | |
931f3bd2ce920db392e33e15dc88c37bd6ab4757 | Revert "remove old assemblyinfo (wasn't included in the solution)" | rickyah/ini-parser,rickyah/ini-parser,davidgrupp/ini-parser | src/IniFileParser.Tests/Properties/AssemblyInfo.cs | src/IniFileParser.Tests/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("IniFileParserTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IniFileParserTests")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[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("b45d3f26-a017-43e3-8f76-2516ad4ec9b2")]
// 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# | |
d18875c04e8efb9556842083ad8faff4f871b64e | Add BgpSettings | ClogenyTechnologies/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,ankurchoubeymsft/azure-powershell,CamSoper/azure-powershell,atpham256/azure-powershell,arcadiahlyy/azure-powershell,akurmi/azure-powershell,zhencui/azure-powershell,arcadiahlyy/azure-powershell,hovsepm/azure-powershell,hungmai-msft/azure-powershell,yoavrubin/azure-powershell,AzureRT/azure-powershell,naveedaz/azure-powershell,shuagarw/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,yoavrubin/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,seanbamsft/azure-powershell,shuagarw/azure-powershell,ClogenyTechnologies/azure-powershell,ankurchoubeymsft/azure-powershell,ankurchoubeymsft/azure-powershell,AzureRT/azure-powershell,naveedaz/azure-powershell,CamSoper/azure-powershell,jtlibing/azure-powershell,nemanja88/azure-powershell,hungmai-msft/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,hovsepm/azure-powershell,shuagarw/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,AzureRT/azure-powershell,atpham256/azure-powershell,rohmano/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,zhencui/azure-powershell,arcadiahlyy/azure-powershell,ClogenyTechnologies/azure-powershell,seanbamsft/azure-powershell,seanbamsft/azure-powershell,krkhan/azure-powershell,nemanja88/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,CamSoper/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,Matt-Westphal/azure-powershell,arcadiahlyy/azure-powershell,yantang-msft/azure-powershell,devigned/azure-powershell,zhencui/azure-powershell,akurmi/azure-powershell,Matt-Westphal/azure-powershell,nemanja88/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,krkhan/azure-powershell,yantang-msft/azure-powershell,naveedaz/azure-powershell,nemanja88/azure-powershell,shuagarw/azure-powershell,jtlibing/azure-powershell,atpham256/azure-powershell,hovsepm/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,pankajsn/azure-powershell,alfantp/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,shuagarw/azure-powershell,alfantp/azure-powershell,devigned/azure-powershell,zhencui/azure-powershell,jtlibing/azure-powershell,arcadiahlyy/azure-powershell,yantang-msft/azure-powershell,yantang-msft/azure-powershell,AzureRT/azure-powershell,yoavrubin/azure-powershell,yoavrubin/azure-powershell,rohmano/azure-powershell,Matt-Westphal/azure-powershell,hovsepm/azure-powershell,CamSoper/azure-powershell,jtlibing/azure-powershell,yoavrubin/azure-powershell,krkhan/azure-powershell,pankajsn/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,naveedaz/azure-powershell,AzureRT/azure-powershell,devigned/azure-powershell,rohmano/azure-powershell,hovsepm/azure-powershell,zhencui/azure-powershell,rohmano/azure-powershell,devigned/azure-powershell,alfantp/azure-powershell,nemanja88/azure-powershell,akurmi/azure-powershell,Matt-Westphal/azure-powershell,CamSoper/azure-powershell,hungmai-msft/azure-powershell,ankurchoubeymsft/azure-powershell,pankajsn/azure-powershell,Matt-Westphal/azure-powershell,yantang-msft/azure-powershell,akurmi/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,alfantp/azure-powershell,akurmi/azure-powershell,AzureAutomationTeam/azure-powershell,ankurchoubeymsft/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,naveedaz/azure-powershell | src/ServiceManagement/Network/Commands.Network/Gateway/Model/BgpSettings.cs | src/ServiceManagement/Network/Commands.Network/Gateway/Model/BgpSettings.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Network
{
public class BgpSettings
{
public uint Asn { get; set; }
public string BgpPeeringAddress { get; set; }
public int PeerWeight { get; set; }
}
}
| apache-2.0 | C# | |
411fc37567398cd9d595e61d1aab5f372df325db | Add type to request comment help | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/CommentHelpRequest.cs | src/PowerShellEditorServices.Protocol/LanguageServer/CommentHelpRequest.cs | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
class CommentHelpRequest
{
public static readonly RequestType<CommentHelpRequestParams, CommentHelpRequestResult, object, object> Type
= RequestType<CommentHelpRequestParams, CommentHelpRequestResult, object, object>.Create("powershell/getCommentHelp");
}
public class CommentHelpRequestResult
{
public string[] content;
}
public class CommentHelpRequestParams
{
public string DocumentUri { get; set; }
public Position TriggerPosition { get; set; }
}
}
| mit | C# | |
db0cd600c417d6f10c762f6e91de39c08e4d8348 | Introduce exponential backoff for executors | ExRam/ExRam.Gremlinq | src/ExRam.Gremlinq.Core/Extensions/GremlinQueryExecutorExtensions.cs | src/ExRam.Gremlinq.Core/Extensions/GremlinQueryExecutorExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Gremlin.Net.Driver.Exceptions;
namespace ExRam.Gremlinq.Core
{
public static class GremlinQueryExecutorExtensions
{
private sealed class ExponentialBackoffExecutor : IGremlinQueryExecutor
{
[ThreadStatic]
private static Random? _rnd;
private const int MaxTries = 32;
private readonly IGremlinQueryExecutor _baseExecutor;
private readonly Func<int, ResponseException, bool> _shouldRetry;
public ExponentialBackoffExecutor(IGremlinQueryExecutor baseExecutor, Func<int, ResponseException, bool> shouldRetry)
{
_baseExecutor = baseExecutor;
_shouldRetry = shouldRetry;
}
public IAsyncEnumerable<object> Execute(object serializedQuery, IGremlinQueryEnvironment environment)
{
return AsyncEnumerable.Create(Core);
async IAsyncEnumerator<object> Core(CancellationToken ct)
{
var hasSeenFirst = false;
for (var i = 0; i < MaxTries; i++)
{
await using (var enumerator = _baseExecutor.Execute(serializedQuery, environment).GetAsyncEnumerator(ct))
{
while (true)
{
try
{
if (!await enumerator.MoveNextAsync())
yield break;
hasSeenFirst = true;
}
catch (ResponseException ex)
{
if (hasSeenFirst)
throw;
if (!_shouldRetry(i, ex))
throw;
await Task.Delay((_rnd ??= new Random()).Next(i + 2) * 16, ct);
break;
}
yield return enumerator.Current;
}
}
}
}
}
}
public static IGremlinQueryExecutor RetryWithExponentialBackoff(this IGremlinQueryExecutor executor, Func<int, ResponseException, bool> shouldRetry)
{
return new ExponentialBackoffExecutor(executor, shouldRetry);
}
}
}
| mit | C# | |
f9ce987cc51a4142a6a1f7065d38de66f88f07db | Cover DelegateInvokingLoadBalancerCreator by unit tests. | TomPallister/Ocelot,TomPallister/Ocelot | test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs | test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs | using System;
using System.Threading.Tasks;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Middleware;
using Ocelot.Responses;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.LoadBalancer
{
public class DelegateInvokingLoadBalancerCreatorTests
{
private readonly DelegateInvokingLoadBalancerCreator<FakeLoadBalancer> _creator;
private readonly Func<DownstreamReRoute, IServiceDiscoveryProvider, ILoadBalancer> _creatorFunc;
private readonly Mock<IServiceDiscoveryProvider> _serviceProvider;
private DownstreamReRoute _reRoute;
private ILoadBalancer _loadBalancer;
private string _typeName;
public DelegateInvokingLoadBalancerCreatorTests()
{
_creatorFunc = (reRoute, serviceDiscoveryProvider) =>
new FakeLoadBalancer(reRoute, serviceDiscoveryProvider);
_creator = new DelegateInvokingLoadBalancerCreator<FakeLoadBalancer>(_creatorFunc);
_serviceProvider = new Mock<IServiceDiscoveryProvider>();
}
[Fact]
public void should_return_expected_name()
{
this.When(x => x.WhenIGetTheLoadBalancerTypeName())
.Then(x => x.ThenTheLoadBalancerTypeIs("FakeLoadBalancer"))
.BDDfy();
}
[Fact]
public void should_return_result_of_specified_creator_func()
{
var reRoute = new DownstreamReRouteBuilder()
.Build();
this.Given(x => x.GivenAReRoute(reRoute))
.When(x => x.WhenIGetTheLoadBalancer())
.Then(x => x.ThenTheLoadBalancerIsReturned<FakeLoadBalancer>())
.BDDfy();
}
private void GivenAReRoute(DownstreamReRoute reRoute)
{
_reRoute = reRoute;
}
private void WhenIGetTheLoadBalancer()
{
_loadBalancer = _creator.Create(_reRoute, _serviceProvider.Object);
}
private void WhenIGetTheLoadBalancerTypeName()
{
_typeName = _creator.Type;
}
private void ThenTheLoadBalancerIsReturned<T>()
where T : ILoadBalancer
{
_loadBalancer.ShouldBeOfType<T>();
}
private void ThenTheLoadBalancerTypeIs(string type)
{
_typeName.ShouldBe(type);
}
private class FakeLoadBalancer : ILoadBalancer
{
public FakeLoadBalancer(DownstreamReRoute reRoute, IServiceDiscoveryProvider serviceDiscoveryProvider)
{
ReRoute = reRoute;
ServiceDiscoveryProvider = serviceDiscoveryProvider;
}
public DownstreamReRoute ReRoute { get; }
public IServiceDiscoveryProvider ServiceDiscoveryProvider { get; }
public Task<Response<ServiceHostAndPort>> Lease(DownstreamContext context)
{
throw new NotImplementedException();
}
public void Release(ServiceHostAndPort hostAndPort)
{
throw new NotImplementedException();
}
}
}
}
| mit | C# | |
6494b13f3509cfb7fe63863e4d6dc36fbff61804 | Add http request reason provider for Abp.Web | carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,verdentk/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate | src/Abp.Web/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs | src/Abp.Web/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs | using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;
namespace Abp.Web.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
return HttpContext.Current?.Request.Url.AbsoluteUri;
}
}
public HttpRequestEntityChangeSetReasonProvider(
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
}
}
}
| mit | C# | |
8130d5ca1af55ac9bacee8d9a148901b4d04a39f | Add LineSchemeUrl static class | pierre3/LineMessagingApi,pierre3/LineMessagingApi | Line.Messaging/LineSchmeUrl.cs | Line.Messaging/LineSchmeUrl.cs | using System;
namespace Line.Messaging
{
public static class LineSchmeUrl
{
private static readonly string camera = "line://nv/camera/";
private static readonly string cameraRollSingle = "line://nv/cameraRoll/single";
private static readonly string cameraRollMulti = "line://nv/cameraRoll/multi";
private static readonly string location = "line://nv/location";
private static readonly string addFriend = "line://ti/p/{0}";
private static readonly string recommendOA = "line://nv/recommendOA/{0}";
private static readonly string main = "line://home/public/main?id={0}";
private static readonly string profile = "line://home/public/profile?id={0}";
private static readonly string post = "line://home/public/post?id={0}&postId={1}";
private static readonly string msgText = "line://msg/text/{0}";
private static readonly string oaMessage = "line://oaMessage/{0}/?{1}";
/// <summary>
/// Opens the camera screen.
/// </summary>
/// <returns>String of LINE Scheme URL</returns>
public static string GetCameraUrl => camera;
/// <summary>
/// Opens the camera screen.
/// </summary>
/// <returns>URI template action</returns>
public static UriTemplateAction GetCameraUriTemplateAction(string label) => new UriTemplateAction(label, GetCameraUrl);
/// <summary>
/// Opens the "Camera Roll" screen where users can select one image to share in the chat.
/// </summary>
/// <returns>String of LINE Scheme URL</returns>
public static string GetCameraRollSingleUrl => cameraRollSingle;
/// <summary>
/// Opens the "Camera Roll" screen where users can select multiple images to share in the chat.
/// </summary>
/// <returns>String of LINE Scheme URL</returns>
public static string GetCameraRollMultiUrl => cameraRollMulti;
/// <summary>
/// Opens the "Location" screen. Users can share the current location or drop a pin on the map to select the location they want to share.
/// </summary>
/// <remarks>
/// Note: This scheme is only supported in one-on-one chats between a user and a bot(LINE@ account).
/// Not supported on external apps or other types of LINE chats.
///</remarks>
/// <returns>String of LINE Scheme URL</returns>
public static string GetLocationUrl => location;
/// <summary>
/// Opens one of the following screens depending on the user's friendship status with the bot.<para>
/// Friend of bot: Opens the chat with the bot.</para><para>
/// Not a friend or blocked by user: Opens the "Add friend" screen for your bot.</para>
/// </summary>
/// <param name="lineId">
/// Find the LINE ID of your bot on the LINE@ Manager. Make sure you include the "@" symbol in the LINE ID.
/// </param>
/// <returns>String of LINE Scheme URL</returns>
public static string GetAddFriendUrl(string lineId) => string.Format(addFriend, lineId);
/// <summary>
/// Opens the "Share with" screen where users can select friends, groups, or chats to share a link to your bot.
/// </summary>
/// <param name="lineId">
/// Find the LINE ID of your bot on the LINE@ Manager. Make sure you include the "@" symbol in the LINE ID.
/// </param>
/// <returns>String of LINE Scheme URL</returns>
public static string GetRemommendUrl(string lineId) => string.Format(recommendOA, lineId);
/// <summary>
/// Opens the Timeline screen for your bot.
/// </summary>
/// <param name="lineIdWithoutAt">
/// Do not include the "@" symbol in the LINE ID.Find the LINE ID of your bot on the LINE@ Manager.
/// </param>
/// <returns>String of LINE Scheme URL</returns>
public static string GetMainUrl(string lineIdWithoutAt) => string.Format(main, lineIdWithoutAt);
/// <summary>
/// Opens the account page for your bot.
/// </summary>
/// <param name="lineIdWithoutAt">
/// Do not include the "@" symbol in the LINE ID.Find the LINE ID of your bot on the LINE@ Manager.
/// </param>
/// <returns>String of LINE Scheme URL</returns>
public static string GetProfileUrl(string lineIdWithoutAt) => string.Format(profile, lineIdWithoutAt);
/// <summary>
/// Opens a specific Timeline post for your bot.
/// You can find the post ID of individual posts in the "Timeline (Home)" section of the LINE@ Manager.
/// </summary>
/// <param name="lineIdWithoutAt">
/// Do not include the "@" symbol in the LINE ID.Find the LINE ID of your bot on the LINE@ Manager.
/// </param>
/// <param name="postId">post ID</param>
/// <returns>String of LINE Scheme URL</returns>
public static string GetPostUrl(string lineIdWithoutAt, string postId) => string.Format(post, lineIdWithoutAt, postId);
/// <summary>
/// Opens the "Share with" screen where users can select friends, groups, or chats to send a preset text message.<para>
/// Users can also post the message as a note in a chat or post the message to Timeline.</para>
/// </summary>
/// <param name="textMessage"></param>
/// <returns>String of LINE Scheme URL</returns>
public static string GetMsgTextUrl(string textMessage) => string.Format(msgText, Uri.EscapeUriString(textMessage));
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.