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 |
|---|---|---|---|---|---|---|---|---|
5e781a63e4a16583441286569f18fcbc52742339 | add MathTypeConverter | yufeih/Common | MathTypeConverter.cs | MathTypeConverter.cs | namespace System
{
using Globalization;
using System.Linq;
static class MathTypeConverter
{
public static T[] FromText<T>(string text, int count, Func<string, T> parse)
{
if (string.IsNullOrEmpty(text)) return null;
var i = 0;
var result = new T[count];
foreach (var part in text.Split(',').Take(count).Select(p => p.Trim()))
{
if (string.IsNullOrEmpty(part))
{
result[i++] = default(T);
}
else
{
result[i++] = parse(part);
}
}
return result;
}
public static string ToText(params float[] values)
{
for (var i = values.Length - 1; i >= 0; i--)
{
if (values[i] != 0)
{
return string.Join(",", values.Take(i + 1).Select(_ => _.ToString(CultureInfo.InvariantCulture)));
}
}
return "";
}
public static string ToText(params double[] values)
{
for (var i = values.Length - 1; i >= 0; i--)
{
if (values[i] != 0)
{
return string.Join(",", values.Take(i + 1).Select(_ => _.ToString(CultureInfo.InvariantCulture)));
}
}
return "";
}
public static string ToText<T>(params T[] values)
{
for (var i = values.Length - 1; i >= 0; i--)
{
// Ignore default values
if (!Equals(values[i], default(T)))
{
return string.Join(",", values.Take(i + 1));
}
}
return "";
}
}
}
| mit | C# | |
35bc451136be7e748c09810b1adc509d5d3d8c6a | Create UnityEventOnKeyUp.cs | felladrin/unity-scripts,felladrin/unity3d-scripts | UnityEventOnKeyUp.cs | UnityEventOnKeyUp.cs | using UnityEngine;
using UnityEngine.Events;
public class UnityEventOnKeyUp : MonoBehaviour
{
public KeyCode Key;
public KeyCode ComboKey;
public UnityEvent OnKeyDown;
void Update()
{
if (ComboKey == KeyCode.None)
{
if (Input.GetKeyUp(Key)) OnKeyDown.Invoke();
}
else
{
if (Input.GetKey(ComboKey) && Input.GetKeyUp(Key)) OnKeyDown.Invoke();
}
}
}
| mit | C# | |
31d6c0504bf805793004d92861abfce93f5687e1 | Create FindDigits.cs | costincaraivan/hackerrank,costincaraivan/hackerrank | algorithms/implementation/C#/FindDigits.cs | algorithms/implementation/C#/FindDigits.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int t = Convert.ToInt32(Console.ReadLine());
for(int a0 = 0; a0 < t; a0++){
int n = Convert.ToInt32(Console.ReadLine());
var count = 0;
var digits = n.ToString();
foreach (var digit in digits)
{
if (Int32.Parse(digit.ToString()) != 0)
{
if (n % Int32.Parse(digit.ToString()) == 0)
{
count += 1;
}
}
}
Console.WriteLine(count);
}
}
}
| mit | C# | |
7faeef18900e356eb0bb92df9c1289a376e6adb0 | Create task_1_3_8_2_age.cs | AndrewTurlanov/ANdrew | task_1_3_8_2_age.cs | task_1_3_8_2_age.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите свой возраст");
int UserAge = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= UserAge; i++)
{
Console.WriteLine("Поздравляю!");
}
}
}
}
| apache-2.0 | C# | |
66e655e33a764b6676550ece9fe9e54618f95b8e | Create OpenApiClient.cs | daniela1991/hack4europecontest | OpenApiClient.cs | OpenApiClient.cs | using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Cdiscount.OpenApi.ProxyClient.Config;
using Cdiscount.OpenApi.ProxyClient.Contract.Common;
using Cdiscount.OpenApi.ProxyClient.Contract.GetCart;
using Cdiscount.OpenApi.ProxyClient.Contract.GetProduct;
using Cdiscount.OpenApi.ProxyClient.Contract.PushToCart;
using Cdiscount.OpenApi.ProxyClient.Contract.Search;
using Newtonsoft.Json;
namespace Cdiscount.OpenApi.ProxyClient
{
/// <summary>
/// Proxy client to interact with the Cdiscount OpenApi
/// </summary>
public class OpenApiClient
{
/// <summary>
/// Configuration setting used for remote calls
/// </summary>
private ProxyClientConfig _configuration;
/// <summary>
/// Create a proxy for the Cdiscount api
/// </summary>
/// <param name="configuration">Configuration setting</param>
public OpenApiClient(ProxyClientConfig configuration)
{
_configuration = configuration;
}
/// <summary>
/// Generic method used to send a request to the Api
/// </summary>
/// <param name="requestUri">Request Uri</param>
/// <param name="requestMessage">Request Message</param>
/// <returns>Request response message</returns>
private static T Post<T>(string requestUri, object requestMessage) where T : BaseResponseMessage
{
T result;
var jsonObject = JsonConvert.SerializeObject(requestMessage);
using (var httpClient = new BaseHttpClient())
using (var content = new BaseHttpContent(jsonObject))
using (HttpResponseMessage response = httpClient.PostAsync(requestUri, content).Result)
{
response.EnsureSuccessStatusCode();
Task<string> responseBody = response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<T>(responseBody.Result);
result.OperationSuccess = true;
}
return result;
}
/// <summary>
/// Method used to add an item to a (new) cart
/// </summary>
/// <param name="request">Request parameters</param>
/// <returns>Cart reference</returns>
public PushToCartResponse PushToCart(PushToCartRequest request)
{
var requestMessage = new PushToCartRequestWrapper
{
ApiKey = _configuration.ApiKey,
PushToCartRequest = request
};
return Post<PushToCartResponse>("OpenApi/json/PushToCart", requestMessage);
}
/// <summary>
/// Retrieve a cart with all its details
/// </summary>
/// <param name="request">Cart to retrieve</param>
/// <returns>Cart content</returns>
public GetCartResponse GetCart(GetCartRequest request)
{
var requestMessage = new GetCartRequestWrapper
{
ApiKey = _configuration.ApiKey,
CartRequest = request
};
return Post<GetCartResponse>("OpenApi/json/GetCart", requestMessage);
}
public GetProductResponse GetProduct(GetProductRequest request)
{
var requestMessage = new GetProductRequestWrapper()
{
ApiKey = _configuration.ApiKey,
ProductRequest = request
};
return Post<GetProductResponse>("OpenApi/json/GetProduct", requestMessage);
}
public SearchResponse Search(SearchRequest request)
{
if (request != null && request.Pagination == null)
{
request.Pagination = new SearchRequestPagination();
}
var requestMessage = new SearchRequestWrapper()
{
ApiKey = _configuration.ApiKey,
SearchRequest = request
};
return Post<SearchResponse>("OpenApi/json/Search", requestMessage);
}
}
}
| mit | C# | |
664cd3002aa286b815a41576905a7331b3288ae0 | Create ZeroGMovement.cs | scmcom/unitycode | ZeroGMovement.cs | ZeroGMovement.cs | //===================================================
// defines 3D zero gravity physics per KEYBOARD input
// KEYBOARD INPUTS - CHANGE POSITION VECTOR
//
// up, down, left-sidestep, right-sidestep, up, back
// W A S D keys
// OR
// < > ^ down (arrow keys)
//===================================================
using UnityEngine;
using System.Collections;
public class ZeroGMovement : MonoBehaviour {
//public variables for vertical & horizontal axes
public string forwardAxisName = "Vertical";
public string horizontalAxisName = "Horizontal";
public float force = 10.0f;
public ForceMode forceMode;
// Use this for initialization
void Start () {}
// FixedUpdate for physics
void FixedUpdate (){
//direction of gravitation force in 3D space
Vector3 forceDirection = new Vector3(Input.GetAxis(horizontalAxisName), 0.0f, Input.GetAxis(forwardAxisName)).normalized;
//get position / transform of rigidbody for player controller in 3D space, apply gravity force
GetComponent<Rigidbody>().AddForce(transform.rotation * forceDirection*force, forceMode);
}
}
| mit | C# | |
7ac0da49140c3c723fe17c072f9eca8f02630af5 | Add date time passing practices. | AxeDotNet/AxePractice.CSharpViaTest | src/CSharpViaTest.OtherBCLs/HandleDates/PassingDateTimeBetweenDifferentCultures.cs | src/CSharpViaTest.OtherBCLs/HandleDates/PassingDateTimeBetweenDifferentCultures.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace CSharpViaTest.OtherBCLs.HandleDates
{
/*
* Description
* ===========
*
* This test will try passing date time between the boundary (e.g. via HTTP).
* And the culture information at each site is different. You have to pass
* the date time accurately.
*
* Difficulty: Super Easy
*
* Knowledge Point
* ===============
*
* - DateTime.ParseExtact / DateTime.Parse
* - DateTime.ToString(string, IFormatProvider)
*/
public class PassingDateTimeBetweenDifferentCultures
{
class CultureContext : IDisposable
{
readonly CultureInfo old;
public CultureContext(CultureInfo culture)
{
old = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = culture;
}
public void Dispose()
{
CultureInfo.CurrentCulture = old;
}
}
#region Please modifies the code to pass the test
static DateTime DeserializeDateTimeFromTargetSite(string serialized)
{
throw new NotImplementedException();
}
static string SerializeDateTimeFromCallerSite(DateTime dateTime)
{
throw new NotImplementedException();
}
#endregion
[Theory]
[MemberData(nameof(GetDateTimeForDifferentCultures))]
public void should_pass_date_time_correctly_between_different_cultures(
DateTime expected,
CultureInfo from,
CultureInfo to)
{
string serialized;
using (new CultureContext(from))
{
serialized = SerializeDateTimeFromCallerSite(expected);
}
using (new CultureContext(to))
{
DateTime deserialized = DeserializeDateTimeFromTargetSite(serialized);
Assert.Equal(expected.ToUniversalTime(), deserialized.ToUniversalTime());
}
}
static IEnumerable<object[]> GetDateTimeForDifferentCultures()
{
return new[]
{
new object[] {new DateTime(2012, 8, 1, 0, 0, 0, DateTimeKind.Utc), new CultureInfo("zh-CN"), new CultureInfo("tr-TR")},
new object[] {new DateTime(2012, 8, 1, 0, 0, 0, DateTimeKind.Utc), new CultureInfo("ja-JP"), new CultureInfo("en-US")}
};
}
}
} | mit | C# | |
622599fda7bf8ffbbabc656d744bbf5312bae990 | Create RandomExtensions.cs | keith-hall/Extensions,keith-hall/Extensions | src/RandomExtensions.cs | src/RandomExtensions.cs | using System;
namespace HallLibrary.Extensions
{
public static class RandomExtensionMethods
{
/// <summary>
/// Returns a random long from min (inclusive) to max (exclusive).
/// </summary>
/// <param name="random">The given random instance.</param>
/// <param name="min">The inclusive minimum bound.</param>
/// <param name="max">The exclusive maximum bound. Must be greater than <paramref name="min" />.</param>
/// <remarks>Code taken from http://stackoverflow.com/a/13095144/4473405</remarks>
public static long NextLong(this Random random, long min, long max)
{
if (max <= min)
throw new ArgumentOutOfRangeException(nameof(max), string.Format("{0} must be > {1}!", nameof(max), nameof(min)));
// Working with ulong so that modulo works correctly with values > long.MaxValue
ulong uRange = (ulong)(max - min);
// Prevent a modolo bias; see http://stackoverflow.com/a/10984975/238419
// for more information.
// In the worst case, the expected number of calls is 2 (though usually it's
// much closer to 1) so this loop doesn't really hurt performance at all.
ulong ulongRand;
do
{
byte[] buf = new byte[8];
random.NextBytes(buf);
ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
} while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);
return (long)(ulongRand % uRange) + min;
}
}
}
| apache-2.0 | C# | |
2dcf6e2d8318d9b71ebc9514fcd489acce6bd8b9 | Create IMongoClientSessionProvider.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/Mongo/IMongoClientSessionProvider.cs | TIKSN.Core/Data/Mongo/IMongoClientSessionProvider.cs | using LanguageExt;
using MongoDB.Driver;
namespace TIKSN.Data.Mongo
{
public interface IMongoClientSessionProvider
{
Option<IClientSessionHandle> GetClientSessionHandle();
}
} | mit | C# | |
3328d5d7e51e23f90afd7b5d110b77500c14d63b | bump version | modulexcite/Anotar,mstyura/Anotar,distantcam/Anotar,Fody/Anotar | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("2.11.1")]
[assembly: AssemblyFileVersion("2.11.1")]
| using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("2.11.0")]
[assembly: AssemblyFileVersion("2.11.0")]
| mit | C# |
15ce7bacf1fcc319916f9365643f5ef1e73f26d6 | Add test coverage for confine functionality | smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu | osu.Game.Tests/Input/ConfineMouseTrackerTest.cs | osu.Game.Tests/Input/ConfineMouseTrackerTest.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.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Input;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.Input;
using osu.Game.Tests.Visual.Navigation;
namespace osu.Game.Tests.Input
{
[HeadlessTest]
public class ConfineMouseTrackerTest : OsuGameTestScene
{
[Resolved]
private FrameworkConfigManager frameworkConfigManager { get; set; }
[Resolved]
private OsuConfigManager osuConfigManager { get; set; }
[TestCase(WindowMode.Windowed)]
[TestCase(WindowMode.Borderless)]
public void TestDisableConfining(WindowMode windowMode)
{
setWindowModeTo(windowMode);
setGameSideModeTo(OsuConfineMouseMode.Never);
gameSideConfineModeDisabled(false);
setLocalUserPlayingTo(false);
frameworkSideModeIs(ConfineMouseMode.Never);
setLocalUserPlayingTo(true);
frameworkSideModeIs(ConfineMouseMode.Never);
}
[TestCase(WindowMode.Windowed)]
[TestCase(WindowMode.Borderless)]
public void TestConfiningDuringGameplay(WindowMode windowMode)
{
setWindowModeTo(windowMode);
setGameSideModeTo(OsuConfineMouseMode.DuringGameplay);
gameSideConfineModeDisabled(false);
setLocalUserPlayingTo(false);
frameworkSideModeIs(ConfineMouseMode.Never);
setLocalUserPlayingTo(true);
frameworkSideModeIs(ConfineMouseMode.Always);
}
[TestCase(WindowMode.Windowed)]
[TestCase(WindowMode.Borderless)]
public void TestConfineAlwaysUserSetting(WindowMode windowMode)
{
setWindowModeTo(windowMode);
setGameSideModeTo(OsuConfineMouseMode.Always);
gameSideConfineModeDisabled(false);
setLocalUserPlayingTo(false);
frameworkSideModeIs(ConfineMouseMode.Always);
setLocalUserPlayingTo(true);
frameworkSideModeIs(ConfineMouseMode.Always);
}
[Test]
public void TestConfineAlwaysInFullscreen()
{
setGameSideModeTo(OsuConfineMouseMode.Never);
setWindowModeTo(WindowMode.Fullscreen);
gameSideConfineModeDisabled(true);
setLocalUserPlayingTo(false);
frameworkSideModeIs(ConfineMouseMode.Always);
setLocalUserPlayingTo(true);
frameworkSideModeIs(ConfineMouseMode.Always);
setWindowModeTo(WindowMode.Windowed);
// old state is restored
gameSideModeIs(OsuConfineMouseMode.Never);
frameworkSideModeIs(ConfineMouseMode.Never);
gameSideConfineModeDisabled(false);
}
private void setWindowModeTo(WindowMode mode)
// needs to go through .GetBindable().Value instead of .Set() due to default overrides
=> AddStep($"make window {mode}", () => frameworkConfigManager.GetBindable<WindowMode>(FrameworkSetting.WindowMode).Value = mode);
private void setGameSideModeTo(OsuConfineMouseMode mode)
=> AddStep($"set {mode} game-side", () => Game.LocalConfig.Set(OsuSetting.ConfineMouseMode, mode));
private void setLocalUserPlayingTo(bool playing)
=> AddStep($"local user {(playing ? "playing" : "not playing")}", () => Game.LocalUserPlaying.Value = playing);
private void gameSideModeIs(OsuConfineMouseMode mode)
=> AddAssert($"mode is {mode} game-side", () => Game.LocalConfig.Get<OsuConfineMouseMode>(OsuSetting.ConfineMouseMode) == mode);
private void frameworkSideModeIs(ConfineMouseMode mode)
=> AddAssert($"mode is {mode} framework-side", () => frameworkConfigManager.Get<ConfineMouseMode>(FrameworkSetting.ConfineMouseMode) == mode);
private void gameSideConfineModeDisabled(bool disabled)
=> AddAssert($"game-side confine mode {(disabled ? "disabled" : "enabled")}",
() => Game.LocalConfig.GetBindable<OsuConfineMouseMode>(OsuSetting.ConfineMouseMode).Disabled == disabled);
}
}
| mit | C# | |
6a00f499d292644365f874b31cec4f6a63d8094c | add PagedRequest | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common/Models/PagedRequest.cs | src/WeihanLi.Common/Models/PagedRequest.cs | namespace WeihanLi.Common.Models
{
public class PagedRequest
{
private int _pageNum = 1;
private int _pageSize = 10;
public int PageNum
{
get => _pageNum;
set => _pageNum = value > 0 ? value : 1;
}
public int PageSize
{
get => _pageSize;
set => _pageSize = value > 0 ? value : 10;
}
}
}
| mit | C# | |
03a816f19d5e31b99a718646a18852d2785c1f32 | Add Peek tests | StevenLiekens/Txt,StevenLiekens/TextFx | test/Txt.Core.Tests/TextSourceTests.Peek.cs | test/Txt.Core.Tests/TextSourceTests.Peek.cs | using Xunit;
namespace Txt.Core
{
public partial class TextSourceTests
{
public class Peek
{
[Fact]
public void EmptyData()
{
var sut = new StringTextSource("");
Assert.Equal(-1, sut.Peek());
Assert.Equal(0, sut.Offset);
Assert.Equal(1, sut.Line);
Assert.Equal(1, sut.Column);
}
[Theory]
[InlineData("0")]
[InlineData("9")]
[InlineData("!")]
[InlineData("A")]
[InlineData("Z")]
[InlineData("ù")]
[InlineData("☕")]
[InlineData("\0")]
[InlineData("\uFFFF")]
public void NonEmptyData(string data)
{
var sut = new StringTextSource(data);
Assert.Equal(data, char.ToString((char)sut.Peek()));
Assert.Equal(0, sut.Offset);
Assert.Equal(1, sut.Line);
Assert.Equal(1, sut.Column);
}
}
}
}
| mit | C# | |
764e23fa32e348e281938b6d9301a28cfe26eb77 | add impl for ICapTransaction | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP/ICapTransaction.Base.cs | src/DotNetCore.CAP/ICapTransaction.Base.cs | using System.Collections.Generic;
using DotNetCore.CAP.Models;
namespace DotNetCore.CAP
{
public abstract class CapTransactionBase : ICapTransaction
{
private readonly IDispatcher _dispatcher;
private readonly IList<CapPublishedMessage> _bufferList;
protected CapTransactionBase(IDispatcher dispatcher)
{
_dispatcher = dispatcher;
_bufferList = new List<CapPublishedMessage>(1);
}
public bool AutoCommit { get; set; }
public object DbTransaction { get; set; }
protected internal void AddToSent(CapPublishedMessage msg)
{
_bufferList.Add(msg);
}
protected void Flush()
{
foreach (var message in _bufferList)
{
_dispatcher.EnqueueToPublish(message);
}
}
public abstract void Commit();
public abstract void Rollback();
public abstract void Dispose();
}
}
| mit | C# | |
076e498a6378b07dcae67e4b06bfde1d0f6f565c | create abstract class OverlaySidebar | peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu | osu.Game/Overlays/OverlaySidebar.cs | osu.Game/Overlays/OverlaySidebar.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 JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays
{
public abstract class OverlaySidebar : CompositeDrawable
{
private readonly Box sidebarBackground;
private readonly Box scrollbarBackground;
protected OverlaySidebar()
{
RelativeSizeAxes = Axes.Y;
Width = 250;
InternalChildren = new Drawable[]
{
sidebarBackground = new Box
{
RelativeSizeAxes = Axes.Both,
},
scrollbarBackground = new Box
{
RelativeSizeAxes = Axes.Y,
Width = OsuScrollContainer.SCROLL_BAR_HEIGHT,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Alpha = 0.5f
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Right = -3 }, // Compensate for scrollbar margin
Child = new OsuScrollContainer
{
RelativeSizeAxes = Axes.Both,
Child = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Right = 3 }, // Addeded 3px back
Child = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding
{
Vertical = 20,
Left = 50,
Right = 30
},
Child = CreateContent()
}
}
}
}
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
sidebarBackground.Colour = colourProvider.Background4;
scrollbarBackground.Colour = colourProvider.Background3;
}
[NotNull]
protected virtual Drawable CreateContent() => Empty();
}
}
| mit | C# | |
0247e55bf604f761310606e9fc42ad8ffd314612 | Insert sort | sylviot/algoritmos,sylviot/algoritmos,sylviot/algoritmos | sorting/Insert.cs | sorting/Insert.cs | using System;
public class InsertSort
{
public static void Main()
{
// Array de exemplo.
int[] array = new int[] { 2, 3, 1, 5, 4 };
// Resultado da ordenação do array de exemplo.
int[] arraySorted = Insert(array);
foreach(var item in arraySorted){
Console.WriteLine(item);
}
}
public static int[] Insert(int[] array)
{
for(int i = 1; i < array.Length; i++)
{
// Point é o número que deve andar para esquerda enquanto precisar trocar (NeedSwap).
int point = array[i];
// Cursor é utilizado para sabe onde foi a ultima troca do Point.
int cursor = i;
// Enquanto cursor poder andar para esquerda (maior que zero)
// e ter a necessida de de trocar de posição (NeedSwap)
while((cursor > 0) && NeedSwap(array[cursor-1], point))
{
// cópia o valor da esquerda para a posição atual do cursor.
array[cursor] = array[cursor - 1];
// cursor movendo para esquerda
cursor--;
}
// posição até onde o cursor se moveu deve receber o valor do point
array[cursor] = point;
}
return array;
}
// Verifica a necessidade da troca de posição entre A e B.
// a > b faz com que todos da esquerda tenham que ser menor que o da direita.
// a < b faz com que todos da esquerda tenham que ser maior que o da direita.
public static bool NeedSwap(int a, int b)
{
return a > b;
}
} | mit | C# | |
119de2e1e5a908bcdc396c7c93e64604359881d7 | add credit card balance | borismod/FinBotApp,idoban/FinBotApp,idoban/FinBotApp,borismod/FinBotApp | FinBot/Engine/CreditBalanceAdapter.cs | FinBot/Engine/CreditBalanceAdapter.cs | using Syn.Bot.Siml;
namespace FinBot.Engine
{
public class CreditBalanceAdapter : BaseAdapter
{
private readonly IFinancialServices _financialServices;
public CreditBalanceAdapter(IFinancialServices financialServices)
{
_financialServices = financialServices;
}
public override string Evaluate(Context context)
{
return _financialServices.GetCreditCardBalance().ToString();
}
}
} | mit | C# | |
7df10c7f024330d9d51251ff85b255db6b3f8704 | Add test properties | brandonio21/update.net | update.net_test/Properties/AssemblyInfo.cs | update.net_test/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("update.net_test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("update.net_test")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7bab4676-2d26-4d1a-8dbe-72649f1ebb3a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# | |
fb78e2b5fdb4ed78c1930cc1b729cde43615145d | Add script for serializing level data | jguarShark/Unity2D-Components,cmilr/Unity2D-Components | Level/LevelData.cs | Level/LevelData.cs | using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using UnityEngine;
public class LevelData : BaseBehaviour
{
public int HP { get; set; }
public int AC { get; set; }
public int Damage { get; set; }
public void Save()
{
var bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/LevelData.dat");
var container = new LevelDataContainer();
container.hp = HP;
container.ac = AC;
container.damage = Damage;
bf.Serialize(file, container);
file.Close();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/LevelData.dat"))
{
var bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/LevelData.dat",FileMode.Open);
var container = (LevelDataContainer)bf.Deserialize(file);
file.Close();
HP = container.hp;
AC = container.ac;
Damage = container.damage;
}
}
void OnSaveLevelData(bool status)
{
Save();
}
void OnLoadLevelData(bool status)
{
Load();
}
void OnEnable()
{
EventKit.Subscribe<bool>("save level data", OnSaveLevelData);
EventKit.Subscribe<bool>("load level data", OnLoadLevelData);
}
void OnDestroy()
{
EventKit.Unsubscribe<bool>("save level data", OnSaveLevelData);
EventKit.Unsubscribe<bool>("load level data", OnLoadLevelData);
}
}
[Serializable]
class LevelDataContainer
{
public int hp;
public int ac;
public int damage;
}
| mit | C# | |
3e1371252905d8b9b297fad8fca15305525c84b0 | add currentUser remove NCMBMenu for #57 | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/NCMB/NCMBMenu.cs | ncmb_unity/Assets/NCMB/NCMBMenu.cs | using System.IO;
using UnityEditor;
using UnityEngine;
namespace NCMB
{
internal class NCMBMenu
{
[MenuItem ("NCMB/DeleteCurrentUserCache")]
private static void DeleteCurrentUserCache ()
{
File.Delete (Application.persistentDataPath + "/" + "currentUser");
Debug.Log ("CurrentUser cache is deleted");
}
[MenuItem ("NCMB/DeleteCurrentUserCache", true)]
private static bool DeleteCurrentUserCacheValidation ()
{
return (File.Exists (Application.persistentDataPath + "/" + "currentUser"));
}
}
} | apache-2.0 | C# | |
478cfc0b87ac3a6062e5948fe8df496df0fac991 | Split model class for mod state | NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu | osu.Game/Overlays/Mods/ModState.cs | osu.Game/Overlays/Mods/ModState.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.Bindables;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Overlays.Mods
{
/// <summary>
/// Wrapper class used to store the current state of a mod shown on the <see cref="ModSelectOverlay"/>.
/// Used primarily to decouple data from drawable logic.
/// </summary>
public class ModState
{
/// <summary>
/// The mod that whose state this instance describes.
/// </summary>
public Mod Mod { get; }
/// <summary>
/// Whether the mod is currently selected.
/// </summary>
public BindableBool Active { get; } = new BindableBool();
/// <summary>
/// Whether the mod is currently filtered out due to not matching imposed criteria.
/// </summary>
public BindableBool Filtered { get; } = new BindableBool();
public ModState(Mod mod)
{
Mod = mod;
}
}
}
| mit | C# | |
9c6dd28e7d3cc2a24a7a5154d1f4604fd0920c7d | Add IProvideExpenditure class to support data provision | xyon1/Expenditure-App | GeneralUseClasses/Services/IProvideExpenditureData.cs | GeneralUseClasses/Services/IProvideExpenditureData.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GeneralUseClasses.Contracts;
namespace GeneralUseClasses.Services
{
public interface IProvideExpenditureData
{
IEnumerable<string> GetDominantTags();
IEnumerable<string> GetAssociatedTags();
IEnumerable<string> GetPeople();
}
}
| apache-2.0 | C# | |
4c7ba3d93c8e30b9fe81e3d092cf87d2040e993f | Add tagging capability to Dinamico news page | nimore/n2cms,EzyWebwerkstaden/n2cms,nimore/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,n2cms/n2cms,nicklv/n2cms,bussemac/n2cms,nicklv/n2cms,nimore/n2cms,nicklv/n2cms,nicklv/n2cms,n2cms/n2cms,bussemac/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,nimore/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,DejanMilicic/n2cms,nicklv/n2cms,bussemac/n2cms,SntsDev/n2cms,n2cms/n2cms,DejanMilicic/n2cms,DejanMilicic/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,bussemac/n2cms | src/Mvc/Dinamico/Dinamico/Themes/Default/Views/ContentPages/News.cshtml | src/Mvc/Dinamico/Dinamico/Themes/Default/Views/ContentPages/News.cshtml | @model Dinamico.Models.ContentPage
@{
Content.Define(re =>
{
re.Title = "News page";
re.IconUrl = "{IconsUrl}/newspaper.png";
re.DefaultValue("Visible", false);
re.RestrictParents("Container");
re.Sort(N2.Definitions.SortBy.PublishedDescending);
re.Tags("Tags");
});
}
@Html.Partial("LayoutPartials/BlogContent")
@using (Content.BeginScope(Content.Traverse.Parent()))
{
@Content.Render.Tokens("NewsFooter")
}
| @model Dinamico.Models.ContentPage
@{
Content.Define(re =>
{
re.Title = "News page";
re.IconUrl = "{IconsUrl}/newspaper.png";
re.DefaultValue("Visible", false);
re.RestrictParents("Container");
re.Sort(N2.Definitions.SortBy.PublishedDescending);
});
}
@Html.Partial("LayoutPartials/BlogContent")
@using (Content.BeginScope(Content.Traverse.Parent()))
{
@Content.Render.Tokens("NewsFooter")
}
| lgpl-2.1 | C# |
0bdd1131bb4173b2df859fa88cad653b76dd4b6f | Add missing file | abjerner/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS | src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/AddUserLoginDtoDateIndex.cs | src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/AddUserLoginDtoDateIndex.cs | using Umbraco.Core.Persistence.Dtos;
namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
{
public class AddUserLoginDtoDateIndex : MigrationBase
{
public AddUserLoginDtoDateIndex(IMigrationContext context)
: base(context)
{ }
public override void Migrate()
{
if (!IndexExists("IX_umbracoUserLogin_lastValidatedUtc"))
Create.Index("IX_umbracoUserLogin_lastValidatedUtc")
.OnTable(UserLoginDto.TableName)
.OnColumn("lastValidatedUtc")
.Ascending()
.WithOptions().NonClustered()
.Do();
}
}
}
| mit | C# | |
d49694623cc3ccf4377d1e09b2a6d78c5fcae1b5 | Create IntellisenseHelper.cs | Excel-DNA/IntelliSense | IntellisenseHelper.cs | IntellisenseHelper.cs | using System;
using System.Collections.Generic;
using ExcelDna.Integration;
namespace ExcelDna.IntelliSense
{
public class IntellisenseHelper : IDisposable
{
private readonly IntelliSenseDisplay _id;
public IntellisenseHelper()
{
_id = CrossAppDomainSingleton.GetOrCreate();
RegisterIntellisense();
}
void RegisterIntellisense()
{
string xllPath = Win32Helper.GetXllName();
object[,] regInfos = ExcelIntegration.GetRegistrationInfo(xllPath, -1) as object[,];
if (regInfos != null)
{
for (int i = 0; i < regInfos.GetLength(0); i++)
{
if (regInfos[i, 0] is ExcelDna.Integration.ExcelEmpty)
{
string functionName = regInfos[i, 3] as string;
string description = regInfos[i, 9] as string;
string argumentStr = regInfos[i, 4] as string;
string[] argumentNames = string.IsNullOrEmpty(argumentStr) ? new string[0] : argumentStr.Split(',');
List<IntelliSenseFunctionInfo.ArgumentInfo> argumentInfos = new List<IntelliSenseFunctionInfo.ArgumentInfo>();
for (int j = 0; j < argumentNames.Length; j++)
{
argumentInfos.Add(new IntelliSenseFunctionInfo.ArgumentInfo { ArgumentName = argumentNames[j], Description = regInfos[i, j + 10] as string });
}
_id.RegisterFunctionInfo(new IntelliSenseFunctionInfo
{
FunctionName = functionName,
Description = description,
ArgumentList = argumentInfos,
XllPath = xllPath
});
}
}
}
}
public void Dispose()
{
CrossAppDomainSingleton.RemoveReference();
}
}
}
| mit | C# | |
69ea7c7ea4d82c6edc624534cd748bcbf547f841 | Create SerializerException.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/SerializerException.cs | TIKSN.Core/Serialization/SerializerException.cs | using System;
namespace TIKSN.Serialization
{
[Serializable]
public class SerializerException : Exception
{
public SerializerException()
{
}
public SerializerException(string message) : base(message)
{
}
public SerializerException(string message, Exception inner) : base(message, inner)
{
}
protected SerializerException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
} | mit | C# | |
657ced56271a3c2f486d7ce1b1c8d4870ab2b8dd | Create ObjectRotateClamp.cs | zabaglione/ObjectRotateClamp | ObjectRotateClamp.cs | ObjectRotateClamp.cs | using UnityEngine;
using System.Collections;
//
// 元ネタ:http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q11128560141 .
//
public class ObjectRotateClamp : MonoBehaviour {
public float maxAngleH = 60; // 最大回転角度.
public float minAngleH = -60; // 最小回転角度.
public float maxAngleV = 60; // 最大回転角度.
public float minAngleV = -60; // 最小回転角度.
public float speed = 0.5f; // 回転スピード.
void Start () {
}
void Update () {
// 入力情報.
float turnH = Input.GetAxis("Horizontal");
// 現在の回転角度を0~360から-180~180に変換.
float rotateY = (transform.eulerAngles.y > 180) ? transform.eulerAngles.y - 360 : transform.eulerAngles.y;
// 現在の回転角度に入力(turn)を加味した回転角度をMathf.Clamp()を使いminAngleからMaxAngle内に収まるようにする.
float angleY = Mathf.Clamp(rotateY + turnH * speed, minAngleH, maxAngleH);
// 回転角度を-180~180から0~360に変換.
angleY = (angleY < 0) ? angleY + 360 : angleY;
// 入力情報.
float turnV = Input.GetAxis("Vertical");
// 現在の回転角度を0~360から-180~180に変換.
float rotateX = (transform.eulerAngles.x > 180) ? transform.eulerAngles.x - 360 : transform.eulerAngles.x;
// 現在の回転角度に入力(turn)を加味した回転角度をMathf.Clamp()を使いminAngleからMaxAngle内に収まるようにする.
float angleX = Mathf.Clamp(rotateX + turnV * speed, minAngleV, maxAngleV);
// 回転角度を-180~180から0~360に変換.
angleX = (angleX < 0) ? angleX + 360 : angleX;
// 回転角度をオブジェクトに適用.
transform.rotation = Quaternion.Euler(angleX, angleY, 0);
}
}
| mit | C# | |
0cbc716b84dc545522d636f169e19e102b592ea6 | Add Id field to Label model (#1946) | shiftkey/octokit.net,alfhenrik/octokit.net,adamralph/octokit.net,octokit/octokit.net,octokit/octokit.net,shiftkey/octokit.net,alfhenrik/octokit.net | Octokit/Models/Response/Label.cs | Octokit/Models/Response/Label.cs | using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Label
{
public Label() { }
public Label(long id, string url, string name, string nodeId, string color, string description, bool @default)
{
Id = id;
Url = url;
Name = name;
NodeId = nodeId;
Color = color;
Description = description;
Default = @default;
}
/// <summary>
/// Id of the label
/// </summary>
public long Id { get; protected set; }
/// <summary>
/// Url of the label
/// </summary>
public string Url { get; protected set; }
/// <summary>
/// Name of the label
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// GraphQL Node Id
/// </summary>
public string NodeId { get; protected set; }
/// <summary>
/// Color of the label
/// </summary>
public string Color { get; protected set; }
/// <summary>
/// Description of the label
/// </summary>
public string Description { get; protected set; }
/// <summary>
/// Is default label
/// </summary>
public bool Default { get; protected set; }
internal string DebuggerDisplay
{
get { return string.Format(CultureInfo.InvariantCulture, "Name: {0} Color: {1}", Name, Color); }
}
}
}
| using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Label
{
public Label() { }
public Label(string url, string name, string nodeId, string color, string description, bool @default)
{
Url = url;
Name = name;
NodeId = nodeId;
Color = color;
Description = description;
Default = @default;
}
/// <summary>
/// Url of the label
/// </summary>
public string Url { get; protected set; }
/// <summary>
/// Name of the label
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// GraphQL Node Id
/// </summary>
public string NodeId { get; protected set; }
/// <summary>
/// Color of the label
/// </summary>
public string Color { get; protected set; }
/// <summary>
/// Description of the label
/// </summary>
public string Description { get; protected set; }
/// <summary>
/// Is default label
/// </summary>
public bool Default { get; protected set; }
internal string DebuggerDisplay
{
get { return string.Format(CultureInfo.InvariantCulture, "Name: {0} Color: {1}", Name, Color); }
}
}
}
| mit | C# |
29677f8895436a0eef540c335b51517a0ec71c78 | bump up version to 1.0.0.5 | Azure/durabletask,yonglehou/durabletask,affandar/durabletask,jasoneilts/durabletask,ddobric/durabletask | Framework/Properties/AssemblyInfo.cs | Framework/Properties/AssemblyInfo.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 System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Durable Task Framework")]
[assembly:
AssemblyDescription(
@"This package provides a C# based durable Task framework for writing long running applications."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Durable Task Framework")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")]
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyFileVersion("1.0.0.5")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")] | // ----------------------------------------------------------------------------------
// 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 System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Durable Task Framework")]
[assembly:
AssemblyDescription(
@"This package provides a C# based durable Task framework for writing long running applications."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Durable Task Framework")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1d626d8b-330b-4c6a-b689-c0fefbeb99cd")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")] | apache-2.0 | C# |
a593f588db95a8ac6b8bb2594c1a94909ade9c5f | Add a test for the realtime room manager | NeoAdonis/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu | osu.Game.Tests/Visual/RealtimeMultiplayer/TestSceneRealtimeRoomManager.cs | osu.Game.Tests/Visual/RealtimeMultiplayer/TestSceneRealtimeRoomManager.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.Game.Online.Multiplayer;
namespace osu.Game.Tests.Visual.RealtimeMultiplayer
{
public class TestSceneRealtimeRoomManager : MultiplayerTestScene
{
private TestRealtimeRoomContainer roomContainer;
private TestRealtimeRoomManager roomManager => roomContainer.RoomManager;
[Test]
public void TestPollsInitially()
{
AddStep("create room manager with a few rooms", () =>
{
createRoomManager().With(d => d.OnLoadComplete += _ =>
{
roomManager.CreateRoom(new Room { Name = { Value = "1" } });
roomManager.PartRoom();
roomManager.CreateRoom(new Room { Name = { Value = "2" } });
roomManager.PartRoom();
roomManager.ClearRooms();
});
});
AddAssert("manager polled for rooms", () => roomManager.Rooms.Count == 2);
AddAssert("initial rooms received", () => roomManager.InitialRoomsReceived.Value);
}
[Test]
public void TestRoomsClearedOnDisconnection()
{
AddStep("create room manager with a few rooms", () =>
{
createRoomManager().With(d => d.OnLoadComplete += _ =>
{
roomManager.CreateRoom(new Room());
roomManager.PartRoom();
roomManager.CreateRoom(new Room());
roomManager.PartRoom();
});
});
AddStep("disconnect", () => roomContainer.Client.Disconnect());
AddAssert("rooms cleared", () => roomManager.Rooms.Count == 0);
AddAssert("initial rooms not received", () => !roomManager.InitialRoomsReceived.Value);
}
[Test]
public void TestRoomsPolledOnReconnect()
{
AddStep("create room manager with a few rooms", () =>
{
createRoomManager().With(d => d.OnLoadComplete += _ =>
{
roomManager.CreateRoom(new Room());
roomManager.PartRoom();
roomManager.CreateRoom(new Room());
roomManager.PartRoom();
});
});
AddStep("disconnect", () => roomContainer.Client.Disconnect());
AddStep("connect", () => roomContainer.Client.Connect());
AddAssert("manager polled for rooms", () => roomManager.Rooms.Count == 2);
AddAssert("initial rooms received", () => roomManager.InitialRoomsReceived.Value);
}
[Test]
public void TestRoomsNotPolledWhenJoined()
{
AddStep("create room manager with a room", () =>
{
createRoomManager().With(d => d.OnLoadComplete += _ =>
{
roomManager.CreateRoom(new Room());
roomManager.ClearRooms();
});
});
AddAssert("manager not polled for rooms", () => roomManager.Rooms.Count == 0);
AddAssert("initial rooms not received", () => !roomManager.InitialRoomsReceived.Value);
}
private TestRealtimeRoomManager createRoomManager()
{
Child = roomContainer = new TestRealtimeRoomContainer
{
RoomManager =
{
TimeBetweenListingPolls = { Value = 1 },
TimeBetweenSelectionPolls = { Value = 1 }
}
};
return roomManager;
}
}
}
| mit | C# | |
c105453b7c0f8f742c0db0aa1fbd1b625ccf59ac | Add text builder benchmark | ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | osu.Framework.Benchmarks/BenchmarkTextBuilder.cs | osu.Framework.Benchmarks/BenchmarkTextBuilder.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.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Text;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTextBuilder
{
private readonly ITexturedGlyphLookupStore store = new TestStore();
private TextBuilder textBuilder;
[Benchmark]
public void AddCharacters() => initialiseBuilder(false);
[Benchmark]
public void RemoveLastCharacter()
{
initialiseBuilder(false);
textBuilder.RemoveLastCharacter();
}
private void initialiseBuilder(bool allDifferentBaselines)
{
textBuilder = new TextBuilder(store, FontUsage.Default);
char different = 'B';
for (int i = 0; i < 100; i++)
textBuilder.AddCharacter(i % (allDifferentBaselines ? 1 : 10) == 0 ? different++ : 'A');
}
private class TestStore : ITexturedGlyphLookupStore
{
public ITexturedCharacterGlyph Get(string fontName, char character) => new TexturedCharacterGlyph(new CharacterGlyph(character, character, character, character, null), Texture.WhitePixel);
public Task<ITexturedCharacterGlyph> GetAsync(string fontName, char character) => Task.Run(() => Get(fontName, character));
}
}
}
| mit | C# | |
afc942b001cb3835f048a57c36f689d8d72669de | Bring TimedExpiryGlyphStore back from the dead | peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework | osu.Framework/IO/Stores/TimedExpiryGlyphStore.cs | osu.Framework/IO/Stores/TimedExpiryGlyphStore.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.
// 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 SharpFNT;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.IO.Stores
{
/// <summary>
/// A glyph store which caches font sprite sheets in memory temporary, to allow for more efficient retrieval.
/// </summary>
/// <remarks>
/// This store has a higher memory overhead than <see cref="RawCachingGlyphStore"/>, but better performance and zero disk footprint.
/// </remarks>
public class TimedExpiryGlyphStore : GlyphStore
{
private readonly TimedExpiryCache<int, Image<Rgba32>> texturePages = new TimedExpiryCache<int, Image<Rgba32>>();
public TimedExpiryGlyphStore(ResourceStore<byte[]> store, string assetName = null)
: base(store, assetName)
{
}
protected override Image<Rgba32> GetPageImageForCharacter(Character character)
{
if (!texturePages.TryGetValue(character.Page, out var image))
{
loadedPageCount++;
texturePages.Add(character.Page, image = base.GetPageImageForCharacter(character));
}
return image;
}
private int loadedPageCount;
public override string ToString() => $@"GlyphStore({AssetName}) LoadedPages:{loadedPageCount} LoadedGlyphs:{LoadedGlyphCount}";
protected override void Dispose(bool disposing)
{
texturePages.Dispose();
}
}
}
| mit | C# | |
5ba524bab11adb60580e0d25b5f75f3ef98b2386 | increment version | AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,bjartebore/azure-activedirectory-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet | src/ADAL.Common/CommonAssemblyInfo.cs | src/ADAL.Common/CommonAssemblyInfo.cs | //----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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.Reflection;
[assembly: AssemblyProduct("Active Directory Authentication Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("Microsoft Open Technologies")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("3.4.0.0")]
// Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion.
// Build and revision numbers are replaced on build machine for official builds.
[assembly: AssemblyFileVersion("3.4.00000.0000")]
// On official build, attribute AssemblyInformationalVersionAttribute is added as well
// with its value equal to the hash of the last commit to the git branch.
// e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")]
// Assembly marked as compliant.
[assembly: CLSCompliant(true)]
| //----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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.Reflection;
[assembly: AssemblyProduct("Active Directory Authentication Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("Microsoft Open Technologies")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("3.3.0.0")]
// Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion.
// Build and revision numbers are replaced on build machine for official builds.
[assembly: AssemblyFileVersion("3.3.00000.0000")]
// On official build, attribute AssemblyInformationalVersionAttribute is added as well
// with its value equal to the hash of the last commit to the git branch.
// e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")]
// Assembly marked as compliant.
[assembly: CLSCompliant(true)]
| mit | C# |
cc60ac253a2ac3158c2a93f6d5b5b685605a3bce | upgrade version to 2.0.8 | Aaron-Liu/equeue,tangxuehua/equeue,tangxuehua/equeue,geffzhang/equeue,Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue | src/EQueue/Properties/AssemblyInfo.cs | src/EQueue/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.8")]
[assembly: AssemblyFileVersion("2.0.8")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.7")]
[assembly: AssemblyFileVersion("2.0.7")]
| mit | C# |
123dc6474cf96f2ab90a02df615f0598c810c22e | Hide logout when not using forms auth | nimore/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,bussemac/n2cms,n2cms/n2cms,nimore/n2cms,n2cms/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,DejanMilicic/n2cms,nicklv/n2cms,nimore/n2cms,nicklv/n2cms,nimore/n2cms,bussemac/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,bussemac/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,DejanMilicic/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,bussemac/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,DejanMilicic/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,bussemac/n2cms | src/Mvc/MvcTemplates/N2/Top.master.cs | src/Mvc/MvcTemplates/N2/Top.master.cs | using System.Configuration;
using System.Web.Configuration;
namespace N2.Management
{
public partial class Top : System.Web.UI.MasterPage
{
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
try
{
var section = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication");
logout.Visible = section.Mode == AuthenticationMode.Forms;
}
catch (System.Exception)
{
}
}
}
}
|
namespace N2.Management
{
public partial class Top : System.Web.UI.MasterPage
{
}
}
| lgpl-2.1 | C# |
ecd7580bc9a2dc32105b87485a56d1d879f04378 | Create PCGSphereTester.cs | scmcom/unitycode | PCGSphereTester.cs | PCGSphereTester.cs | using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class PCGSphereTester : MonoBehaviour {
public int subdivisions = 0;
public float radius = 1f;
private void Awake(){
GetComponent<MeshFilter>().mesh = PCGSphereCreator.Create(subdivisions, radius);
}
}
| mit | C# | |
e400781bd553ce384e4f958af9cf864b99e10c22 | Create GLOBAL.cs | Tech-Curriculums/101-GameDesign-2D-GameDesign-With-Unity | AngryHipsters/GLOBAL.cs | AngryHipsters/GLOBAL.cs | using UnityEngine;
using System.Collections;
public class GLOBAL : MonoBehaviour {
private int glasses = 0;
public int getNumberOfGlasses() {
return glasses;
}
public int Hipped(int hits) {
if (glasses >= 1) {
glasses--;
}
return glasses;
}
public void PlusOne() {
glasses++;
}
}
| mit | C# | |
38eb44fcc5ddbd8151b13d33ffe52815d29c6ae2 | Create Gemstones.cs | SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming | Hackerrank/Gemstones.cs | Hackerrank/Gemstones.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
string temp;
int tc;
temp=Console.ReadLine();
int.TryParse(temp, out tc);
int[][] hashmatrix=new int[tc][];
for(int i=0;i<tc;i++)
{hashmatrix[i]=new int[26];}
string[] src=new string[tc];
for(int i=0;i<tc;i++)
{
src[i]=Console.ReadLine();
for(int j=0;j<26;j++){hashmatrix[i][j]=0;}
}
for(int i=0;i<tc;i++)
{
byte[] dec=Encoding.ASCII.GetBytes(src[i]);
for(int j=0;j<src[i].Length;j++)
{hashmatrix[i][dec[j]-97]++;}
}
int x=0,y=0,counter=0;
bool breaker;
while(y<26)
{
breaker=false;
x=0;
while(x<tc&&!breaker)
{
if(hashmatrix[x][y]==0)
{
breaker=true;
}
else{x++;}
}
if(!breaker){counter++;}else{breaker=false;}
//if(((hashmatrix[x][y])>0)&&(x==tc-1)&&(y<26)){counter++;}
y++;
}
Console.WriteLine(counter);
}
}
| mit | C# | |
5069bdfca2c70bf16bb41aab822dc97c86127e78 | add fix that ensures routing | leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | JoinRpg.Portal.Test/RoutingTests.cs | JoinRpg.Portal.Test/RoutingTests.cs | using System.Reflection;
using JoinRpg.Portal.Controllers;
using JoinRpg.Portal.Controllers.Common;
using JoinRpg.TestHelpers;
using Microsoft.AspNetCore.Mvc;
using Shouldly;
using Xunit;
namespace JoinRpg.Portal.Test
{
public class RoutingTests
{
[Theory]
[ClassData(typeof(ControllerDataSource))]
public void GameControllersShouldHaveProjectIdInRoute(TypeInfo controllerType)
{
if (controllerType == typeof(GameController))
{
//This is special controller, we need to refactor it
return;
}
var routeAttribute = controllerType.GetCustomAttribute<RouteAttribute>();
routeAttribute.ShouldNotBeNull();
routeAttribute.Template.ShouldStartWith("{projectId}");
}
private class ControllerDataSource : FindDerivedClassesDataSourceBase<ControllerGameBase, Startup> { }
}
}
| mit | C# | |
15d5d4c9ef6fbd78a3d44f44987eb6b5353e9d61 | Create LanguagesController.cs | letsbelopez/asp.net-snippets,letsbelopez/asp.net-snippets | LanguagesController.cs | LanguagesController.cs | using Sabio.Web.Models;
using Sabio.Web.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Sabio.Web.Controllers
{
[Authorize(Roles = "Admin")]
[RoutePrefix("languages")]
public class LanguagesController : BaseController
{
// GET: Languages
public ActionResult Index()
{
return View();
}
[Route("create")] [Route("{id:int}/edit")] [HttpGet]
public ActionResult Create(int id = 0)
{
ItemViewModel<int> model = new ItemViewModel<int>();
model.Item = id;
return View(model);
}
[Route("manage")]
public ActionResult Manage()
{
return View();
}
// GET: Angular Languages
public ActionResult Angular()
{
return View();
}
}
}
| mit | C# | |
262be727fd8f9adaa4ef18ddc5e8832b72fa08ff | Add enums folder and one enum | fredatgithub/UsefulFunctions | FonctionsUtiles.Fred.Csharp/Enums/Result.cs | FonctionsUtiles.Fred.Csharp/Enums/Result.cs | namespace FonctionsUtiles.Fred.Csharp.Enums
{
public enum Result
{
Unknown = 0,
Failure,
Success
}
}
| mit | C# | |
c181c592ce2f42c72902c106115b2767768538be | Create Task.cs | KirillOsenkov/MSBuildTools | test/Task.cs | test/Task.cs | using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
namespace HelloTask
{
public class Hello : Task
{
public string YourName { get; set; }
public override bool Execute()
{
Log.LogMessage(MessageImportance.High, "{0}", YourName);
return true;
}
}
}
| mit | C# | |
caecae78cca7e535c16ff498693c1d81cf2e182d | Add cake build script | Cheesebaron/ALRadialMenu | build.cake | build.cake | #tool nuget:?package=GitVersion.CommandLine
#tool nuget:?package=vswhere
#addin nuget:?package=Cake.Incubator
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var artifactsDirectory = new DirectoryPath("./artifacts");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories("./src/**/bin");
CleanDirectories("./src/**/obj");
CleanDirectories(artifactsDirectory.FullPath);
EnsureDirectoryExists(artifactsDirectory);
});
GitVersion versionInfo = null;
Task("Version").Does(() => {
versionInfo = GitVersion(new GitVersionSettings {
UpdateAssemblyInfo = true,
OutputType = GitVersionOutput.Json
});
Information("GitVersion -> {0}", versionInfo.Dump());
});
Task("UpdateAppVeyorBuildNumber")
.IsDependentOn("Version")
.WithCriteria(() => AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
AppVeyor.UpdateBuildVersion(versionInfo.FullBuildMetaData);
});
FilePath msBuildPath;
Task("ResolveBuildTools")
.Does(() =>
{
var vsLatest = VSWhereLatest();
msBuildPath = (vsLatest == null)
? null
: vsLatest.CombineWithFilePath("./MSBuild/15.0/Bin/MSBuild.exe");
});
Task("Build")
.IsDependentOn("ResolveBuildTools")
.IsDependentOn("Clean")
.IsDependentOn("UpdateAppVeyorBuildNumber")
.Does(() =>
{
var settings = new MSBuildSettings
{
Configuration = configuration,
ToolPath = msBuildPath,
Verbosity = Verbosity.Minimal,
ArgumentCustomization = args => args.Append("/m")
};
settings = settings.WithProperty("DebugSymbols", "True").
WithProperty("DebugType", "Full");
MSBuild("./src/RadialMenu/RadialMenu.sln", settings);
});
Task("Package")
.IsDependentOn("Build")
.Does(() =>
{
var nugetContent = new List<NuSpecContent>();
var binDir = "./src/RadialMenu/RadialMenu/bin/iPhone/" + configuration;
var files = GetFiles(binDir + "/*.dll") + GetFiles(binDir + "/*.pdb");
foreach(var dll in files)
{
Information("File: {0}", dll.ToString());
nugetContent.Add(new NuSpecContent
{
Target = "lib/Xamarin.iOS10",
Source = dll.ToString()
});
}
var nugetSettings = new NuGetPackSettings {
Id = "ALRadialMenu",
Title = "RadialMenu for Xamarin.iOS",
Authors = new [] { "Tomasz Cielecki" },
Owners = new [] { "Tomasz Cielecki" },
IconUrl = new Uri("http://i.imgur.com/V3983YY.png"),
ProjectUrl = new Uri("https://github.com/Cheesebaron/ALRadialMenu"),
LicenseUrl = new Uri("https://raw.githubusercontent.com/Cheesebaron/ALRadialMenu/master/LICENSE"),
Copyright = "Copyright (c) Tomasz Cielecki",
Tags = new [] { "menu", "radial", "ios", "xamarin", "alradialmenu", "radialmenu" },
Description = "A Radial Menu for Xamarin.iOS.",
RequireLicenseAcceptance = false,
Version = versionInfo.NuGetVersion,
Symbols = false,
NoPackageAnalysis = true,
OutputDirectory = artifactsDirectory,
Verbosity = NuGetVerbosity.Detailed,
Files = nugetContent,
BasePath = "./"
};
NuGetPack(nugetSettings);
});
Task("UploadAppVeyorArtifact")
.IsDependentOn("Package")
.WithCriteria(() => !AppVeyor.Environment.PullRequest.IsPullRequest)
.WithCriteria(() => AppVeyor.IsRunningOnAppVeyor)
.Does(() => {
Information("Artifacts Dir: {0}", artifactsDirectory.FullPath);
var uploadSettings = new AppVeyorUploadArtifactsSettings {
ArtifactType = AppVeyorUploadArtifactType.NuGetPackage
};
foreach(var file in GetFiles(artifactsDirectory.FullPath + "/*.nupkg"))
{
Information("Uploading {0}", file.FullPath);
AppVeyor.UploadArtifact(file.FullPath, uploadSettings);
}
});
Task("Default")
.IsDependentOn("UploadAppVeyorArtifact");
RunTarget(target); | mit | C# | |
0ad8d961ddfe781619e3585277bf11a84d88d5dd | Create StaffController.cs | Longfld/ASPNETCoreAngular2,Longfld/ASPNETCoreAngular2,Longfld/ASPNETCoreAngular2,Longfld/ASPNETCoreAngular2 | webapp/src/webapp/Controllers/StaffController.cs | webapp/src/webapp/Controllers/StaffController.cs |
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace webapp
{
[Route("api/[controller]")]
public class StaffController : Controller
{
[HttpGet("GetStaff")]
public IActionResult GetStaff()
{
List<string> model = new List<string>();
model.Add("John");
model.Add("Jack");
model.Add("Jane");
model.Add("Matthew");
model.Add("May");
return Json(model);
}
}
}
| mit | C# | |
ac09dbba9c5d213fd02ed19534a17d098cbd6a18 | Add min/max examples #762 | mbdavid/LiteDB,89sos98/LiteDB,falahati/LiteDB,falahati/LiteDB,89sos98/LiteDB | LiteDB.Tests/Database/MinMax_Tests.cs | LiteDB.Tests/Database/MinMax_Tests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
namespace LiteDB.Tests.Database
{
#region Model
public class EntityMinMax
{
public int Id { get; set; }
public byte ByteValue { get; set; }
public int IntValue { get; set; }
public uint UintValue { get; set; }
public long LongValue { get; set; }
}
#endregion
[TestClass]
public class MinMax_Tests
{
[TestMethod, TestCategory("Database")]
public void MinMax()
{
using (var f = new TempFile())
using (var db = new LiteDatabase(f.Filename))
{
var c = db.GetCollection<EntityMinMax>("col");
c.Insert(new EntityMinMax { });
c.Insert(new EntityMinMax
{
ByteValue = 200,
IntValue = 443500,
LongValue = 443500,
UintValue = 443500
});
c.EnsureIndex(x => x.ByteValue);
c.EnsureIndex(x => x.IntValue);
c.EnsureIndex(x => x.LongValue);
c.EnsureIndex(x => x.UintValue);
Assert.AreEqual(200, c.Max(x => x.ByteValue).AsInt32);
Assert.AreEqual(443500, c.Max(x => x.IntValue).AsInt32);
Assert.AreEqual(443500, c.Max(x => x.LongValue).AsInt64);
Assert.AreEqual(443500, c.Max(x => x.UintValue).AsInt32);
}
}
}
} | mit | C# | |
8c6f78568a25f204ec100bfbdb8e06c1bbd1be6a | Attach Identity.cs source | jeremyrsellars/no-new-legacy,jeremyrsellars/no-new-legacy,jeremyrsellars/no-new-legacy | posts/Identity.cs | posts/Identity.cs | public class Identity<TSelf, TData> : IEquatable<TSelf>
where TSelf : Identity<TSelf, TData>
where TData : IEquatable<TData>
{
private readonly TData _value;
public Identity(TData value)
{
if (ReferenceEquals(value, null))
throw new ArgumentNullException(nameof(value));
_value = value;
}
public virtual bool Equals(TSelf other) =>
other != null
&& Value.Equals(other.Value);
public override bool Equals(object other) => Equals(other as TSelf);
public sealed override int GetHashCode()
{
// GetHashCode is effectively a 31-bit hashcode
// calculated from the Value, by default.
// When this bit is set, then the code as already calculated.
const int assignmentBit = 1 << 15;
// This lazy, lock-free implementation is thread-safe, assuming:
// * The resulting hash code is the same regardless of which thread calculates it.
// * Int32 fields can be assigned with a single operation.
// ReSharper disable NonReadonlyMemberInGetHashCode
var hc = _hashCode;
if (hc == 0)
_hashCode = hc = GetHashCodeCore() | assignmentBit;
return hc;
}
protected virtual int GetHashCodeCore() => Value.GetHashCode();
public override string ToString() =>
$"{ShortTypeName}[{Value}]";
protected TData Value => _value;
[NonSerialized]
private int _hashCode;
protected static string ShortTypeName { get; } = typeof(TSelf).Name;
}
public class Identity<TSelf, TData1, TData2> : Identity<TSelf, TData1>
where TSelf : Identity<TSelf, TData1, TData2>
where TData1 : IEquatable<TData1>
where TData2 : IEquatable<TData2>
{
private readonly TData2 _value2;
public Identity(TData1 value, TData2 value2)
: base(value)
{
if (ReferenceEquals(value2, null))
throw new ArgumentNullException(nameof(value2));
_value2 = value2;
}
protected TData2 Value2 => _value2;
public override string ToString() =>
$"{ShortTypeName}[{Value},{Value2}]";
public override bool Equals(TSelf other) =>
other != null
&& Value.Equals(other.Value)
&& Value2.Equals(other.Value2);
protected override int GetHashCodeCore()
{
var hash = 17;
hash = hash * 23 + Value.GetHashCode();
hash = hash * 23 + Value2.GetHashCode();
return hash;
}
}
| isc | C# | |
9dd1600ff367cb1c0b9617a535dac3b69c49d191 | Introduce OrderAttribute and Utils | peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework | osu.Framework/Utils/OrderAttribute.cs | osu.Framework/Utils/OrderAttribute.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
namespace osu.Framework.Utils
{
public static class OrderAttributeUtils
{
/// <summary>
/// Get values of an enum in order. Supports custom ordering via <see cref="OrderAttribute"/>.
/// </summary>
public static IEnumerable<T> GetValuesInOrder<T>()
{
var type = typeof(T);
if (!type.IsEnum)
throw new InvalidOperationException("T must be an enum");
IEnumerable<T> items = (T[])Enum.GetValues(type);
return GetValuesInOrder(items);
}
/// <summary>
/// Get values of a collection of enum values in order. Supports custom ordering via <see cref="OrderAttribute"/>.
/// </summary>
public static IEnumerable<T> GetValuesInOrder<T>(IEnumerable<T> items)
{
var type = typeof(T);
if (!type.IsEnum)
throw new InvalidOperationException("T must be an enum");
if (!(Attribute.GetCustomAttribute(type, typeof(HasOrderedElementsAttribute)) is HasOrderedElementsAttribute orderedAttr))
return items;
return items.OrderBy(i =>
{
if (type.GetField(i.ToString()).GetCustomAttributes(typeof(OrderAttribute), false).FirstOrDefault() is OrderAttribute attr)
return attr.Order;
if (orderedAttr.AllowPartialOrdering)
return (int)Enum.Parse(type, i.ToString());
throw new ArgumentException($"Not all values of {nameof(T)} have {nameof(OrderAttribute)} specified.");
});
}
}
[AttributeUsage(AttributeTargets.Field)]
public class OrderAttribute : Attribute
{
public readonly int Order;
public OrderAttribute(int order)
{
Order = order;
}
}
[AttributeUsage(AttributeTargets.Enum)]
public class HasOrderedElementsAttribute : Attribute
{
/// <summary>
/// Allow for partially ordering Enum members.
/// Members without an Order Attribute will default to their value as ordering key.
/// </summary>
public bool AllowPartialOrdering { get; set; }
}
}
| mit | C# | |
6abdcc6ccb3769848659f7863cca963d028814f3 | Add LayoutFile class | whampson/cascara,whampson/bft-spec | Cascara/Src/LayoutFile.cs | Cascara/Src/LayoutFile.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;
using System.Xml;
using System.Xml.Linq;
namespace WHampson.Cascara
{
/// <summary>
/// Represents a Layout File, used for defining the structure of a binary file.
/// </summary>
public sealed class LayoutFile
{
/// <summary>
/// Loads a Layout File from the filesystem.
/// </summary>
/// <param name="layoutFilePath">
/// The path to the layout file.
/// </param>
/// <returns>
/// A <see cref="LayoutFile"/> object containing the layout information
/// from the provided file.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown if the XML path is invalid.
/// </exception>
/// <exception cref="XmlException">
/// If an error occurs while loading the Layout XML file.
/// </exception>
public static LayoutFile Load(string layoutFilePath)
{
return new LayoutFile(OpenXmlFile(layoutFilePath));
}
/// <summary>
/// Creates a new <see cref="LayoutFile"/> object
/// from an XML data string.
/// </summary>
/// <param name="xmlData">
/// The contents of an XML file containing the layout information.
/// </param>
public LayoutFile(string xmlData)
: this(XDocument.Parse(xmlData))
{ }
/// <summary>
/// Creates a new <see cref="LayoutFile"/> object
/// from an existing <see cref="XDocument"/> object.
/// </summary>
/// <param name="xDoc">
/// An <see cref="XDocument"/> object containing the
/// Layout File XML data.
/// </param>
/// <exception cref="ArgumentNullException">
/// If the provided <see cref="XDocument"/> object is <code>null</code>.
/// </exception>
public LayoutFile(XDocument xDoc)
{
Document = xDoc ?? throw new ArgumentNullException("xDoc");
}
/// <summary>
/// Gets the <see cref="XDocument"/> associated with
/// this <see cref="LayoutFile"/> file.
/// </summary>
internal XDocument Document
{
get;
}
public override int GetHashCode()
{
return Document.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is LayoutFile))
{
return false;
}
LayoutFile lf = (LayoutFile) obj;
return lf.Document.Equals(Document);
}
/// <summary>
/// Loads data from an XML file located at the specified path.
/// </summary>
/// <param name="path">
/// The path to the XML file to load.
/// </param>
/// <returns>
/// The loaded XML data as an <see cref="XDocument"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown if the XML path is invalid.
/// </exception>
/// <exception cref="XmlException">
/// Thrown if there is an error while loading the XML document.
/// </exception>
private static XDocument OpenXmlFile(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentException("Path cannot be empty or null");
}
return XDocument.Load(path, LoadOptions.SetLineInfo);
}
}
}
| mit | C# | |
143d7ab640b588569e5dc31bd0d87f79b8a78401 | Add test scene for spinner rotation | ppy/osu,peppy/osu,peppy/osu-new,ZLima12/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,ppy/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,ZLima12/osu,smoogipooo/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,EVAST9919/osu | osu.Game.Rulesets.Osu.Tests/TestSceneSpinnerRotation.cs | osu.Game.Rulesets.Osu.Tests/TestSceneSpinnerRotation.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.Allocation;
using osu.Framework.Audio;
using osu.Framework.Logging;
using osu.Framework.MathUtils;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual;
using osuTK;
using System.Collections.Generic;
using System.Linq;
using static osu.Game.Tests.Visual.OsuTestScene.ClockBackedTestWorkingBeatmap;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneSpinnerRotation : TestSceneOsuPlayer
{
[Resolved]
private AudioManager audioManager { get; set; }
private TrackVirtualManual track;
protected override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap)
{
var working = new ClockBackedTestWorkingBeatmap(beatmap, new FramedClock(new ManualClock { Rate = 1 }), audioManager);
track = (TrackVirtualManual)working.Track;
return working;
}
private DrawableSpinner drawableSpinner;
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("retrieve spinner", () => drawableSpinner = (DrawableSpinner)((TestPlayer)Player).DrawableRuleset.Playfield.AllHitObjects.First());
// wait for frame stable clock time to hit 0 (for some reason, executing a seek while current time is below 0 doesn't seek successfully)
addSeekStep(0);
}
[Test]
public void TestSpinnerRewindingRotation()
{
addSeekStep(5000);
AddAssert("is rotation absolute not almost 0", () => !Precision.AlmostEquals(drawableSpinner.Disc.RotationAbsolute, 0, 100));
addSeekStep(0);
AddAssert("is rotation absolute almost 0", () => Precision.AlmostEquals(drawableSpinner.Disc.RotationAbsolute, 0, 100));
}
[Test]
public void TestSpinnerMiddleRewindingRotation()
{
double estimatedRotation = 0;
addSeekStep(5000);
AddStep("retrieve rotation", () => estimatedRotation = drawableSpinner.Disc.RotationAbsolute);
addSeekStep(2500);
addSeekStep(5000);
AddAssert("is rotation absolute almost same", () => Precision.AlmostEquals(drawableSpinner.Disc.RotationAbsolute, estimatedRotation, 100));
}
private void addSeekStep(double time)
{
AddStep($"seek to {time}", () => track.Seek(time));
AddUntilStep("wait for seek to finish", () => Precision.AlmostEquals(time, ((TestPlayer)Player).DrawableRuleset.FrameStableClock.CurrentTime, 100));
}
protected override Player CreatePlayer(Ruleset ruleset)
{
Mods.Value = Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() }).ToArray();
return new TestPlayer();
}
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new Beatmap
{
HitObjects = new List<HitObject>
{
new Spinner
{
Position = new Vector2(256, 192),
EndTime = 5000,
},
// placeholder object to avoid hitting the results screen
new HitObject
{
StartTime = 99999,
}
}
};
}
}
| mit | C# | |
c8ff5acec2a511a3e2d60673d419f9798b275e2e | Add RID unit tests. | lecaillon/Evolve | test/Evolve.Core.Test/Utilities/RIDTest.cs | test/Evolve.Core.Test/Utilities/RIDTest.cs | using Evolve.Utilities;
using Xunit;
namespace Evolve.Core.Test.Utilities
{
public class RIDTest
{
[Theory(DisplayName = "RID_ToString_must_extract_metadata")]
[InlineData((string)null, "RID: [] OS: [], Version: [], Architecture: []")]
[InlineData("", "RID: [] OS: [], Version: [], Architecture: []")]
[InlineData("win", "RID: [win] OS: [win], Version: [], Architecture: []")]
[InlineData("win7", "RID: [win7] OS: [win7], Version: [], Architecture: []")]
[InlineData("win-x86", "RID: [win-x86] OS: [win], Version: [], Architecture: [x86]")]
[InlineData("win10-arm64", "RID: [win10-arm64] OS: [win10], Version: [], Architecture: [arm64]")]
[InlineData("win10-arm64-blah", "RID: [win10-arm64-blah] OS: [win10], Version: [], Architecture: [arm64]")]
[InlineData("centos.7-x64", "RID: [centos.7-x64] OS: [centos], Version: [7], Architecture: [x64]")]
[InlineData("fedora.24-x64", "RID: [fedora.24-x64] OS: [fedora], Version: [24], Architecture: [x64]")]
[InlineData("opensuse.42.1-x64", "RID: [opensuse.42.1-x64] OS: [opensuse], Version: [42.1], Architecture: [x64]")]
[InlineData("osx.10.12-x64", "RID: [osx.10.12-x64] OS: [osx], Version: [10.12], Architecture: [x64]")]
[InlineData("osx.10.12-x64-blah", "RID: [osx.10.12-x64-blah] OS: [osx], Version: [10.12], Architecture: [x64]")]
public void RID_ToString_must_extract_metadata(string rid, string result)
{
Assert.Equal(result, new RID(rid).ToString());
}
}
}
| mit | C# | |
2de560d6644a7f73aa6e5b35cd5e0254d02c05db | Add a factory for Property path element | Domysee/Pather.CSharp | src/Pather.CSharp/PathElements/PropertyFactory.cs | src/Pather.CSharp/PathElements/PropertyFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class PropertyFactory : IPathElementFactory
{
public IPathElement Create(string pathElement)
{
return new Property(pathElement);
}
public bool IsApplicable(string pathElement)
{
return Regex.IsMatch(pathElement, @"\w+");
}
}
}
| mit | C# | |
c0bb234f30026b7d9438a2ed815e25ecc688549d | Create SmsController.cs | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | quickstart/csharp/sms/receive-sms-core/SmsController.cs | quickstart/csharp/sms/receive-sms-core/SmsController.cs | // Code sample for ASP.NET Core on .NET Core
// From command prompt, run:
// dotnet add package Twilio.AspNet.Core
using Twilio.AspNet.Common;
using Twilio.AspNet.Core;
using Twilio.TwiML;
namespace YourNewWebProject.Controllers
{
public class SmsController : TwilioController
{
public TwiMLResult Index(SmsRequest incomingMessage)
{
var messagingResponse = new MessagingResponse();
messagingResponse.Message("The copy cat says: " +
incomingMessage.Body);
return TwiML(messagingResponse);
}
}
}
| mit | C# | |
5c86c502ad610d755791d8370e93e5c0b80c743b | Create HttpJsonTarget.cs | jupe/NLog.HttpJsonTarget | HttpJsonTarget.cs | HttpJsonTarget.cs | using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog.Common;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
namespace NLog.Targets
{
[Target("HttpJsonTarget")]
public sealed class HttpJsonTarget : Target
{
[RequiredParameter]
public Uri Url { get; set; }
[RequiredParameter]
public Layout Layout { get; set; }
protected override void Write(AsyncLogEventInfo info)
{
try
{
String layout = this.Layout.Render(info.LogEvent);
//layout = layout.Replace("\\", "/"); //this might be useful
var json = JObject.Parse(layout).ToString(); // make sure the json is valid
var client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
UploadStringCompletedEventHandler cb = null;
cb = (s, e) =>
{
if (cb != null)
client.UploadStringCompleted -= cb;
if (e.Error != null)
{
if (e.Error is WebException)
{
var we = e.Error as WebException;
try
{
var result = JObject.Load(new JsonTextReader(new StreamReader(we.Response.GetResponseStream())));
var error = result.GetValue("error");
if (error != null)
{
info.Continuation(new Exception(result.ToString(), e.Error));
return;
}
}
catch (Exception) { info.Continuation(new Exception("Failed to send log event to HttpJsonTarget", e.Error)); }
}
info.Continuation(e.Error);
return;
}
info.Continuation(null);
};
client.UploadStringCompleted += cb;
client.UploadStringAsync(Url, "POST", json);
}
catch (Exception ex)
{
info.Continuation(ex);
}
}
protected override void Write(LogEventInfo logEvent)
{
throw new NotImplementedException();
}
}
}
| mit | C# | |
076fe91611858d47cc351b512b9d3d58663b1248 | Add tests for RNG | ektrah/nsec | tests/Core/RandomTests.cs | tests/Core/RandomTests.cs | using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Core
{
public static class RandomTests
{
#region GenerateBytes #1
[Fact]
public static void GenerateBytesWithNegativeCount()
{
Assert.Throws<ArgumentOutOfRangeException>("count", () => SecureRandom.GenerateBytes(-1));
}
[Fact]
public static void GenerateBytesWithZeroCount()
{
var bytes = SecureRandom.GenerateBytes(0);
Assert.NotNull(bytes);
Assert.Equal(0, bytes.Length);
}
[Theory]
[InlineData(1)]
[InlineData(15)]
[InlineData(63)]
public static void GenerateBytesWithCount(int count)
{
var bytes = SecureRandom.GenerateBytes(count);
Assert.NotNull(bytes);
Assert.Equal(count, bytes.Length);
Assert.NotEqual(new byte[count], bytes);
}
#endregion
#region GenerateBytes #2
[Fact]
public static void GenerateBytesWithEmptySpan()
{
SecureRandom.GenerateBytes(new byte[0]);
}
[Theory]
[InlineData(1)]
[InlineData(15)]
[InlineData(63)]
public static void GenerateBytesWithSpan(int count)
{
var bytes = new byte[count];
SecureRandom.GenerateBytes(bytes);
Assert.NotEqual(new byte[count], bytes);
}
#endregion
}
}
| mit | C# | |
95367b8eecc8cce8b58a55cfdfc6a3764f1b27e3 | Create program.cs | justynak2/indywidualne | program.cs | program.cs | int a =2;
| mit | C# | |
22438a4bf6a4c92067c8db9bb6baf45514d9e6b0 | Create Transmitter.cs | Pharap/SpengyUtils | Examples/SimpleCommandSystem/Transmitter.cs | Examples/SimpleCommandSystem/Transmitter.cs | // Instructions:
// 1. Place script in programmable block
// 2. Assign programmable block to antenna named "Antenna"
public void Broadcast(string name, string message)
{
var antenna = GridTerminalSystem.GetBlockWithName(name) as IMyRadioAntenna;
antenna.TransmitMessage(message);
}
public void Main(string argument)
{
Broadcast("Antenna", argument);
}
| apache-2.0 | C# | |
9cbf925947d9b7ff6000bd866bae19be8badc39a | introduce TsProjectFile | isukces/isukces.code | isukces.code/Typescript/_project/TsProjectFile.cs | isukces.code/Typescript/_project/TsProjectFile.cs | using System;
using System.IO;
namespace isukces.code.Typescript
{
/// <summary>
/// Helps to manage relations between ts files
/// </summary>
public class TsProjectFile
{
public TsProjectFile(TsFile file, DirectoryInfo webProjectRoot, DirectoryInfo resultFileDir)
{
File = file;
ResultFileDir = resultFileDir;
WebProjectRoot = webProjectRoot;
}
private static string GetRelativePath(FileInfo fileInfo, DirectoryInfo baseDir)
{
var pathUri = new Uri(fileInfo.FullName);
// Folders must end in a slash
var folder = baseDir.FullName;
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
folder += Path.DirectorySeparatorChar;
var folderUri = new Uri(folder);
var tmp = folderUri.MakeRelativeUri(pathUri).ToString();
return Uri.UnescapeDataString(tmp.Replace('/', Path.DirectorySeparatorChar));
}
/// <summary>
/// Add reference to typescript file.
/// </summary>
/// <param name="relFilePath">File path related to <see cref="WebProjectRoot">ProjectRoot</see></param>
public void AddRelativeReference(string relFilePath)
{
var fi = new FileInfo(Path.Combine(WebProjectRoot.FullName, relFilePath));
var rel = GetRelativePath(fi, ResultFileDir);
File.References.Add(new TsReference(rel));
}
public TsFile File { get; }
/// <summary>
/// Directory where typescript file will be saved
/// </summary>
public DirectoryInfo ResultFileDir { get; }
/// <summary>
/// Root directory of web project
/// </summary>
public DirectoryInfo WebProjectRoot { get; }
}
} | mit | C# | |
cc64c7e4b08c6878aefa16336ee41a654b87734c | Bump version number | mjanthony/Huxley,Newsworthy/Huxley,jpsingleton/Huxley,mjanthony/Huxley,jpsingleton/Huxley,Newsworthy/Huxley | src/Huxley/Properties/AssemblyInfo.cs | src/Huxley/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Huxley")]
[assembly: AssemblyDescription("A restful JSON proxy for the UK National Rail Live Departure Board SOAP API (Darwin)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("James Singleton (unop.uk)")]
[assembly: AssemblyProduct("Huxley")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("73cde2fa-1069-4e90-b2ce-f97c866b296e")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Huxley")]
[assembly: AssemblyDescription("A restful JSON proxy for the UK National Rail Live Departure Board SOAP API (Darwin)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("James Singleton (unop.uk)")]
[assembly: AssemblyProduct("Huxley")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("73cde2fa-1069-4e90-b2ce-f97c866b296e")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")] | agpl-3.0 | C# |
6f661f15a1fc3c010d6c2a9da077085ceb84c2b2 | Add spline easing class | wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia | src/Avalonia.Animation/Easing/SplineEasing.cs | src/Avalonia.Animation/Easing/SplineEasing.cs | namespace Avalonia.Animation.Easings
{
/// <summary>
/// Eases a <see cref="double"/> value
/// using a user-defined cubic bezier curve.
/// Good for custom easing functions that doesn't quite
/// fit with the built-in ones.
/// </summary>
public class SplineEasing : Easing
{
/// <summary>
/// X coordinate of the first control point
/// </summary>
private double _x1;
public double X1
{
get => _x1;
set
{
_x1 = value; _internalKeySpline.ControlPointX1 = _x1;
}
}
/// <summary>
/// Y coordinate of the first control point
/// </summary>
private double _y1;
public double Y1
{
get => _y1;
set
{
_y1 = value; _internalKeySpline.ControlPointY1 = _y1;
}
}
/// <summary>
/// X coordinate of the second control point
/// </summary>
private double _x2 = 1.0d;
public double X2
{
get => _x2;
set
{
_x2 = value;
_internalKeySpline.ControlPointX2 = _x2;
}
}
/// <summary>
/// Y coordinate of the second control point
/// </summary>
private double _y2 = 1.0d;
public double Y2
{
get => _y2;
set
{
_y2 = value;
_internalKeySpline.ControlPointY2 = _y2;
}
}
private KeySpline _internalKeySpline;
public SplineEasing(double x1 = 0d, double y1 = 0d, double x2 = 1d, double y2 = 1d) : base()
{
this._internalKeySpline = new KeySpline();
this.X1 = x1;
this.Y1 = y1;
this.X2 = x2;
this.Y1 = y2;
}
public SplineEasing()
{
this._internalKeySpline = new KeySpline();
}
/// <inheritdoc/>
public override double Ease(double progress) =>
_internalKeySpline.GetSplineProgress(progress);
}
}
| mit | C# | |
0552a676747b4721b72133e4ec71f9b1c409bb7b | Add test | bgTeamDev/bgTeam.Core,bgTeamDev/bgTeam.Core | tests/Test.bgTeam.Core/Tests/Test_Helpers.cs | tests/Test.bgTeam.Core/Tests/Test_Helpers.cs | using bgTeam.Core.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Test.bgTeam.Core.Tests
{
public class Test_Helpers
{
[Fact]
public void ConfigHelper_Init()
{
var fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
var configFolderPath = Path.Combine(fileInfo.Directory.FullName, "Configurations");
var configurations = ConfigHelper.Init<InsuranceConfiguration>(configFolderPath);
Assert.True(configurations.Any());
}
public class InsuranceConfiguration
{
public string ConfigName { get; set; }
public string ContextType { get; set; }
public string Description { get; set; }
public string NameQueue { get; set; }
public string DateFormatStart { get; set; }
public int? DateChangeOffsetFrom { get; set; }
public int? DateChangeOffsetTo { get; set; }
public string[] Sql { get; set; }
}
}
}
| mit | C# | |
eeaf463f917a991121abb7bb1201c9a4ee845b78 | Test detouring empty methods | AngelDE98/MonoMod,0x0ade/MonoMod | MonoMod.UnitTest/RuntimeDetour/DetourEmptyTest.cs | MonoMod.UnitTest/RuntimeDetour/DetourEmptyTest.cs | #pragma warning disable CS1720 // Expression will always cause a System.NullReferenceException because the type's default value is null
#pragma warning disable xUnit1013 // Public method should be marked as test
using Xunit;
using MonoMod.RuntimeDetour;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using MonoMod.Utils;
using System.Reflection.Emit;
using System.Text;
namespace MonoMod.UnitTest {
[Collection("RuntimeDetour")]
public class DetourEmptyTest {
private bool DidNothing = true;
[Fact]
public void TestDetoursEmpty() {
// The following use cases are not meant to be usage examples.
// Please take a look at DetourTest and HookTest instead.
Assert.True(DidNothing);
using (Hook h = new Hook(
// .GetNativeStart() to enforce a native detour.
typeof(DetourEmptyTest).GetMethod("DoNothing"),
new Action<DetourEmptyTest>(self => {
DidNothing = false;
})
)) {
DoNothing();
Assert.False(DidNothing);
}
}
public void DoNothing() {
}
}
}
| mit | C# | |
97ca5a4df499834a843cca4e64042a77fce9c5dd | Create DEB.cs | etormadiv/njRAT_0.7d_Stub_ReverseEngineering | j_csharp/OK/DEB.cs | j_csharp/OK/DEB.cs | //Reversed by Etor Madiv
public static string DEB(ref string s)
{
byte[] data = System.Convert.FromBase64String(s);
return BS(ref data);
}
| unlicense | C# | |
79c3dda0346d66766bf852da495f1595354f01a0 | sort questions | jackzhenguo/leetcode-csharp | Sort/WiggleSortSln.cs | Sort/WiggleSortSln.cs | /* ==============================================================================
* 功能描述:WiggleSort
* 创 建 者:gz
* 创建日期:2017/5/31 14:02:01
* ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WiggleSort
{
/// <summary>
/// WiggleSort
/// </summary>
public class WiggleSortSln
{
private static int[] _array;
public int[] WiggleSort(int[] array)
{
_array = array;
int median = findKThLargest(_array.Length / 2);
int left = 0, i = 0, right = _array.Length - 1;
while (i <= right)
{
if (_array[newIndex(i)] > median)
{
//put newIndex(i) at odd index(from 1, 3, to 5, ...)
swap(newIndex(left++), newIndex(i));
i++;
}
else if (_array[newIndex(i)] < median)
{
//put newIndex(i) at even index(max even index to little .... )
swap(newIndex(right--), newIndex(i)); //right--, so i relatively toward right 1 step
}
else
{
i++;
}
}
return _array;
}
private int newIndex(int index)
{
return (1 + 2 * index) % (_array.Length | 1);
}
private void swap(int i, int j)
{
int tmp = _array[i];
_array[i] = _array[j];
_array[j] = tmp;
}
//based on quick sort to find the Kth largest in _array
private int findKThLargest(int k)
{
int left = 0;
int right = _array.Length - 1;
while (true)
{
int pivotIndex = quickSort(left, right);
if (k == pivotIndex)
return _array[pivotIndex];
else if (k < pivotIndex)
right = pivotIndex - 1;
else
left = pivotIndex + 1;
}
}
private int quickSort(int lo, int hi)
{
int key = _array[lo];
while (lo < hi)
{
while (lo < hi && _array[hi] >= key)
hi--;
//hi is less than key, hi element moves to lo index
_array[lo] = _array[hi];
while (lo < hi && _array[lo] < key)
lo++;
//lo is bigger than key, lo element moves to hi index
_array[hi] = _array[lo];
}
_array[lo] = key;
return lo;
}
}
}
| mit | C# | |
c3245f8d89bdb988ad86a2f1991a24002574045a | Add HttpModule | whongxiao/Refactor-Bruce-Blog,whongxiao/Refactor-Bruce-Blog,whongxiao/Refactor-Bruce-Blog,whongxiao/Refactor-Bruce-Blog,whongxiao/Refactor-Bruce-Blog | blog/App_Code/NHibernateBindCurrentSession.cs | blog/App_Code/NHibernateBindCurrentSession.cs | using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NHibernate;
using NHibernate.Context;
using NHibernateUtility;
/// <summary>
/// NHibernateBindCurrentSession 的摘要说明
/// </summary>
public class NHibernateBindCurrentSession:IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
context.EndRequest += new EventHandler(Application_EndRequest);
}
public void Dispose()
{
}
private void Application_BeginRequest(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
//ISession session = NHibernateSessionHelper.OpenSession("Model");
ISession session = NHibernateSessionHelper.GetCurrentSession();
// CurrentSessionContext.Bind(session);
}
private void Application_EndRequest(object sender,EventArgs e)
{
ISession session = CurrentSessionContext.Unbind(NHibernateSessionHelper.SessionFactory);
if(session!=null)
try
{
if(session.IsOpen==true)
if(session.IsConnected==true&&session.Transaction.IsActive==true)
session.Transaction.Commit();
}
catch (Exception ex)
{
session.Transaction.Rollback();
}
finally
{
if (session.IsOpen == true)
session.Close();
}
}
}
| apache-2.0 | C# | |
f1d8f9514ed90283d74fa5594fc0da0748fb8280 | Rename task_1_3_8_4.cs to task_1_3_8_5.cs | AndrewTurlanov/ANdrew | task_1_3_8_5.cs | task_1_3_8_5.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
/*
Сделать метод DrawPyramid который принимает 1 параметр типа int size.
Результатом этого метода должна быть отрисованная в консоли пирамида размером size.
*/
DrawPyramid(6);
}
static void DrawPyramid(int size)
{
int rowOstatok, columnOstatok, rowStart, columnStart, maxRowDigit, maxColumnDigit;
for (int i = 0; i < size; i++)
{
//столбцы
for (int j = 0; j < size; j++)
{
//строки
rowOstatok = size - i;
columnOstatok = size - j;
rowStart = i + 1;
columnStart = j + 1;
// до середины выбираем из мин. из rowStart,columnStart, потом идем вниз и уже смотрим rowOstatok и columnOstatok
maxRowDigit = Math.Min(rowStart, columnStart);
maxColumnDigit = Math.Min(rowOstatok, columnOstatok);
Console.Write(Math.Min(maxRowDigit, maxColumnDigit));
}
Console.WriteLine();
}
}
}
}
| apache-2.0 | C# | |
c522ef1a0f12237b8c65822835f125c0a3696640 | Create GravityCenter.cs | scmcom/unitycode | GravityCenter.cs | GravityCenter.cs | using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class GravityCenter : MonoBehaviour {
// Rigidbody rigidbody;
public Rigidbody rb;
public Rigidbody rb2;
// public Transform pi;
// public Transform twopi;
// public float orbitTime = 1.0f;
// private float startTime;
void Start()
{
// startTime = Time.time;
rb = GetComponent<Rigidbody>();
}
void Update()
{
//origin for the center of gravity / BLACK HOLE!
Vector3 gravityOrigin = new Vector3(0.0f,0.5f,0.0f);
Vector3 toGravityOriginFromObject = gravityOrigin - gameObject.transform.position;
toGravityOriginFromObject.Normalize();
float accelertaionDueToGravity = 9.8f;
toGravityOriginFromObject *= (
accelertaionDueToGravity * gameObject.GetComponent<Rigidbody>().mass * Time.deltaTime);
//apply accel
gameObject.GetComponent<Rigidbody>().AddForce(toGravityOriginFromObject, ForceMode.Acceleration);
rb.transform.RotateAround(Vector3.zero, Vector3.up, 20 * Time.deltaTime);
}
void FixedUpdate()
{
// Vector3 center = (pi.position + twopi.position) * 0.5f;
// center -= new Vector3(0,1,0);
// Vector3 inRelCenter = pi.position - center;
// Vector3 outRelCenter = twopi.position - center;
// float fracComplete = (Time.time - startTime) / orbitTime;
// transform.position = Vector3.Slerp(inRelCenter, outRelCenter, fracComplete);
// transform.position += center;
}
}
| mit | C# | |
e75263bf6ca89563550cf7f32548905bd2203bd4 | Add Rect <-> Vector2i collisions | neon2d/neonGL,neon2d/neon2d,DontBelieveMe/neon2d | neon2d/neon2d/Physics.cs | neon2d/neon2d/Physics.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using neon2d.Math;
namespace neon2d.Physics
{
public class Rect
{
public float x, y;
public float width, height;
public Rect(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public bool intersects(Rect other)
{
return this.x + this.width > other.x && this.x < other.x + other.width
&&
this.y + this.height > other.y && this.y < other.y + other.height;
}
public bool intersects(Vector2i other)
{
return other.x > this.x && other.x < this.x + width && other.y > this.y && other.y < this.y;
}
}
public class Circle
{
public float centerX, centerY;
public float radius;
public Circle(int centerX, int centerY, int radius)
{
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
}
public Circle(Vector2i centerPoint, int radius)
{
this.centerX = centerPoint.x;
this.centerY = centerPoint.y;
this.radius = radius;
}
public bool intersects(Vector2i other)
{
return other.x >= centerX - radius && other.x <= centerX + radius
&& other.y >= centerY - radius && other.y <= centerY + radius;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using neon2d.Math;
namespace neon2d.Physics
{
public class Rect
{
public float x, y;
public float width, height;
public Rect(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public bool intersects(Rect other)
{
return this.x + this.width > other.x && this.x < other.x + other.width
&&
this.y + this.height > other.y && this.y < other.y + other.height;
}
}
public class Circle
{
public float centerX, centerY;
public float radius;
public Circle(int centerX, int centerY, int radius)
{
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
}
public Circle(Vector2i centerPoint, int radius)
{
this.centerX = centerPoint.x;
this.centerY = centerPoint.y;
this.radius = radius;
}
public bool intersects(Vector2i other)
{
return other.x >= centerX - radius && other.x <= centerX + radius
&& other.y >= centerY - radius && other.y <= centerY + radius;
}
}
}
| mit | C# |
ce48dc84ad3bf22563226862e7071bb7fd830f7c | Create MsBuildLogger.cs | sobercoder/msbuild-api-hacks | MsBuildLogger.cs | MsBuildLogger.cs | using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class MsBuildLogger : Logger
{
private StringBuilder errorLog = new StringBuilder();
/// <summary>
/// This will gather error info about the projects being built
/// </summary>
public IList<BuildTarget> Targets { get; private set; }
public IList<BuildError> Errors { get; private set; }
public IList<BuildWarning> Warnings { get; private set; }
/// <summary>
/// This will gather general info about the projects being built
/// </summary>
public IList<string> BuildDetails { get; private set; }
/// <summary>
/// Initialize is guaranteed to be called by MSBuild at the start of the build
/// before any events are raised.
/// </summary>
public override void Initialize(IEventSource eventSource)
{
BuildDetails = new List<string>();
Targets = new List<BuildTarget>();
Errors = new List<BuildError>();
Warnings = new List<BuildWarning>();
// For brevity, we'll only register for certain event types.
eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted);
eventSource.TargetFinished += new TargetFinishedEventHandler(eventSource_TargetFinished);
eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised);
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished);
}
void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
{
BuildDetails.Add(e.Message);
}
void eventSource_TargetFinished(object sender, TargetFinishedEventArgs e)
{
BuildTarget target = new BuildTarget() {
Name = e.TargetName,
File = e.TargetFile,
Succeeded = e.Succeeded,
Outputs = e.TargetOutputs
};
Targets.Add(target);
}
void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
{
// BuildErrorEventArgs adds LineNumber, ColumnNumber, File, amongst other parameters
BuildError error = new BuildError() {
File = e.File,
Timestamp = e.Timestamp,
LineNumber = e.LineNumber,
ColumnNumber = e.ColumnNumber,
Code = e.Code,
Message = e.Message,
};
Errors.Add(error);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
BuildWarning warning = new BuildWarning()
{
File = e.File,
Timestamp = e.Timestamp,
LineNumber = e.LineNumber,
ColumnNumber = e.ColumnNumber,
Code = e.Code,
Message = e.Message,
};
Warnings.Add(warning);
}
void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
{
Console.WriteLine(e.Message);
}
/// <summary>
/// Shutdown() is guaranteed to be called by MSBuild at the end of the build, after all
/// events have been raised.
/// </summary>
public override void Shutdown()
{
// Done logging, let go of the file
// Errors = errorLog.ToString();
}
}
| unlicense | C# | |
3d7d1d39ab148732bc374a474750c86c0aaa44c4 | Add test for PeerList | BYVoid/distribox | src/Distribox.Network/PeerListTest.cs | src/Distribox.Network/PeerListTest.cs | namespace Distribox.Network
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
[TestFixture]
class PeerListTest
{
[Test]
public void TestOperation()
{
string fileName = "peerList.test.tmp";
string fileName2 = "peerList.test.tmp2";
PeerList pList = new PeerList(fileName);
Assert.AreEqual(fileName, pList.PeerFileName);
Assert.AreEqual(0, pList.Peers.Count);
Peer peer1 = new Peer("127.0.0.1", 8888);
Peer peer2 = new Peer("127.0.0.2", 8888);
Peer peer3 = new Peer("127.0.0.2", 9999);
pList.AddPeer(peer1);
Assert.AreEqual(1, pList.Peers.Count);
pList.AddPeer(peer1);
Assert.AreEqual(1, pList.Peers.Count);
Assert.IsTrue(pList.Peers.Contains(peer1));
Assert.IsFalse(pList.Peers.Contains(peer2));
// Test FileOperation
PeerList pList2 = PeerList.GetPeerList(fileName);
Assert.AreEqual(1, pList.Peers.Count);
Assert.IsTrue(pList.Peers.Contains(peer1));
Assert.IsFalse(pList.Peers.Contains(peer2));
pList2.AddPeer(peer2);
Assert.IsFalse(pList.Peers.Contains(peer2));
pList = PeerList.GetPeerList(fileName);
Assert.IsTrue(pList.Peers.Contains(peer2));
// Test Merge
PeerList pList3 = PeerList.GetPeerList(fileName2);
Assert.AreEqual(0, pList3.Peers.Count);
pList3.AddPeer(peer3);
Assert.AreEqual(1, pList3.Peers.Count);
pList3.MergeWith(pList2);
Assert.IsTrue(pList3.Peers.Contains(peer1));
Assert.IsTrue(pList3.Peers.Contains(peer2));
Assert.IsTrue(pList3.Peers.Contains(peer3));
int peer1Cnt = 0, peer2Cnt = 0;
for (int i = 0; i < 10000; ++i)
{
Peer peer = pList2.SelectRandomPeer();
Assert.IsTrue(pList2.Peers.Contains(peer));
Assert.IsTrue(peer.Equals(peer1) || peer.Equals(peer2));
if (peer.Equals(peer1))
{
++peer1Cnt;
}
else
{
++peer2Cnt;
}
}
Assert.Less((double)(Math.Abs(peer1Cnt - peer2Cnt) / 10000), 0.05);
// Clean up
File.Delete(fileName);
File.Delete(fileName2);
}
}
}
| mit | C# | |
6a5d3138e683fd4ee143b3b61c3f9a9b3487df71 | Add support for LoadRules and ExtractRules commands | agardiner/hfmcmd,agardiner/hfmcmd,agardiner/hfmcmd | src/hfm/RulesLoad.cs | src/hfm/RulesLoad.cs | using System;
using System.IO;
using log4net;
using HSVSESSIONLib;
using HSVRULESLOADACVLib;
using HFMCONSTANTSLib;
using Command;
using HFMCmd;
namespace HFM
{
public class RulesLoad
{
/// <summary>
/// Defines the possible rule file formats.
/// </summary>
public enum ERulesFormat
{
Native = 0,
CalcManager = 1
}
// Reference to class logger
protected static readonly ILog _log = LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Reference to HFM HsvRulesLoadACV object
internal readonly HsvRulesLoadACV HsvRulesLoad;
[Factory]
public RulesLoad(Session session)
{
HsvRulesLoad = new HsvRulesLoadACV();
HsvRulesLoad.SetSession(session.HsvSession, (int)tagHFM_LANGUAGES.HFM_LANGUAGE_INSTALLED);
}
[Command("Loads an HFM application's calculation rules from a native rule or Calculation Manager XML file")]
public void LoadRules(
[Parameter("Path to the source rules file")]
string rulesFile,
[Parameter("Path to the load log file; if not specified, defaults to same path " +
"and name as the source rules file.",
DefaultValue = null)]
string logFile,
[Parameter("Scan rules file for syntax errors, rather than loading it",
DefaultValue = false)]
bool scanOnly,
[Parameter("Check integrity of intercompany transactions following rules load",
DefaultValue = false)]
bool checkIntegrity)
{
bool errors = false, warnings = false, info = false;
if(logFile == null || logFile == "") {
logFile = Path.ChangeExtension(rulesFile, ".log");
}
// Ensure rules file exists and logFile is writeable
Utilities.FileExists(rulesFile);
Utilities.FileWriteable(logFile);
HFM.Try("Loading rules",
() => HsvRulesLoad.LoadCalcRules2(rulesFile, logFile, scanOnly, checkIntegrity,
out errors, out warnings, out info));
if(errors) {
_log.Error("Rules load resulted in errors; check log file for details");
// TODO: Should we show the warnings here?
}
if(warnings) {
_log.Warn("Rules load resulted in warnings; check log file for details");
// TODO: Should we show the warnings here?
}
}
[Command("Extracts an HFM application's rules to a native ASCII or XML file")]
public void ExtractRules(
[Parameter("Path to the generated rules extract file")]
string rulesFile,
[Parameter("Path to the extract log file; if not specified, defaults to same path " +
"and name as extract file.", DefaultValue = null)]
string logFile,
[Parameter("Format in which to extract rules", DefaultValue = ERulesFormat.Native)]
ERulesFormat rulesFormat)
{
if(logFile == null || logFile == "") {
logFile = Path.ChangeExtension(rulesFile, ".log");
}
// TODO: Display options etc
_log.FineFormat(" Rules file: {0}", rulesFile);
_log.FineFormat(" Log file: {0}", logFile);
// Ensure rulesFile and logFile are writeable locations
Utilities.FileWriteable(rulesFile);
Utilities.FileWriteable(logFile);
HFM.Try("Extracting rules",
() => HsvRulesLoad.ExtractCalcRulesEx(rulesFile, logFile, (int)rulesFormat));
}
}
}
| bsd-2-clause | C# | |
a82e52b6255e11785820b2828c5ce62899fc7c17 | fix bookshelf | MediaBrowser/Emby.Plugins,SvenVandenbrande/Emby.Plugins,SvenVandenbrande/Emby.Plugins,MediaBrowser/Emby.Plugins,SvenVandenbrande/Emby.Plugins,heksesang/Emby.Plugins,heksesang/Emby.Plugins,heksesang/Emby.Plugins | Bookshelf/Plugin.cs | Bookshelf/Plugin.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MBBookshelf.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
namespace MBBookshelf
{
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{
public readonly SemaphoreSlim GoogleBooksSemiphore = new SemaphoreSlim(5, 5);
public readonly SemaphoreSlim ComicVineSemiphore = new SemaphoreSlim(5, 5);
/// <summary>
///
/// </summary>
/// <param name="applicationPaths"></param>
/// <param name="xmlSerializer"></param>
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
: base(applicationPaths, xmlSerializer)
{
Instance = this;
}
/// <summary>
///
/// </summary>
public override string Name
{
get { return "MB Bookshelf"; }
}
public IEnumerable<PluginPageInfo> GetPages()
{
return new[]
{
new PluginPageInfo
{
Name = Name,
EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html"
}
};
}
/// <summary>
///
/// </summary>
public static Plugin Instance { get; private set; }
/// <summary>
///
/// </summary>
public PluginConfiguration PluginConfiguration
{
get { return Configuration; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MBBookshelf.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
namespace MBBookshelf
{
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{
public readonly SemaphoreSlim GoogleBooksSemiphore = new SemaphoreSlim(5, 5);
public readonly SemaphoreSlim ComicVineSemiphore = new SemaphoreSlim(5, 5);
/// <summary>
///
/// </summary>
/// <param name="applicationPaths"></param>
/// <param name="xmlSerializer"></param>
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
: base(applicationPaths, xmlSerializer)
{
Instance = this;
}
/// <summary>
///
/// </summary>
public override string Name
{
get { return "MB Bookshelf"; }
}
public IEnumerable<PluginPageInfo> GetPages()
{
return new[]
{
new PluginPageInfo
{
Name = Name,
EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
}
};
}
/// <summary>
///
/// </summary>
public static Plugin Instance { get; private set; }
/// <summary>
///
/// </summary>
public PluginConfiguration PluginConfiguration
{
get { return Configuration; }
}
}
}
| mit | C# |
c53ec61945df55c803e45e5506b71e06c18387c5 | Add PostHelper | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Rest/Entities/Feeds/PostHelper.cs | src/NTwitch.Rest/Entities/Feeds/PostHelper.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
internal class PostHelper
{
public static Task CreateReactionAsync(RestPostComment post, ulong emoteid)
{
throw new NotImplementedException();
}
public static Task DeleteReactionAsync(RestPostComment post, ulong emoteid)
{
throw new NotImplementedException();
}
internal static Task<RestPostComment> CreateCommentAsync(RestPost restPost, string content)
{
throw new NotImplementedException();
}
internal static Task<RestPost> DeleteAsync(RestPost restPost)
{
throw new NotImplementedException();
}
internal static Task<RestPostComment> DeleteCommentAsync(RestPost restPost, ulong commentid)
{
throw new NotImplementedException();
}
internal static Task<IEnumerable<RestPostComment>> GetCommentsAsync(RestPost restPost, TwitchPageOptions options)
{
throw new NotImplementedException();
}
internal static Task<RestPostComment> DeleteReactionAsync(RestPost restPost, ulong emoteid)
{
throw new NotImplementedException();
}
internal static Task<Task> CreateReactionAsync(RestPost restPost, ulong emoteid)
{
throw new NotImplementedException();
}
}
}
| mit | C# | |
dd38e718fc82b1b3c60f1f807594e8e71176bf40 | Add redirect. | Giftednewt/roslyn,swaroop-sridhar/roslyn,genlu/roslyn,AnthonyDGreen/roslyn,tannergooding/roslyn,bbarry/roslyn,Giftednewt/roslyn,jhendrixMSFT/roslyn,DustinCampbell/roslyn,cston/roslyn,tvand7093/roslyn,bkoelman/roslyn,TyOverby/roslyn,dpoeschl/roslyn,srivatsn/roslyn,agocke/roslyn,Shiney/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,natidea/roslyn,vslsnap/roslyn,ErikSchierboom/roslyn,abock/roslyn,genlu/roslyn,drognanar/roslyn,amcasey/roslyn,mmitche/roslyn,AArnott/roslyn,weltkante/roslyn,diryboy/roslyn,dotnet/roslyn,xasx/roslyn,Shiney/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KevinRansom/roslyn,jmarolf/roslyn,Giftednewt/roslyn,mattscheffer/roslyn,drognanar/roslyn,lorcanmooney/roslyn,mattwar/roslyn,balajikris/roslyn,jmarolf/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,KiloBravoLima/roslyn,KevinH-MS/roslyn,tmeschter/roslyn,genlu/roslyn,Hosch250/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,KevinH-MS/roslyn,robinsedlaczek/roslyn,jeffanders/roslyn,robinsedlaczek/roslyn,VSadov/roslyn,tmat/roslyn,natidea/roslyn,paulvanbrenk/roslyn,physhi/roslyn,nguerrera/roslyn,pdelvo/roslyn,davkean/roslyn,mgoertz-msft/roslyn,gafter/roslyn,jkotas/roslyn,Hosch250/roslyn,KevinH-MS/roslyn,Hosch250/roslyn,AmadeusW/roslyn,srivatsn/roslyn,khyperia/roslyn,jhendrixMSFT/roslyn,dpoeschl/roslyn,balajikris/roslyn,wvdd007/roslyn,reaction1989/roslyn,tmat/roslyn,OmarTawfik/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,diryboy/roslyn,weltkante/roslyn,agocke/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,jamesqo/roslyn,vslsnap/roslyn,akrisiun/roslyn,amcasey/roslyn,AArnott/roslyn,stephentoub/roslyn,cston/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,jcouv/roslyn,tmeschter/roslyn,vslsnap/roslyn,Shiney/roslyn,mmitche/roslyn,ErikSchierboom/roslyn,dpoeschl/roslyn,VSadov/roslyn,jhendrixMSFT/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,DustinCampbell/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,swaroop-sridhar/roslyn,tvand7093/roslyn,AlekseyTs/roslyn,bkoelman/roslyn,bartdesmet/roslyn,kelltrick/roslyn,orthoxerox/roslyn,MattWindsor91/roslyn,kelltrick/roslyn,abock/roslyn,davkean/roslyn,davkean/roslyn,lorcanmooney/roslyn,jcouv/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,kelltrick/roslyn,mgoertz-msft/roslyn,tmat/roslyn,zooba/roslyn,sharwell/roslyn,wvdd007/roslyn,Pvlerick/roslyn,diryboy/roslyn,yeaicc/roslyn,abock/roslyn,OmarTawfik/roslyn,a-ctor/roslyn,MattWindsor91/roslyn,CyrusNajmabadi/roslyn,amcasey/roslyn,TyOverby/roslyn,ljw1004/roslyn,nguerrera/roslyn,ljw1004/roslyn,weltkante/roslyn,reaction1989/roslyn,CyrusNajmabadi/roslyn,AnthonyDGreen/roslyn,gafter/roslyn,bbarry/roslyn,balajikris/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,jamesqo/roslyn,paulvanbrenk/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,cston/roslyn,khyperia/roslyn,AArnott/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,physhi/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,jkotas/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,CyrusNajmabadi/roslyn,bkoelman/roslyn,pdelvo/roslyn,zooba/roslyn,tannergooding/roslyn,mattscheffer/roslyn,brettfo/roslyn,orthoxerox/roslyn,heejaechang/roslyn,mavasani/roslyn,brettfo/roslyn,dotnet/roslyn,a-ctor/roslyn,pdelvo/roslyn,bbarry/roslyn,physhi/roslyn,xoofx/roslyn,xoofx/roslyn,heejaechang/roslyn,paulvanbrenk/roslyn,akrisiun/roslyn,mavasani/roslyn,lorcanmooney/roslyn,jeffanders/roslyn,jcouv/roslyn,AnthonyDGreen/roslyn,dotnet/roslyn,MattWindsor91/roslyn,jkotas/roslyn,ljw1004/roslyn,Pvlerick/roslyn,OmarTawfik/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,yeaicc/roslyn,aelij/roslyn,xoofx/roslyn,AmadeusW/roslyn,sharwell/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,mattwar/roslyn,akrisiun/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,khyperia/roslyn,KevinRansom/roslyn,xasx/roslyn,xasx/roslyn,CaptainHayashi/roslyn,mattwar/roslyn,orthoxerox/roslyn,drognanar/roslyn,eriawan/roslyn,DustinCampbell/roslyn,Pvlerick/roslyn,yeaicc/roslyn,natidea/roslyn,robinsedlaczek/roslyn,mavasani/roslyn,a-ctor/roslyn,KiloBravoLima/roslyn,srivatsn/roslyn,jeffanders/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,CaptainHayashi/roslyn,zooba/roslyn,mgoertz-msft/roslyn,TyOverby/roslyn,mattscheffer/roslyn,aelij/roslyn,tvand7093/roslyn,bartdesmet/roslyn,aelij/roslyn,VSadov/roslyn,CaptainHayashi/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,mmitche/roslyn,jamesqo/roslyn,KiloBravoLima/roslyn | src/VisualStudio/Setup.Next/AssemblyRedirects.cs | src/VisualStudio/Setup.Next/AssemblyRedirects.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Roslyn.VisualStudio.Setup;
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.EditorFeatures.Next.dll")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.CallHierarchy.Package.Definitions",
GenerateCodeBase = false,
PublicKeyToken = "31BF3856AD364E35",
OldVersionLowerBound = "14.0.0.0",
OldVersionUpperBound = "14.9.9.9",
NewVersion = "15.0.0.0")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\StreamJsonRpc.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Microsoft.ServiceHub.Client.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Newtonsoft.Json.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Microsoft.VisualStudio.Shell.Framework.dll")] | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Roslyn.VisualStudio.Setup;
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.EditorFeatures.Next.dll")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.CallHierarchy.Package.Definitions",
GenerateCodeBase = false,
PublicKeyToken = "31BF3856AD364E35",
OldVersionLowerBound = "14.0.0.0",
OldVersionUpperBound = "14.9.9.9",
NewVersion = "15.0.0.0")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\StreamJsonRpc.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Microsoft.ServiceHub.Client.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Newtonsoft.Json.dll")] | mit | C# |
1bb62020c9e1749e27083c2c2c8fe2d9a7765ab1 | add category extensions | arrowflex/FreeAgent | src/FreeAgent/ModelExtensions/CategoryExtensions.cs | src/FreeAgent/ModelExtensions/CategoryExtensions.cs | using FreeAgent.Model;
using System;
using System.Threading.Tasks;
using FreeAgent.Helpers;
namespace FreeAgent
{
public static class CategoryExtensions
{
public static async Task<Categories> GetCategoriesAsync(this FreeAgentClient client)
{
var result = await client.Execute(c => c.CategoryList(client.Configuration.CurrentHeader));
return result;
}
public static async Task<Category> GetCategoryAsync(this FreeAgentClient client, Category category)
{
if (category == null || category.NominalCode.IsNullOrEmpty())
return null;
return await client.GetCategoryAsync(category.NominalCode);
}
public static async Task<Category> GetCategoryAsync(this FreeAgentClient client, string nominalCode)
{
var result = await client.Execute(c => c.GetCategory(client.Configuration.CurrentHeader, nominalCode));
if (result != null)
{
if (result.AdminExpensesCategories != null)
return result.AdminExpensesCategories;
if (result.CostOfSalesCategories != null)
return result.CostOfSalesCategories;
if (result.GeneralCategories != null)
return result.GeneralCategories;
if (result.IncomeCategories != null)
return result.IncomeCategories;
}
return null; //TODO - make this work like a true fail (ie wrong nominal code)
}
}
}
| apache-2.0 | C# | |
893adb15869b72062ed411388ce7a66127107413 | Add UptimeController | OlsonDev/PersonalWebApp,OlsonDev/PersonalWebApp | Controllers/UptimeController.cs | Controllers/UptimeController.cs | using System;
using System.Globalization;
using Microsoft.AspNet.Mvc;
namespace PersonalWebApp.Controllers {
public class UptimeController : Controller {
public IActionResult Ping() {
return Content(DateTime.Now.ToString("o"));
}
}
} | mit | C# | |
219990b0785df14f5f7fc96cdb79f0d0cbd379c0 | Add test vector from draft-arciszewski-xchacha-00 | ektrah/nsec | tests/Rfc/XChaCha20Poly1305Tests.cs | tests/Rfc/XChaCha20Poly1305Tests.cs | using System;
using NSec.Cryptography;
using NSec.Experimental.Sodium;
using Xunit;
namespace NSec.Tests.Rfc
{
public static class XChaCha20Poly1305Tests
{
public static readonly TheoryData<string[]> TestVectors = new TheoryData<string[]>
{
// https://tools.ietf.org/html/draft-arciszewski-xchacha-00#appendix-A.1
new string[] { "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e", "50515253c0c1c2c3c4c5c6c7", "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", "404142434445464748494a4b4c4d4e4f5051525354555657", "bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb731c7f1b0b4aa6440bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b4522f8c9ba40db5d945b11b69b982c1bb9e3f3fac2bc369488f76b2383565d3fff921f9664c97637da9768812f615c68b13b52e", "c0875924c1c7987947deafd8780acf49" },
};
[Theory]
[MemberData(nameof(TestVectors))]
public static void Test(string[] testVector)
{
var plaintext = testVector[0];
var aad = testVector[1];
var key = testVector[2];
var nonce = testVector[3];
var ciphertext = testVector[4];
var tag = testVector[5];
var a = new XChaCha20Poly1305();
using (var k = Key.Import(a, key.DecodeHex(), KeyBlobFormat.RawSymmetricKey))
{
var b = a.Encrypt(k, new Nonce(nonce.DecodeHex(), 0), aad.DecodeHex(), plaintext.DecodeHex());
Assert.Equal((ciphertext + tag).DecodeHex(), b);
Assert.True(a.Decrypt(k, new Nonce(nonce.DecodeHex(), 0), aad.DecodeHex(), b, out var r));
Assert.Equal(plaintext.DecodeHex(), r);
}
}
}
}
| mit | C# | |
b06785c4964e0d86fe2e2e0050b9aaae81c164ab | Add IPartitioner interface | mayuanyang/MapReduce.Net | src/MapReduce.Net/IPartitioner.cs | src/MapReduce.Net/IPartitioner.cs | namespace MapReduce.Net
{
public interface IPartitioner
{
//Don't know what to do with this one yet
}
}
| apache-2.0 | C# | |
76648cb01faada63d3a68b49066d615967e9111d | Add video object tests | RehanSaeed/Schema.NET | Tests/Schema.NET.Test/VideoObjectTest.cs | Tests/Schema.NET.Test/VideoObjectTest.cs | namespace Schema.NET.Test
{
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
public class VideoObjectTest
{
// https://developers.google.com/search/docs/data-types/articles
[Fact]
public void ToString_VideoGoogleStructuredData_ReturnsExpectedJsonLd()
{
var videoObject = new VideoObject()
{
Name = "Title",
Description = "Video description",
ThumbnailUrl = new Uri("https://www.example.com/thumbnail.jpg"),
UploadDate = new DateTimeOffset(2015, 2, 5, 8, 0, 0, TimeSpan.Zero),
Duration = new TimeSpan(0, 1, 33),
Publisher = new Organization()
{
Name = "Example Publisher",
Logo = new ImageObject()
{
Height = 60,
Url = new Uri("https://example.com/logo.jpg"),
Width = 600
}
},
ContentUrl = new Uri("https://www.example.com/video123.flv"),
EmbedUrl = new Uri("https://www.example.com/videoplayer.swf?video=123"),
InteractionStatistic = new InteractionCounter()
{
UserInteractionCount = 2347
}
};
var expectedJson =
"{" +
"\"@context\":\"http://schema.org\"," +
"\"@type\":\"VideoObject\"," +
"\"description\":\"Video description\"," +
"\"contentUrl\":\"https://www.example.com/video123.flv\"," +
"\"duration\":\"PT1M33S\"," +
"\"embedUrl\":\"https://www.example.com/videoplayer.swf?video=123\"," +
"\"name\":\"Title\"," +
"\"uploadDate\":\"2015-02-05T08:00:00+00:00\"," +
"\"interactionStatistic\":{" +
"\"@type\":\"InteractionCounter\"," +
"\"userInteractionCount\":2347" +
"}," +
"\"publisher\":{" +
"\"@type\":\"Organization\"," +
"\"name\":\"Example Publisher\"," +
"\"logo\":{" +
"\"@type\":\"ImageObject\"," +
"\"height\":60," +
"\"url\":\"https://example.com/logo.jpg\"," +
"\"width\":600" +
"}" +
"}," +
"\"thumbnailUrl\":\"https://www.example.com/thumbnail.jpg\"" +
"}";
var json = videoObject.ToString();
Assert.Equal(expectedJson, json);
}
}
}
| mit | C# | |
c1ae775c7ce1cbe5ec86da87be8a8c7b92c3a051 | Add extension method to provide drawable adjustments | ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework | osu.Framework/Graphics/DrawableExtensions.cs | osu.Framework/Graphics/DrawableExtensions.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;
namespace osu.Framework.Graphics
{
/// <summary>
/// Holds extension methods for <see cref="Drawable"/>.
/// </summary>
public static class DrawableExtensions
{
/// <summary>
/// Adjusts specified properties of a <see cref="Drawable"/>.
/// </summary>
/// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param>
/// <param name="adjustment">The adjustment function.</param>
/// <returns>The given <see cref="Drawable"/>.</returns>
public static T With<T>(this T drawable, Action<T> adjustment)
where T : Drawable
{
adjustment?.Invoke(drawable);
return drawable;
}
}
}
| mit | C# | |
49d3a3af15e8d6d57a8fe55c51402ff3e14f3849 | Adjust FinishedLaunching() structure | andypaul/monotouch-samples,kingyond/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,hongnguyenpro/monotouch-samples,a9upam/monotouch-samples,iFreedive/monotouch-samples,W3SS/monotouch-samples,davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,sakthivelnagarajan/monotouch-samples,markradacz/monotouch-samples,xamarin/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,iFreedive/monotouch-samples,davidrynn/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,W3SS/monotouch-samples,nelzomal/monotouch-samples,markradacz/monotouch-samples,andypaul/monotouch-samples,sakthivelnagarajan/monotouch-samples,albertoms/monotouch-samples,robinlaide/monotouch-samples,a9upam/monotouch-samples,albertoms/monotouch-samples,YOTOV-LIMITED/monotouch-samples,peteryule/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,kingyond/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,xamarin/monotouch-samples,robinlaide/monotouch-samples,iFreedive/monotouch-samples,hongnguyenpro/monotouch-samples,a9upam/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,hongnguyenpro/monotouch-samples,YOTOV-LIMITED/monotouch-samples,albertoms/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,nervevau2/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,peteryule/monotouch-samples,nelzomal/monotouch-samples,robinlaide/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples | OpenGLESSample-GameView/Main.cs | OpenGLESSample-GameView/Main.cs | using UIKit;
namespace OpenGLESSampleGameView
{
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
}
}
| mit | C# | |
8f3cca975e247432c825e3afcdc2961c9b45e4f0 | remove debug code | DecaTec/windows-universal,scherke85/windows-universal,scherke/windows-universal,SunboX/windows-universal,scherke/windows-universal,altima/windows-universal,altima/windows-universal,SunboX/windows-universal,TheScientist/windows-universal,altima/windows-universal,scherke85/windows-universal,TheScientist/windows-universal,scherke/windows-universal,DecaTec/windows-universal,DecaTec/windows-universal,TheScientist/windows-universal,SunboX/windows-universal,scherke85/windows-universal | NextcloudApp/AppShell.xaml.cs | NextcloudApp/AppShell.xaml.cs | using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using NextcloudApp.Services;
namespace NextcloudApp
{
public sealed partial class AppShell
{
public AppShell()
{
InitializeComponent();
ShowUpdateMessage();
}
private void ShowUpdateMessage()
{
if (SettingsService.Instance.LocalSettings.ShowUpdateMessage)
{
UpdateNotificationService.NotifyUser(UpdateDialogContainer, UpdateDialogTitle, UpdateDialogContent, UpdateDialogButton1, UpdateDialogButton2);
}
else
{
SettingsService.Instance.LocalSettings.PropertyChanged += (sender, args) =>
{
if (args.PropertyName.Equals("ShowUpdateMessage") && SettingsService.Instance.LocalSettings.ShowUpdateMessage)
{
UpdateNotificationService.NotifyUser(UpdateDialogContainer, UpdateDialogTitle, UpdateDialogContent, UpdateDialogButton1, UpdateDialogButton2);
}
};
}
}
public void SetContentFrame(Frame frame)
{
RootSplitView.Content = frame;
}
public void SetMenuPaneContent(UIElement content)
{
RootSplitView.Pane = content;
}
public UIElement GetContentFrame()
{
return RootSplitView.Content;
}
}
}
| using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using NextcloudApp.Services;
namespace NextcloudApp
{
public sealed partial class AppShell
{
public AppShell()
{
InitializeComponent();
ShowUpdateMessage();
}
private void ShowUpdateMessage()
{
UpdateNotificationService.NotifyUser(UpdateDialogContainer, UpdateDialogTitle, UpdateDialogContent, UpdateDialogButton1, UpdateDialogButton2);
if (SettingsService.Instance.LocalSettings.ShowUpdateMessage)
{
UpdateNotificationService.NotifyUser(UpdateDialogContainer, UpdateDialogTitle, UpdateDialogContent, UpdateDialogButton1, UpdateDialogButton2);
}
else
{
SettingsService.Instance.LocalSettings.PropertyChanged += (sender, args) =>
{
if (args.PropertyName.Equals("ShowUpdateMessage") && SettingsService.Instance.LocalSettings.ShowUpdateMessage)
{
UpdateNotificationService.NotifyUser(UpdateDialogContainer, UpdateDialogTitle, UpdateDialogContent, UpdateDialogButton1, UpdateDialogButton2);
}
};
}
}
public void SetContentFrame(Frame frame)
{
RootSplitView.Content = frame;
}
public void SetMenuPaneContent(UIElement content)
{
RootSplitView.Pane = content;
}
public UIElement GetContentFrame()
{
return RootSplitView.Content;
}
}
}
| mpl-2.0 | C# |
c6b15fd523a83dc0336ec9add90f6e0188dbe52b | Create InvocationHelper.cs | smusenok/misc | InvocationHelper.cs | InvocationHelper.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Temp
{
class Program
{
static void Main()
{
var method = GetInvoker(typeof(My).GetMethod("Get"));
var param = new object[] { 500, 0, 1 };
try { method(new My(), param); } catch { }
Console.WriteLine("{0}, {1}, {2}", param[0],param[1],param[2]);
}
static Action<object, object[]> GetInvoker(MethodInfo method)
{
var instanceType = method.DeclaringType;
var paramInfos = method.GetParameters();
var instance = Expression.Parameter(typeof(object));
var outputParameters = Expression.Parameter(typeof(object[]));
var variables = new ParameterExpression[paramInfos.Length];
var preAssigns = new Expression[paramInfos.Length];
var postAssigns = new Expression[paramInfos.Length];
for (var i = 0; i < paramInfos.Length; i++)
{
var paramType = paramInfos[i].ParameterType;
if (paramType.IsByRef)
paramType = paramType.GetElementType();
variables[i] = Expression.Parameter(paramType);
preAssigns[i] = Expression.Assign(variables[i],
Expression.Convert(
Expression.ArrayAccess(outputParameters,
Expression.Constant(i)), paramType));
postAssigns[i] = Expression.Assign(
Expression.ArrayAccess(outputParameters,
Expression.Constant(i)),
Expression.Convert(variables[i], typeof(object)));
}
return Expression.Lambda<Action<object, object[]>>(
Expression.Block(
variables,
Expression.Block(Enumerable.Empty<ParameterExpression>(), preAssigns),
Expression.TryFinally(
Expression.Call(instanceType == null ? null : Expression.Convert(instance, instanceType), method, variables),
Expression.Block(Enumerable.Empty<ParameterExpression>(), postAssigns)))
, instance, outputParameters)
.Compile();
}
class My
{
public void Get(int input, out int result, ref int refval)
{
refval++;
result = 1000000 + input;
throw new Exception();
}
}
}
}
| mit | C# | |
94bd1270ac849b5f29cddc24edb132815e7d23f8 | Remove unused using. | lorcanmooney/roslyn,sharwell/roslyn,AnthonyDGreen/roslyn,jasonmalinowski/roslyn,vslsnap/roslyn,brettfo/roslyn,zooba/roslyn,MichalStrehovsky/roslyn,akrisiun/roslyn,tmat/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,jmarolf/roslyn,bkoelman/roslyn,vslsnap/roslyn,eriawan/roslyn,mavasani/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,KevinH-MS/roslyn,paulvanbrenk/roslyn,DustinCampbell/roslyn,agocke/roslyn,weltkante/roslyn,pdelvo/roslyn,tmeschter/roslyn,mattwar/roslyn,agocke/roslyn,pdelvo/roslyn,weltkante/roslyn,AnthonyDGreen/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,yeaicc/roslyn,a-ctor/roslyn,robinsedlaczek/roslyn,jcouv/roslyn,mavasani/roslyn,tvand7093/roslyn,abock/roslyn,dotnet/roslyn,Hosch250/roslyn,agocke/roslyn,heejaechang/roslyn,jkotas/roslyn,bbarry/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,a-ctor/roslyn,wvdd007/roslyn,diryboy/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,srivatsn/roslyn,robinsedlaczek/roslyn,MattWindsor91/roslyn,jkotas/roslyn,jeffanders/roslyn,jamesqo/roslyn,mmitche/roslyn,mattwar/roslyn,VSadov/roslyn,mattscheffer/roslyn,davkean/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bartdesmet/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,physhi/roslyn,lorcanmooney/roslyn,srivatsn/roslyn,Giftednewt/roslyn,gafter/roslyn,mgoertz-msft/roslyn,gafter/roslyn,cston/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,pdelvo/roslyn,jeffanders/roslyn,aelij/roslyn,genlu/roslyn,jamesqo/roslyn,jcouv/roslyn,AnthonyDGreen/roslyn,dpoeschl/roslyn,swaroop-sridhar/roslyn,mmitche/roslyn,yeaicc/roslyn,Giftednewt/roslyn,robinsedlaczek/roslyn,vslsnap/roslyn,jkotas/roslyn,KirillOsenkov/roslyn,tvand7093/roslyn,drognanar/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,jmarolf/roslyn,CaptainHayashi/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,xasx/roslyn,tmat/roslyn,tmat/roslyn,TyOverby/roslyn,AmadeusW/roslyn,VSadov/roslyn,heejaechang/roslyn,abock/roslyn,bkoelman/roslyn,OmarTawfik/roslyn,cston/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,reaction1989/roslyn,tvand7093/roslyn,kelltrick/roslyn,khyperia/roslyn,KevinH-MS/roslyn,AArnott/roslyn,davkean/roslyn,dotnet/roslyn,mmitche/roslyn,xoofx/roslyn,jamesqo/roslyn,xoofx/roslyn,CyrusNajmabadi/roslyn,orthoxerox/roslyn,Hosch250/roslyn,ErikSchierboom/roslyn,AArnott/roslyn,orthoxerox/roslyn,zooba/roslyn,bartdesmet/roslyn,Giftednewt/roslyn,abock/roslyn,nguerrera/roslyn,jmarolf/roslyn,zooba/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,jcouv/roslyn,AlekseyTs/roslyn,xasx/roslyn,kelltrick/roslyn,wvdd007/roslyn,swaroop-sridhar/roslyn,reaction1989/roslyn,bartdesmet/roslyn,stephentoub/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,bbarry/roslyn,eriawan/roslyn,stephentoub/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,khyperia/roslyn,dpoeschl/roslyn,TyOverby/roslyn,amcasey/roslyn,CaptainHayashi/roslyn,akrisiun/roslyn,mattwar/roslyn,cston/roslyn,khyperia/roslyn,tmeschter/roslyn,aelij/roslyn,KirillOsenkov/roslyn,kelltrick/roslyn,MattWindsor91/roslyn,diryboy/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,genlu/roslyn,tannergooding/roslyn,davkean/roslyn,AArnott/roslyn,tmeschter/roslyn,dotnet/roslyn,akrisiun/roslyn,mattscheffer/roslyn,Hosch250/roslyn,sharwell/roslyn,KevinH-MS/roslyn,panopticoncentral/roslyn,bbarry/roslyn,panopticoncentral/roslyn,a-ctor/roslyn,mgoertz-msft/roslyn,xoofx/roslyn,amcasey/roslyn,weltkante/roslyn,CaptainHayashi/roslyn,gafter/roslyn,TyOverby/roslyn,KirillOsenkov/roslyn,amcasey/roslyn,xasx/roslyn,MichalStrehovsky/roslyn,OmarTawfik/roslyn,brettfo/roslyn,mattscheffer/roslyn,reaction1989/roslyn,yeaicc/roslyn,orthoxerox/roslyn,OmarTawfik/roslyn,drognanar/roslyn,bkoelman/roslyn,MattWindsor91/roslyn,VSadov/roslyn,mavasani/roslyn,dpoeschl/roslyn,lorcanmooney/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,jeffanders/roslyn,MichalStrehovsky/roslyn,DustinCampbell/roslyn,genlu/roslyn,srivatsn/roslyn,physhi/roslyn,drognanar/roslyn,sharwell/roslyn,physhi/roslyn | src/Features/CSharp/Portable/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.InlineDeclarationFixAllProvider.cs | src/Features/CSharp/Portable/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.InlineDeclarationFixAllProvider.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.FixAllOccurrences;
namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration
{
internal partial class CSharpInlineDeclarationCodeFixProvider : CodeFixProvider
{
private class InlineDeclarationFixAllProvider : DocumentBasedFixAllProvider
{
private readonly CSharpInlineDeclarationCodeFixProvider _provider;
public InlineDeclarationFixAllProvider(CSharpInlineDeclarationCodeFixProvider provider)
{
_provider = provider;
}
protected override Task<Document> FixDocumentAsync(
Document document,
ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
return _provider.FixAllAsync(document, diagnostics, cancellationToken);
}
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.FixAllOccurrences;
namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration
{
internal partial class CSharpInlineDeclarationCodeFixProvider : CodeFixProvider
{
private class InlineDeclarationFixAllProvider : DocumentBasedFixAllProvider
{
private readonly CSharpInlineDeclarationCodeFixProvider _provider;
public InlineDeclarationFixAllProvider(CSharpInlineDeclarationCodeFixProvider provider)
{
_provider = provider;
}
protected override Task<Document> FixDocumentAsync(
Document document,
ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
return _provider.FixAllAsync(document, diagnostics, cancellationToken);
}
}
}
} | mit | C# |
5c98554e0594eac5f67a7893ebeb0340588500a3 | Add license | waltersoto/PortableMD5 | PortableMD5/PortableMD5/MD5Extensions.cs | PortableMD5/PortableMD5/MD5Extensions.cs | /*
The MIT License (MIT)
Copyright (c) 2015 Walter M. Soto Reyes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Text;
namespace PortableMD5
{
public static class Md5Extensions
{
public static uint RotateLeft(this uint val, int count)
{
return (val << count) | (val >> (32 - count));
}
public static uint RotateRight(this uint val, int count)
{
return (val >> count) | (val << (32 - count));
}
public static string ConvertToString(this byte[] byteArray)
{
return BitConverter.ToString(byteArray).Replace("-", "").ToLower();
}
public static byte[] ConvertToByteArray(this string s)
{
return Encoding.UTF8.GetBytes(s);
}
}
}
| using System;
using System.Text;
namespace PortableMD5
{
public static class Md5Extensions
{
public static uint RotateLeft(this uint val, int count)
{
return (val << count) | (val >> (32 - count));
}
public static uint RotateRight(this uint val, int count)
{
return (val >> count) | (val << (32 - count));
}
public static string ConvertToString(this byte[] byteArray)
{
return BitConverter.ToString(byteArray).Replace("-", "").ToLower();
}
public static byte[] ConvertToByteArray(this string s)
{
return Encoding.UTF8.GetBytes(s);
}
}
}
| mit | C# |
03c5282f4c28f4179d10b2db7b7e636da06bac14 | Remove unused deconstructor | physhi/roslyn,bartdesmet/roslyn,tannergooding/roslyn,sharwell/roslyn,mavasani/roslyn,diryboy/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,AlekseyTs/roslyn,AlekseyTs/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,weltkante/roslyn,mavasani/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,dotnet/roslyn,tmat/roslyn,physhi/roslyn,physhi/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,tannergooding/roslyn,wvdd007/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,bartdesmet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,tmat/roslyn,eriawan/roslyn,KevinRansom/roslyn,bartdesmet/roslyn | src/Features/Core/Portable/InlineHints/TypeHint.cs | src/Features/Core/Portable/InlineHints/TypeHint.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.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
internal class TypeHint
{
public TypeHint(ITypeSymbol type, TextSpan span, bool leadingSpace = false, bool trailingSpace = false)
: this(type, span,
prefix: CreateSpaceSymbolPartArray(leadingSpace),
suffix: CreateSpaceSymbolPartArray(trailingSpace))
{
}
private static ImmutableArray<SymbolDisplayPart> CreateSpaceSymbolPartArray(bool hasSpace)
=> hasSpace
? ImmutableArray.Create(new SymbolDisplayPart(SymbolDisplayPartKind.Space, symbol: null, " "))
: ImmutableArray<SymbolDisplayPart>.Empty;
private TypeHint(ITypeSymbol type, TextSpan span, ImmutableArray<SymbolDisplayPart> prefix, ImmutableArray<SymbolDisplayPart> suffix)
{
Type = type;
Span = span;
Prefix = prefix;
Suffix = suffix;
}
public ITypeSymbol Type { get; }
public TextSpan Span { get; }
public ImmutableArray<SymbolDisplayPart> Prefix { get; }
public ImmutableArray<SymbolDisplayPart> Suffix { get; }
public void Deconstruct(out ITypeSymbol type, out TextSpan span, out ImmutableArray<SymbolDisplayPart> prefix, out ImmutableArray<SymbolDisplayPart> suffix)
{
type = Type;
span = Span;
prefix = Prefix;
suffix = Suffix;
}
}
}
| // 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.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
internal class TypeHint
{
public TypeHint(ITypeSymbol type, TextSpan span, bool leadingSpace = false, bool trailingSpace = false)
: this(type, span,
prefix: CreateSpaceSymbolPartArray(leadingSpace),
suffix: CreateSpaceSymbolPartArray(trailingSpace))
{
}
private static ImmutableArray<SymbolDisplayPart> CreateSpaceSymbolPartArray(bool hasSpace)
=> hasSpace
? ImmutableArray.Create(new SymbolDisplayPart(SymbolDisplayPartKind.Space, symbol: null, " "))
: ImmutableArray<SymbolDisplayPart>.Empty;
private TypeHint(ITypeSymbol type, TextSpan span, ImmutableArray<SymbolDisplayPart> prefix, ImmutableArray<SymbolDisplayPart> suffix)
{
Type = type;
Span = span;
Prefix = prefix;
Suffix = suffix;
}
public ITypeSymbol Type { get; }
public TextSpan Span { get; }
public ImmutableArray<SymbolDisplayPart> Prefix { get; }
public ImmutableArray<SymbolDisplayPart> Suffix { get; }
public void Deconstruct(out ITypeSymbol type, out TextSpan span)
{
type = Type;
span = Span;
}
public void Deconstruct(out ITypeSymbol type, out TextSpan span, out ImmutableArray<SymbolDisplayPart> prefix, out ImmutableArray<SymbolDisplayPart> suffix)
{
type = Type;
span = Span;
prefix = Prefix;
suffix = Suffix;
}
}
}
| mit | C# |
f8632d8c3072de9cc1b13700c0c2d828bfefea3b | Add new exception type | aNutForAJarOfTuna/kafka-net,PKRoma/kafka-net,CenturyLinkCloud/kafka-net,nightkid1027/kafka-net,geffzhang/kafka-net,gigya/KafkaNetClient,BDeus/KafkaNetClient,bridgewell/kafka-net,martijnhoekstra/kafka-net,EranOfer/KafkaNetClient,Jroland/kafka-net | kafka-net/Protocol.cs | kafka-net/Protocol.cs | using System;
namespace KafkaNet
{
public enum ApiKeyRequestType
{
Produce = 0,
Fetch = 1,
Offset = 2,
MetaData = 3,
LeaderAndIsr = 4,
StopReplica = 5,
OffsetCommit = 6,
OffsetFetch = 7
}
public enum ErrorResponseCode
{
NoError = 0,
Unknown = -1,
OffsetOutOfRange = 1,
InvalidMessage = 2,
UnknownTopicOrPartition = 3,
InvalidMessageSize = 4,
LeaderNotAvailable = 5,
NotLeaderForPartition = 6,
RequestTimedOut = 7,
BrokerNotAvailable = 8,
ReplicaNotAvailable = 9,
MessageSizeTooLarge = 10,
StaleControllerEpochCode = 11,
OffsetMetadataTooLargeCode = 12
}
public class FailCrcCheckException : Exception
{
public FailCrcCheckException(string message) : base(message) { }
}
public class ResponseTimeoutException : Exception
{
public ResponseTimeoutException(string message) : base(message) { }
}
public class InvalidPartitionException : Exception
{
public InvalidPartitionException(string message) : base(message) { }
}
public class ServerUnreachableException : Exception
{
public ServerUnreachableException(string message) : base(message) { }
}
public class InvalidTopicMetadataException : Exception
{
public InvalidTopicMetadataException(string message) : base(message) { }
}
}
| using System;
namespace KafkaNet
{
public enum ApiKeyRequestType
{
Produce = 0,
Fetch = 1,
Offset = 2,
MetaData = 3,
LeaderAndIsr = 4,
StopReplica = 5,
OffsetCommit = 6,
OffsetFetch = 7
}
public enum ErrorResponseCode
{
NoError = 0,
Unknown = -1,
OffsetOutOfRange = 1,
InvalidMessage = 2,
UnknownTopicOrPartition = 3,
InvalidMessageSize = 4,
LeaderNotAvailable = 5,
NotLeaderForPartition = 6,
RequestTimedOut = 7,
BrokerNotAvailable = 8,
ReplicaNotAvailable = 9,
MessageSizeTooLarge = 10,
StaleControllerEpochCode = 11,
OffsetMetadataTooLargeCode = 12
}
public class FailCrcCheckException : Exception
{
public FailCrcCheckException(string message) : base(message) { }
}
public class ResponseTimeoutException : Exception
{
public ResponseTimeoutException(string message) : base(message) { }
}
public class InvalidPartitionException : Exception
{
public InvalidPartitionException(string message) : base(message) { }
}
public class ServerUnreachableException : Exception
{
public ServerUnreachableException(string message) : base(message) { }
}
}
| apache-2.0 | C# |
428a09be874e01d80c007a631491797ad7c8cff5 | Create GetBCPHighScoreNotification.cs | missionpinball/unity-bcp-server | Assets/BCP/Scripts/PlayMaker/GetBCPHighScoreNotification.cs | Assets/BCP/Scripts/PlayMaker/GetBCPHighScoreNotification.cs | using UnityEngine;
using System;
using HutongGames.PlayMaker;
using TooltipAttribute = HutongGames.PlayMaker.TooltipAttribute;
/// <summary>
/// Custom PlayMaker action for MPF that sends an Event when a high_score_enter_initials BCP Trigger
/// command is received.
/// </summary>
[ActionCategory("BCP")]
[Tooltip("Sends an Event when the special BCP Trigger high_score_enter_initials command is received.")]
public class GetBCPHighScoreNotification: FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The variable to receive the award label value")]
public FsmString award;
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The variable to receive the player number")]
public FsmInt player;
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The variable to receive the high score value")]
public FsmInt value;
[UIHint(UIHint.Variable)]
[Tooltip("The PlayMaker event to send when the high_score_enter_initials BCP Trigger is received")]
public FsmEvent sendEvent;
private bool registered;
/// <summary>
/// Resets this instance to default values.
/// </summary>
public override void Reset()
{
base.Reset();
award = null;
player = null;
value = null;
sendEvent = null;
registered = false;
}
/// <summary>
/// Called when the state becomes active. Adds the MPF BCP Trigger event handler.
/// </summary>
public override void OnEnter()
{
base.OnEnter();
// Auto-register the trigger name with the pin controller (if necessary)
if (!registered)
{
BcpServer.Instance.Send(BcpMessage.RegisterTriggerMessage("high_score_enter_initials"));
registered = true;
}
BcpMessageController.OnTrigger += Trigger;
}
/// <summary>
/// Called before leaving the current state. Removes the MPF BCP Trigger event handler.
/// </summary>
public override void OnExit()
{
BcpMessageController.OnTrigger -= Trigger;
base.OnExit();
}
/// <summary>
/// Event handler called when a trigger message is received from MPF.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="TriggerMessageEventArgs"/> instance containing the event data.</param>
public void Trigger(object sender, TriggerMessageEventArgs e)
{
// Determine if this trigger message is the one we are interested in. If so, send specified FSM event.
if (e.Name == "high_score_enter_initials")
{
try
{
award = e.BcpMessage.Parameters["award"].Value;
player = e.BcpMessage.Parameters["player_num"].AsInt;
value = e.BcpMessage.Parameters["value"].AsInt;
Fsm.Event(sendEvent);
}
catch (Exception ex)
{
BcpServer.Instance.Send(BcpMessage.ErrorMessage("An error occurred while processing a 'high_score_enter_initials' trigger message: " + ex.Message, e.BcpMessage.RawMessage));
}
}
}
}
| mit | C# | |
011ca99ee6ee449b90b5f041b18639edfc9ce760 | Add Nuget Reference | monoman/NugetCracker,monoman/NugetCracker | NugetCracker/Components/NugetReference.cs | NugetCracker/Components/NugetReference.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NugetCracker.Interfaces;
using System.Text.RegularExpressions;
namespace NugetCracker.Components
{
public class NugetReference : IComponent
{
public NugetReference(string name, string versions)
{
Name = name;
Versions = versions;
}
public string Versions { get; protected set; }
public string Name { get; protected set; }
public string Description { get; private set; }
public Version CurrentVersion { get; private set; }
public string FullPath { get; private set; }
public IQueryable<IComponent> Dependencies
{
get { return null; }
}
public bool MatchName(string pattern)
{
return string.IsNullOrWhiteSpace(pattern) || Regex.IsMatch(Name, pattern,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
}
public string ToLongString()
{
return ToString();
}
public override string ToString()
{
return string.Format("Nuget Reference: {0} {1}", Name, Versions);
}
public bool Equals(IComponent other)
{
return IsEqual(other);
}
private bool IsEqual(IComponent other)
{
return other != null && Name == other.Name;
}
public override bool Equals(object obj)
{
return IsEqual(obj as IComponent);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}
| apache-2.0 | C# | |
90b5101b8ccd284cd340e99b44a95f04c3c0d4bc | Create HUD.cs | ryskulova/UnityGame | HUD.cs | HUD.cs | using UnityEngine;
using System.Collections;
public class HUD : MonoBehaviour {
public GameObject Player1;
public GameObject Player2;
public BoxCollider2D topWall;
public BoxCollider2D bottomWall;
public BoxCollider2D leftWall;
public BoxCollider2D rightWall;
}
| mit | C# | |
cbeaa458968a6e6c528b273228bbbb9713679295 | Add test (#1879) | oxwanawxo/Newtonsoft.Json,jkorell/Newtonsoft.Json,JamesNK/Newtonsoft.Json,bfriesen/Newtonsoft.Json,PKRoma/Newtonsoft.Json,ze-pequeno/Newtonsoft.Json,brjohnstmsft/Newtonsoft.Json,TylerBrinkley/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Issues/Issue1877.cs | Src/Newtonsoft.Json.Tests/Issues/Issue1877.cs | #region License
// Copyright (c) 2007 James Newton-King
//
// 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 Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests.Issues
{
[TestFixture]
public class Issue1877
{
[Test]
public void Test()
{
var f2 = new Fubar2();
f2.Version = new Version("3.0");
(f2 as Fubar).Version = new Version("4.0");
var s = JsonConvert.SerializeObject(f2, new JsonSerializerSettings
{
Converters = { new VersionConverter() }
});
Assert.AreEqual(@"{""Version"":""4.0""}", s);
var f3 = JsonConvert.DeserializeObject<Fubar2>(s, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace,
Converters = { new VersionConverter() }
});
Assert.AreEqual(2, f3.Version.Major);
Assert.AreEqual(4, (f3 as Fubar).Version.Major);
}
class Fubar
{
public Version Version { get; set; } = new Version("1.0");
// ...
}
private class Fubar2 : Fubar
{
[JsonIgnore]
public new Version Version { get; set; } = new Version("2.0");
// ...
}
}
}
| mit | C# | |
0e5df3783eeae7ba25ee926601a94fa21317d113 | Create SceneSwitcherWindow.cs | UnityCommunity/UnityLibrary | Assets/Scripts/Editor/Tools/SceneSwitcherWindow.cs | Assets/Scripts/Editor/Tools/SceneSwitcherWindow.cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using UnityEditor.SceneManagement;
public class SceneSwitcherWindow : EditorWindow
{
public enum ScenesSource
{
Assets,
BuildSettings
}
protected Vector2 scrollPosition;
protected ScenesSource scenesSource = ScenesSource.Assets;
protected OpenSceneMode openSceneMode = OpenSceneMode.Single;
[MenuItem ( "Tools/Scene Switcher" )]
public static void Init ()
{
var window = EditorWindow.GetWindow<SceneSwitcherWindow> ( "Scene Switcher" );
window.Show ();
}
protected virtual void OnGUI ()
{
List<EditorBuildSettingsScene> buildScenes = new List<EditorBuildSettingsScene> ( EditorBuildSettings.scenes );
this.scenesSource = ( ScenesSource )EditorGUILayout.EnumPopup ( "Scenes Source", this.scenesSource );
this.openSceneMode = ( OpenSceneMode )EditorGUILayout.EnumPopup ( "Open Scene Mode", this.openSceneMode );
GUILayout.Label ( "Scenes", EditorStyles.boldLabel );
string [] guids = AssetDatabase.FindAssets ( "t:Scene" );
this.scrollPosition = EditorGUILayout.BeginScrollView ( this.scrollPosition );
EditorGUILayout.BeginVertical ();
for ( int i = 0; i < guids.Length; i++ )
{
string path = AssetDatabase.GUIDToAssetPath ( guids [ i ] );
SceneAsset sceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset> ( path );
EditorBuildSettingsScene buildScene = buildScenes.Find ( (editorBuildScene ) =>
{
return editorBuildScene.path == path;
} );
Scene scene = SceneManager.GetSceneByPath ( path );
bool isOpen = scene.IsValid () && scene.isLoaded;
GUI.enabled = !isOpen;
if ( this.scenesSource == ScenesSource.Assets )
{
if ( GUILayout.Button ( sceneAsset.name ) )
{
Open ( path );
}
}
else
{
if ( buildScene != null )
{
if ( GUILayout.Button ( sceneAsset.name ) )
{
Open ( path );
}
}
}
GUI.enabled = true;
}
if ( GUILayout.Button ( "Create New Scene" ) )
{
Scene newScene = EditorSceneManager.NewScene ( NewSceneSetup.DefaultGameObjects, NewSceneMode.Single );
EditorSceneManager.SaveScene ( newScene );
}
EditorGUILayout.EndVertical ();
EditorGUILayout.EndScrollView ();
}
public virtual void Open ( string path )
{
if ( EditorSceneManager.EnsureUntitledSceneHasBeenSaved ( "You don't have saved the Untitled Scene, Do you want to leave?" ) )
{
EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo ();
EditorSceneManager.OpenScene ( path, this.openSceneMode );
}
}
}
| mit | C# | |
adb69df4efc0ddc92e46c058b4ee129050aa1b57 | fix warning CS0162: Unreachable code detected in Log.cs | wenyanw/FakeItEasy,wenyanw/FakeItEasy,adamralph/FakeItEasy,FakeItEasy/FakeItEasy,blairconrad/FakeItEasy,FakeItEasy/FakeItEasy,khellang/FakeItEasy,adamralph/FakeItEasy,robvanschelven/FakeItEasy,jamiehumphries/FakeItEasy,thomaslevesque/FakeItEasy,CedarLogic/FakeItEasy,robvanschelven/FakeItEasy,CedarLogic/FakeItEasy,jamiehumphries/FakeItEasy,blairconrad/FakeItEasy,thomaslevesque/FakeItEasy,khellang/FakeItEasy | Source/FakeItEasy/Log.cs | Source/FakeItEasy/Log.cs | namespace FakeItEasy
{
using System;
using System.Diagnostics.CodeAnalysis;
internal static class Log
{
static Log()
{
UseLogging = false;
}
private static bool UseLogging { get; set; }
public static Logger GetLogger<T>()
{
if (UseLogging)
{
return new ConsoleLogger(typeof(T).ToString());
}
else
{
return NullLogger.Instance;
}
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Can be instantiated at will.")]
private class ConsoleLogger
: Logger
{
private readonly string name;
public ConsoleLogger(string name)
{
this.name = name;
}
public override void Debug(Func<string> message)
{
Console.WriteLine("Log: {0}\r\n\t {1}".FormatInvariant(this.name, message.Invoke()));
}
}
private class NullLogger
: Logger
{
public static readonly NullLogger Instance = new NullLogger();
private NullLogger()
{
}
public override void Debug(Func<string> message)
{
// Do nothing
}
}
}
} | namespace FakeItEasy
{
using System;
using System.Diagnostics.CodeAnalysis;
internal static class Log
{
#if DEBUG
private const bool UseLogging = false;
#else
private const bool UseLogging = false;
#endif
public static Logger GetLogger<T>()
{
if (UseLogging)
{
return new ConsoleLogger(typeof(T).ToString());
}
else
{
return NullLogger.Instance;
}
}
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Can be instanticated at will.")]
private class ConsoleLogger
: Logger
{
private readonly string name;
public ConsoleLogger(string name)
{
this.name = name;
}
public override void Debug(Func<string> message)
{
Console.WriteLine("Log: {0}\r\n\t {1}".FormatInvariant(this.name, message.Invoke()));
}
}
private class NullLogger
: Logger
{
public static readonly NullLogger Instance = new NullLogger();
private NullLogger()
{
}
public override void Debug(Func<string> message)
{
// Do nothing
}
}
}
} | mit | C# |
363a237d2d1053a6a17fb4e04877e128d61e3222 | Create IProtocol.cs | poostwoud/discovery | src/Protocol/IProtocol.cs | src/Protocol/IProtocol.cs | public interface IProtocol
{
void Append();
void Partial();
string Read(Uri uri, string userName = "", string password = "");
void Remove();
void Replace();
}
| mit | C# | |
231f08f6669073a341bc3e9fdf4c86bdcae340a0 | Add ImageValueConverter. | cube-soft/Cube.Core,cube-soft/Cube.Core | Converters/ImageValueConverter.cs | Converters/ImageValueConverter.cs | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.IO;
using System.Windows.Media.Imaging;
namespace Cube.Xui.Converters
{
/* --------------------------------------------------------------------- */
///
/// ImageConversions
///
/// <summary>
/// BitmapImage オブジェクト関連する拡張用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
public static class ImageOperations
{
/* ----------------------------------------------------------------- */
///
/// ToBitmapImage
///
/// <summary>
/// System.Drawing.Image オブジェクトから BitmapImage オブジェクトに
/// 変換します。
/// </summary>
///
/* ----------------------------------------------------------------- */
public static BitmapImage ToBitmapImage(this System.Drawing.Image src)
{
if (src == null) return default(BitmapImage);
using (var ss = new MemoryStream())
{
src.Save(ss, System.Drawing.Imaging.ImageFormat.Png);
var dest = new BitmapImage();
dest.BeginInit();
dest.CacheOption = BitmapCacheOption.OnLoad;
dest.StreamSource = new MemoryStream(ss.ToArray());
dest.EndInit();
if (dest.CanFreeze) dest.Freeze();
return dest;
}
}
}
/* --------------------------------------------------------------------- */
///
/// ImageValueConverter
///
/// <summary>
/// System.Drawing.Image オブジェクトから BitmapImage オブジェクトに
/// 変換するためのクラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
public class ImageValueConverter : OneWayValueConverter
{
/* ----------------------------------------------------------------- */
///
/// ImageValueConverter
///
/// <summary>
/// オブジェクトを初期化します。
/// </summary>
///
/* ----------------------------------------------------------------- */
public ImageValueConverter() : base(e =>
{
var src = e is System.Drawing.Image image ? image :
e is System.Drawing.Icon icon ? icon.ToBitmap() :
null;
return src.ToBitmapImage();
}) { }
}
}
| apache-2.0 | C# | |
e5260f5758c53df202e44d3aaca5ec4724c838d6 | Fix warnings in unit tests flagged by MSBuild Log | github/VisualStudio,github/VisualStudio,github/VisualStudio | test/GitHub.Exports.UnitTests/GlobalSuppressions.cs | test/GitHub.Exports.UnitTests/GlobalSuppressions.cs |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Unit test names can contain a _")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "Nested unit test classes should be visible", Scope = "type")]
| mit | C# | |
cc7d4598664b8119a820406722962f9f03f5332b | Add a button press example | DuFF14/OSVR-Unity,grobm/OSVR-Unity,grobm/OSVR-Unity,JeroMiya/OSVR-Unity,OSVR/OSVR-Unity | OSVR-Unity/Assets/scripts/HandleButtonPress.cs | OSVR-Unity/Assets/scripts/HandleButtonPress.cs | using UnityEngine;
using System.Collections;
public class HandleButtonPress : MonoBehaviour {
public OSVR.Unity.OSVRClientKit clientKit;
public OSVR.Unity.InterfaceCallbacks cb;
public void Start() {
GetComponent<OSVR.Unity.InterfaceCallbacks> ().RegisterCallback (handleButton);
}
public void handleButton(string path, bool state) {
Debug.Log ("Got button: " + path + " state is " + state);
}
}
| apache-2.0 | C# | |
c662e718aef36d5e50194c39e291a2bce1bc0c87 | Test fix | MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS | src/R/Components/Test/Script/InstallPackagesTest.cs | src/R/Components/Test/Script/InstallPackagesTest.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.Common.Core.Install;
using Microsoft.Common.Core.Test.Install;
using Microsoft.R.Components.Script;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Components.Test.Script {
[ExcludeFromCodeCoverage]
[Collection(CollectionNames.NonParallel)]
public class InstallPackagesTest
{
[Test]
[Category.R.Package]
public void InstallPackages_BaseTest()
{
var svl =new SupportedRVersionList(3, 2, 3, 2);
RInstallData data = RInstallation.GetInstallationData(string.Empty, svl);
data.Status.Should().Be(RInstallStatus.OK);
bool result = InstallPackages.IsInstalled("base", Int32.MaxValue, data.Path);
result.Should().BeTrue();
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.Common.Core.Install;
using Microsoft.Common.Core.Test.Install;
using Microsoft.R.Components.Script;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.R.Components.Test.Script {
[ExcludeFromCodeCoverage]
[Collection(CollectionNames.NonParallel)]
public class InstallPackagesTest
{
[Test]
[Category.R.Package]
public void InstallPackages_BaseTest()
{
var svl = RInstallationTest.MakeSupportedVersions(3, 2, 3, 2);
RInstallData data = RInstallation.GetInstallationData(string.Empty, svl);
data.Status.Should().Be(RInstallStatus.OK);
bool result = InstallPackages.IsInstalled("base", Int32.MaxValue, data.Path);
result.Should().BeTrue();
}
}
}
| mit | C# |
405069dd9830c115bc4fe043a180b67e8370c066 | Add SGD | kawatan/Milk | Megalopolis/Optimizers/SGD.cs | Megalopolis/Optimizers/SGD.cs | using System;
namespace Megalopolis.Optimizers
{
public class SGD
{
public double lr = 0.001; // Learning rate
public SGD() { }
public SGD(double lr)
{
this.lr = lr;
}
public double Optimize(int index, double weight, double gradient)
{
return weight - this.lr * gradient;
}
}
}
| apache-2.0 | C# | |
6dff62e0d09feae2e3d9bb9d29319f1aa4db5390 | Create C#.cs | TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets,TobitSoftware/chayns-snippets | Backend/EmailToGroup/C#.cs | Backend/EmailToGroup/C#.cs | import RestSharp;
public class MailDto
{
public string Headline { get; set; }
public string Text { get; set; }
public string Greeting { get; set; }
public string Subject { get; set; }
public List<int> UacIds { get; set; }
public List<int> UserIds { get; set; }
}
public string Server = "https://api.chayns.net/v2.0/";
private const string Secret = "Your Tapp Secret";
public IHttpActionResult post(int locationId, int tappId, [FromBody]MailDto body)
{
try
{
RestClient restClient = new RestClient(Server);
RestRequest req = new RestRequest(locationId + "/Email");
req.Method = Method.POST;
req.AddHeader("Content-Type", "application/json");
req.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToString(tappId) + ":" + Secret)));
req.RequestFormat = DataFormat.Json;
req.AddBody(body);
IRestResponse resp = restClient.Execute(req);
if (resp.StatusCode == HttpStatusCode.OK)
{
return Ok(JObject.Parse(resp.Content));
}
else
{
return Conflict();
}
}
catch (Exception e)
{
return InternalServerError(e);
}
}
| mit | C# | |
c575a259142ffb4424433658c35ee2d041c40594 | Create simple-targets.csx | adamralph/simple-targets-csx | simple-targets.csx | simple-targets.csx | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Target
{
private string[] inputs = new string[0];
private string[] outputs = new string[0];
private string[] dependOn = new string[0];
public string[] Inputs
{
get { return this.inputs; }
set { this.inputs = value ?? new string[0]; }
}
public string[] Outputs
{
get { return this.outputs; }
set { this.outputs = value ?? new string[0]; }
}
public string[] DependOn
{
get { return this.dependOn; }
set { this.dependOn = value ?? new string[0]; }
}
public Action Do { get; set; }
}
public static void Run(IList<string> args, IDictionary<string, Target> targets)
{
foreach (var option in args.Where(arg => arg.StartsWith("-", StringComparison.Ordinal)))
{
switch (option)
{
case "-H":
case "-h":
case "-?":
Console.WriteLine("Usage: <script-runner> build.csx [<options>] [<targets>]");
Console.WriteLine();
Console.WriteLine("script-runner: A C# script runner. E.g. csi.exe.");
Console.WriteLine();
Console.WriteLine("options:");
Console.WriteLine(" -T Display the targets, then exit");
Console.WriteLine();
Console.WriteLine("targets: A list of targets to run. If not specified, 'default' target will be run.");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" csi.exe build.csx");
Console.WriteLine(" csi.exe build.csx -T");
Console.WriteLine(" csi.exe build.csx test package");
return;
case "-T":
foreach (var target in targets)
{
Console.WriteLine(target.Key);
}
return;
default:
Console.WriteLine($"Unknown option '{option}'.");
return;
}
}
var targetNames = args.Where(arg => !arg.StartsWith("-", StringComparison.Ordinal)).ToList();
if (!targetNames.Any())
{
targetNames.Add("default");
}
var targetsRan = new HashSet<string>();
foreach (var name in targetNames)
{
RunTarget(name, targets, targetsRan);
}
Console.WriteLine(
$"Target{(targetNames.Count > 1 ? "s" : "")} {string.Join(", ", targetNames.Select(name => $"'{name}'"))} succeeded.");
}
public static void RunTarget(string name, IDictionary<string, Target> targets, ISet<string> targetsRan)
{
Target target;
if (!targets.TryGetValue(name, out target))
{
throw new InvalidOperationException($"Target '{name}' not found.");
}
targetsRan.Add(name);
var outputs = target.Outputs ?? Enumerable.Empty<string>();
if (outputs.Any() && !outputs.Any(output => !File.Exists(output)))
{
Console.WriteLine($"Skipping target '{name}' since all outputs are present.");
return;
}
foreach (var dependency in target.DependOn
.Concat(targets.Where(t => t.Value.Outputs.Intersect(target.Inputs).Any()).Select(t => t.Key))
.Except(targetsRan))
{
RunTarget(dependency, targets, targetsRan);
}
if (target.Do != null)
{
Console.WriteLine($"Running target '{name}'...");
try
{
target.Do.Invoke();
}
catch (Exception)
{
Console.WriteLine($"Target '{name}' failed!");
throw;
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.