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 |
|---|---|---|---|---|---|---|---|---|
56ec14ee580b507b3cf4f84e3acb598082c8ec85 | add MyAudioSource | tatmos/MyAudioSource | MyAudioSource.cs | MyAudioSource.cs | using UnityEngine;
using System.Collections;
#if UNITY_WEBPLAYER
public class MyAudioSource : MonoBehaviour
{
private AudioSource _Mysource;
public AudioSource source
{
get
{
return _Mysource;
}
}
public void Awake()
{
if(_Mysource == null){
_Mysource = gameObject.AddComponent<AudioSource>();
source.rolloffMode = AudioRolloffMode.Linear; //3Dポジション時に音が小さくなるのを軽減
}
}
#else
public class MyAudioSource : CriAtomSource
{
public CriAtomSource source {
get
{
return this;
}
}
public AudioClip clip{
set
{
this.cueName = value.name;
}
}
public bool isPlaying
{
get
{
if(this.status == Status.Playing)return true;
return false;
}
}
public float timeSamples
{
get
{
return this.time / 44100.0f;
}
}
#endif
} | mit | C# | |
24ad42e9de09159491dd2f53c574759a7463dad9 | Create Timer.cs | UnityCommunity/UnityLibrary | Scripts/Helpers/Debug/Timer.cs | Scripts/Helpers/Debug/Timer.cs | // Timer: get time elapsed in milliseconds
using UnityEngine;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
namespace UnityLibrary
{
public class Timer : MonoBehaviour
{
void Start()
{
// init and start timer
var stopwatch = new Stopwatch();
stopwatch.Start();
// put your function here..
for (int i = 0; i < 1000000; i++)
{
var tmp = "asdf" + 1.ToString();
}
// get results in ms
stopwatch.Stop();
Debug.LogFormat("Timer: {0} ms", stopwatch.ElapsedMilliseconds);
stopwatch.Reset();
}
}
}
| mit | C# | |
7dfac2fd787f081986f7e9865323dcd85a0ef60a | Add assembly info for new project | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.Owin.Security.Cookies.Interop/Properties/AssemblyInfo.cs | src/Microsoft.Owin.Security.Cookies.Interop/Properties/AssemblyInfo.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")] | apache-2.0 | C# | |
4357f43d1b36cab47d44a78d9d9a14bbabfdd978 | Revert "Fix AssemblyVersion to 3.0.0.1" | EzyWebwerkstaden/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,nimore/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,n2cms/n2cms,nimore/n2cms,nicklv/n2cms,DejanMilicic/n2cms,nicklv/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,nicklv/n2cms,bussemac/n2cms,bussemac/n2cms,bussemac/n2cms,DejanMilicic/n2cms,EzyWebwerkstaden/n2cms,nicklv/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,bussemac/n2cms,nimore/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,nicklv/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,n2cms/n2cms,nimore/n2cms | src/Framework/AssemblyVersion.cs | src/Framework/AssemblyVersion.cs | using System.Reflection;
// Version information for an assembly consists of the following four values: You can specify all the values or you can default the Revision and Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("3.0")]
[assembly: AssemblyFileVersion("3.0.0.1-beta")]
| using System.Reflection;
// Version information for an assembly consists of the following four values: You can specify all the values or you can default the Revision and Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("3.0")]
[assembly: AssemblyFileVersion("3.0.0.1")]
| lgpl-2.1 | C# |
a27dd1caede68db2ac0c04c70260e232ad1e288a | Create TT2PrestigeStage.cs | cwesnow/Net_Fiddle | 2017Dec/TT2PrestigeStage.cs | 2017Dec/TT2PrestigeStage.cs | // https://www.reddit.com/r/TapTitans2/comments/7jbvzg/flipping_a_formula_in_excel/
// Formula posted by: CFMcGhee
// Author: cwesnow - CrimsonWolfSage
using System;
public class Program
{
public static void Main()
{
// Input Book of Shadows
int BookOfShadows = 750;
// Input Desired Relics
int DesiredRelics = 1000000000;
Console.WriteLine(
"Prestige at Stage: {0} for {1} relics.",
CalculateStage(DesiredRelics, BookOfShadows),
DesiredRelics);
}
static int CalculateStage(int Relics, int Book){
double P = doB(Book);
for(int x = 100; x < 9999;x++) {
double B = Math.Pow(x,.48);
double C = Math.Pow(1.21,B);
double G = Math.Pow(x, 1.1) * 0.0000005+1;
double I = Math.Pow(x, 1.005 * G);
double J = Math.Pow(1.002, I);
double K = (3*C) + (1.5 * (x-110)) + J;
if( K*P > Relics ) return x;
}
return 1;
}
static double doB(int Book){
double answer = 1.5*(.0001 * Book);
answer = Math.Pow((1+answer), .5);
return 1 + 0.05 * Math.Pow(Book, answer);
}
static int Floor(decimal x) { return (int)x; }
}
| mit | C# | |
7321ced9fde3d3d5e7d7bbfa7c53b2b9aab558cd | Test cases for ISteamNews interface | ShaneC/SteamSharp | SteamSharp.TestFramework/ISteamNews.cs | SteamSharp.TestFramework/ISteamNews.cs | using System;
using Xunit;
using SteamSharp;
using System.Net;
namespace SteamSharp.TestFramework {
public class ISteamNews {
[Fact]
public void GET_GetNewsForApp_ByUri() {
SteamClient client = new SteamClient();
SteamRequest request = new SteamRequest( "ISteamNews/GetNewsForApp/v0002/" );
request.AddParameter( "appid", 440 );
request.AddParameter( "count", 2 );
request.AddParameter( "maxlength", 100 );
var response = client.Execute( request );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.NotNull( response.Content );
}
[Fact]
public void GET_GetNewsForApp_ByEnums() {
SteamClient client = new SteamClient();
SteamRequest request = new SteamRequest( SteamInterface.ISteamNews, "GetNewsForApp", SteamMethodVersion.v0002 );
request.AddParameter( "appid", 440 );
request.AddParameter( "count", 2 );
request.AddParameter( "maxlength", 100 );
var response = client.Execute( request );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.NotNull( response.Content );
}
[Fact]
public void GET_GetNewsForApp_ByClass() {
var response = SteamNews.GetNewsForApp( 440, 2, 100 );
Assert.Equal( HttpStatusCode.OK, response.StatusCode );
Assert.NotNull( response.Content );
}
[Fact]
public void GET_GetNewsForApp_NoValues() {
SteamClient client = new SteamClient();
SteamRequest request = new SteamRequest( "ISteamNews/GetNewsForApp/v0002/" );
var response = client.Execute( request );
Assert.Equal( HttpStatusCode.BadRequest, response.StatusCode );
}
}
}
| apache-2.0 | C# | |
23d7487bbc09bbe0444dfbd8a9171a31a9525912 | add test for b2_list_buckets | NebulousConcept/b2-csharp-client | b2-csharp-client-test/B2.Client/Apis/ListBucketsV1/TestListBucketsV1.cs | b2-csharp-client-test/B2.Client/Apis/ListBucketsV1/TestListBucketsV1.cs | using System;
using System.Threading.Tasks;
using B2.Client.Apis.AuthorizeAccountV1;
using B2.Client.Apis.ListBucketsV1;
using B2.Client.Rest;
using NUnit.Framework;
namespace B2.Client.Test.Apis.ListBucketsV1
{
[TestFixture]
public class TestListBucketsV1
{
[Test]
public async Task TestListBucketsV1Success()
{
var client = new UnauthenticatedB2Client(new Uri(TestEnvironment.B2ApiUrl));
var req = new AuthorizeAccountV1Request(TestEnvironment.GetTestAccountId(), TestEnvironment.GetTestAccountKey());
var authedClient = client.AuthenticateWithResponse(
await client.PerformAuthenticationRequestAsync(new AuthorizeAccountV1Api(), req));
var result = await authedClient.PerformApiRequestAsync(new ListBucketsV1Api(),
new ListBucketsV1Request(TestEnvironment.GetTestAccountId()));
Assert.That(result.Buckets, Is.Not.Null);
}
}
} | mit | C# | |
267b7d812c35d8a4fe48212bda8200c6e5c7287f | Add Region property to MatchReference (#314) | Challengermode/RiotSharp,Oucema90/RiotSharp,frederickrogan/RiotSharp,BenFradet/RiotSharp,Shidesu/RiotSharp,florinciubotariu/RiotSharp,oisindoherty/RiotSharp,JanOuborny/RiotSharp,jono-90/RiotSharp | RiotSharp/MatchEndpoint/MatchReference.cs | RiotSharp/MatchEndpoint/MatchReference.cs | using Newtonsoft.Json;
using RiotSharp.MatchEndpoint.Enums;
using System;
namespace RiotSharp.MatchEndpoint
{
public class MatchReference
{
/// <summary>
/// The ID of the champion played during the match.
/// </summary>
[JsonProperty("champion")]
public long ChampionID { get; set; }
/// <summary>
/// Participant's lane.
/// </summary>
[JsonProperty("lane")]
public Lane Lane { get; set; }
/// <summary>
/// The match ID relating to the match.
/// </summary>
[JsonProperty("matchId")]
public long MatchID { get; set; }
/// <summary>
/// The ID of the platform on which the game is being played
/// </summary>
[JsonProperty("platformId")]
public string PlatformID { get; set; }
/// <summary>
/// Match queue type.
/// </summary>
[JsonProperty("queue")]
public Queue Queue { get; set; }
/// <summary>
/// The region match was played in.
/// </summary>
[JsonProperty("region")]
public Region Region { get; set; }
/// <summary>
/// Participant's role.
/// </summary>
[JsonProperty("role")]
public Role Role { get; set; }
/// <summary>
/// Season match was played.
/// </summary>
[JsonProperty("season")]
public Season Season { get; set; }
/// <summary>
/// The date/time of which the game lobby was created.
/// </summary>
[JsonProperty("timestamp")]
[JsonConverter(typeof(DateTimeConverterFromLong))]
public DateTime Timestamp { get; set; }
}
}
| using Newtonsoft.Json;
using RiotSharp.MatchEndpoint.Enums;
using System;
namespace RiotSharp.MatchEndpoint
{
public class MatchReference
{
/// <summary>
/// The ID of the champion played during the match.
/// </summary>
[JsonProperty("champion")]
public long ChampionID { get; set; }
/// <summary>
/// Participant's lane.
/// </summary>
[JsonProperty("lane")]
public Lane Lane { get; set; }
/// <summary>
/// The match ID relating to the match.
/// </summary>
[JsonProperty("matchId")]
public long MatchID { get; set; }
/// <summary>
/// The ID of the platform on which the game is being played
/// </summary>
[JsonProperty("platformId")]
public string PlatformID { get; set; }
/// <summary>
/// Match queue type.
/// </summary>
[JsonProperty("queue")]
public Queue Queue { get; set; }
/// <summary>
/// Participant's role.
/// </summary>
[JsonProperty("role")]
public Role Role { get; set; }
/// <summary>
/// Season match was played.
/// </summary>
[JsonProperty("season")]
public Season Season { get; set; }
/// <summary>
/// The date/time of which the game lobby was created.
/// </summary>
[JsonProperty("timestamp")]
[JsonConverter(typeof(DateTimeConverterFromLong))]
public DateTime Timestamp { get; set; }
}
}
| mit | C# |
cf0015ede96fb94b4dad7ad0b3ec813e816cc40f | add zone for UnitTesing subsystem (#1212) | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Rider/UnitTesting/IUnityUnitTestingZone.cs | resharper/resharper-unity/src/Rider/UnitTesting/IUnityUnitTestingZone.cs | using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.UnitTestFramework;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.UnitTesting
{
[ZoneDefinition]
[ZoneDefinitionConfigurableFeature("Exploration for UnityTests", "Support for [UnityTest] tests", false)]
public interface IUnityUnitTestingZone : IZone, IRequire<IUnitTestingZone>
{
}
} | apache-2.0 | C# | |
d46d27e91f876b706e1fcbfb5061e186df5e9f25 | Add converter | mstrother/BmpListener | src/BmpListener/Serialization/Converters/PathAttributeOriginConverter.cs | src/BmpListener/Serialization/Converters/PathAttributeOriginConverter.cs | using System;
using BmpListener.Bgp;
using Newtonsoft.Json;
namespace BmpListener.Serialization.Converters
{
public class PathAttributeOriginConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(PathAttributeOrigin);
}
public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
var origin = (PathAttributeOrigin)value;
switch (origin.Origin)
{
case PathAttributeOrigin.Type.IGP:
writer.WriteValue("igp");
break;
case PathAttributeOrigin.Type.EGP:
writer.WriteValue("egp");
break;
case PathAttributeOrigin.Type.Incomplete:
writer.WriteValue("incomplete");
break;
default:
writer.WriteValue("incomplete");
break;
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
| mit | C# | |
08e1904a7e271e01eb6d7cd44ccbd0eea19eb67c | fix deserialisation in the case where the status is Ok but the empty response object is missing | luiseduardohdbackup/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Wrapper.Unit.Tests/Deserialisation/User/Payment/DeleteCardTests.cs | src/SevenDigital.Api.Wrapper.Unit.Tests/Deserialisation/User/Payment/DeleteCardTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using NUnit.Framework;
using SevenDigital.Api.Schema.Payment;
using SevenDigital.Api.Schema.User.Payment;
using SevenDigital.Api.Wrapper.Utility.Http;
using SevenDigital.Api.Wrapper.Utility.Serialization;
namespace SevenDigital.Api.Wrapper.Unit.Tests.Deserialisation.User.Payment
{
[TestFixture]
public class DeleteCardTests
{
[Test]
public void Can_Deserialise_ok_response_without_body__as_DeleteCard()
{
const string ResponseXml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response status=\"ok\" version=\"1.2\" />";
var response = new Response
{
StatusCode = HttpStatusCode.OK,
Body = ResponseXml
};
var xmlSerializer = new ResponseDeserializer<DeleteCard>();
var result = xmlSerializer.Deserialize(response);
Assert.That(result, Is.Not.Null);
}
}
}
| mit | C# | |
5dd84eba221696e43d156c31fec7bdbe895ea409 | add cs temp | punkieL/proCom,candywater/ProCon,candywater/ProCon,punkieL/proCom,candywater/ProCon,candywater/ProCon,candywater/ProCon,punkieL/proCom,candywater/ProCon,candywater/ProCon,candywater/ProCon,candywater/ProCon | _template/cs.cs | _template/cs.cs | using System.Collections;
using System.Collections.Generic;
using System;
static void Main()
{
} | mit | C# | |
ddc25b3cf11b0f1e505109008e1a48c80ac81d72 | Add TestServiceCollectionExtensions | tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server | tests/Tgstation.Server.Host.Tests/Core/TestServiceCollectionExtensions.cs | tests/Tgstation.Server.Host.Tests/Core/TestServiceCollectionExtensions.cs | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
namespace Tgstation.Server.Host.Core.Tests
{
[TestClass]
public sealed class TestServiceCollectionExtensions
{
class GoodConfig
{
public const string Section = "asdf";
}
class BadConfig1
{
const string Section = "asdf";
}
class BadConfig2
{
public const bool Section = false;
}
class BadConfig3
{
//nah
}
[TestMethod]
public void TestUseStandardConfig()
{
var serviceCollection = new ServiceCollection();
var mockConfig = new Mock<IConfigurationSection>();
mockConfig.Setup(x => x.GetSection(It.IsNotNull<string>())).Returns(mockConfig.Object).Verifiable();
Assert.ThrowsException<ArgumentNullException>(() => ServiceCollectionExtensions.UseStandardConfig<GoodConfig>(null, null));
Assert.ThrowsException<ArgumentNullException>(() => serviceCollection.UseStandardConfig<GoodConfig>(null));
serviceCollection.UseStandardConfig<GoodConfig>(mockConfig.Object);
Assert.ThrowsException<InvalidOperationException>(() => serviceCollection.UseStandardConfig<BadConfig1>(mockConfig.Object));
Assert.ThrowsException<InvalidOperationException>(() => serviceCollection.UseStandardConfig<BadConfig2>(mockConfig.Object));
Assert.ThrowsException<InvalidOperationException>(() => serviceCollection.UseStandardConfig<BadConfig3>(mockConfig.Object));
mockConfig.Verify();
}
}
}
| agpl-3.0 | C# | |
85c7e8f5eba5505f236e0ab9f08e1dad0a6ed5d9 | Create SetInputFieldSelected.cs | UnityCommunity/UnityLibrary | Assets/Scripts/UI/SetInputFieldSelected.cs | Assets/Scripts/UI/SetInputFieldSelected.cs | // sets input field selected (so that can start typing on it)
// usage: attach to UI InputField gameobject
using UnityEngine;
using UnityEngine.UI;
namespace UnityLibrary
{
[RequireComponent(typeof(InputField))]
public class SetInputFieldSelected : MonoBehaviour
{
void Start()
{
var inputField = GetComponent<InputField>();
inputField.Select();
}
}
}
| mit | C# | |
d9d563891b055c963d43fd4c5613260baa7a69d3 | Fix README.md code samples | dsolovay/AutoSitecore | src/AutoSitecoreUnitTest/DocumentationTest.cs | src/AutoSitecoreUnitTest/DocumentationTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoSitecoreUnitTest
{
class DocumentationTest
{
}
}
| mit | C# | |
47a288927311c13af8d3ec135e8a12eb48e859bc | disable windows by default and add a note about IIS requiring configuration | jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4 | src/Host/Quickstart/Account/AccountOptions.cs | src/Host/Quickstart/Account/AccountOptions.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
namespace IdentityServer4.Quickstart.UI
{
public class AccountOptions
{
public static bool AllowLocalLogin = true;
public static bool AllowRememberLogin = true;
public static TimeSpan RememberMeLoginDuration = TimeSpan.FromDays(30);
public static bool ShowLogoutPrompt = true;
public static bool AutomaticRedirectAfterSignOut = false;
// to enable windows authentication, the host (IIS or IIS Express) also must have
// windows auth enabled.
public static bool WindowsAuthenticationEnabled = false;
// specify the Windows authentication schemes you want to use for authentication
public static readonly string[] WindowsAuthenticationSchemes = new string[] { "Negotiate", "NTLM" };
public static readonly string WindowsAuthenticationProviderName = "Windows";
public static readonly string WindowsAuthenticationDisplayName = "Windows";
public static string InvalidCredentialsErrorMessage = "Invalid username or password";
}
}
| // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
namespace IdentityServer4.Quickstart.UI
{
public class AccountOptions
{
public static bool AllowLocalLogin = true;
public static bool AllowRememberLogin = true;
public static TimeSpan RememberMeLoginDuration = TimeSpan.FromDays(30);
public static bool ShowLogoutPrompt = true;
public static bool AutomaticRedirectAfterSignOut = false;
public static bool WindowsAuthenticationEnabled = true;
// specify the Windows authentication schemes you want to use for authentication
public static readonly string[] WindowsAuthenticationSchemes = new string[] { "Negotiate", "NTLM" };
public static readonly string WindowsAuthenticationProviderName = "Windows";
public static readonly string WindowsAuthenticationDisplayName = "Windows";
public static string InvalidCredentialsErrorMessage = "Invalid username or password";
}
}
| apache-2.0 | C# |
b126dc44950997afa17a4c0bb6ed3903229ed71e | Update ContextState.cs | IDeliverable/Orchard,bedegaming-aleksej/Orchard,ehe888/Orchard,sfmskywalker/Orchard,jersiovic/Orchard,geertdoornbos/Orchard,hbulzy/Orchard,fassetar/Orchard,ehe888/Orchard,Lombiq/Orchard,aaronamm/Orchard,jtkech/Orchard,hbulzy/Orchard,Lombiq/Orchard,Serlead/Orchard,Dolphinsimon/Orchard,Praggie/Orchard,AdvantageCS/Orchard,Praggie/Orchard,omidnasri/Orchard,jimasp/Orchard,omidnasri/Orchard,jersiovic/Orchard,geertdoornbos/Orchard,jagraz/Orchard,IDeliverable/Orchard,yersans/Orchard,yersans/Orchard,SzymonSel/Orchard,omidnasri/Orchard,jagraz/Orchard,IDeliverable/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,sfmskywalker/Orchard,Dolphinsimon/Orchard,geertdoornbos/Orchard,gcsuk/Orchard,Fogolan/OrchardForWork,rtpHarry/Orchard,jtkech/Orchard,JRKelso/Orchard,sfmskywalker/Orchard,hannan-azam/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,Fogolan/OrchardForWork,Praggie/Orchard,Dolphinsimon/Orchard,mvarblow/Orchard,phillipsj/Orchard,Praggie/Orchard,OrchardCMS/Orchard,AdvantageCS/Orchard,ehe888/Orchard,armanforghani/Orchard,Fogolan/OrchardForWork,JRKelso/Orchard,Fogolan/OrchardForWork,aaronamm/Orchard,SzymonSel/Orchard,bedegaming-aleksej/Orchard,hannan-azam/Orchard,mvarblow/Orchard,hannan-azam/Orchard,LaserSrl/Orchard,hbulzy/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,aaronamm/Orchard,Fogolan/OrchardForWork,mvarblow/Orchard,omidnasri/Orchard,omidnasri/Orchard,jimasp/Orchard,SzymonSel/Orchard,Lombiq/Orchard,omidnasri/Orchard,JRKelso/Orchard,hbulzy/Orchard,OrchardCMS/Orchard,gcsuk/Orchard,hannan-azam/Orchard,fassetar/Orchard,LaserSrl/Orchard,gcsuk/Orchard,johnnyqian/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,rtpHarry/Orchard,jtkech/Orchard,Serlead/Orchard,Lombiq/Orchard,sfmskywalker/Orchard,jimasp/Orchard,phillipsj/Orchard,aaronamm/Orchard,Dolphinsimon/Orchard,rtpHarry/Orchard,omidnasri/Orchard,jersiovic/Orchard,johnnyqian/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Praggie/Orchard,jimasp/Orchard,jersiovic/Orchard,Serlead/Orchard,jersiovic/Orchard,sfmskywalker/Orchard,IDeliverable/Orchard,fassetar/Orchard,jtkech/Orchard,JRKelso/Orchard,sfmskywalker/Orchard,armanforghani/Orchard,armanforghani/Orchard,geertdoornbos/Orchard,yersans/Orchard,OrchardCMS/Orchard,OrchardCMS/Orchard,bedegaming-aleksej/Orchard,jagraz/Orchard,hannan-azam/Orchard,AdvantageCS/Orchard,JRKelso/Orchard,gcsuk/Orchard,ehe888/Orchard,fassetar/Orchard,Dolphinsimon/Orchard,aaronamm/Orchard,Lombiq/Orchard,johnnyqian/Orchard,johnnyqian/Orchard,armanforghani/Orchard,sfmskywalker/Orchard,OrchardCMS/Orchard,rtpHarry/Orchard,bedegaming-aleksej/Orchard,Serlead/Orchard,yersans/Orchard,rtpHarry/Orchard,LaserSrl/Orchard,phillipsj/Orchard,LaserSrl/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,fassetar/Orchard,gcsuk/Orchard,omidnasri/Orchard,ehe888/Orchard,yersans/Orchard,phillipsj/Orchard,mvarblow/Orchard,jtkech/Orchard,jimasp/Orchard,johnnyqian/Orchard,SzymonSel/Orchard,IDeliverable/Orchard,geertdoornbos/Orchard,SzymonSel/Orchard,jagraz/Orchard,mvarblow/Orchard,bedegaming-aleksej/Orchard,armanforghani/Orchard,jagraz/Orchard,Serlead/Orchard,LaserSrl/Orchard,phillipsj/Orchard,hbulzy/Orchard | src/Orchard/Environment/State/ContextState.cs | src/Orchard/Environment/State/ContextState.cs | using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
namespace Orchard.Environment.State {
/// <summary>
/// Holds some state through the logical call context
/// </summary>
/// <typeparam name="T">The type of data to store</typeparam>
public class ContextState<T> where T : class {
private readonly string _name;
private readonly Func<T> _defaultValue;
public ContextState(string name) {
_name = name;
}
public ContextState(string name, Func<T> defaultValue) {
_name = name;
_defaultValue = defaultValue;
}
public T GetState() {
var handle = CallContext.LogicalGetData(_name) as ObjectHandle;
var data = handle != null ? handle.Unwrap() : null;
if (data == null) {
if (_defaultValue != null) {
CallContext.LogicalSetData(_name, new ObjectHandle(data = _defaultValue()));
return data as T;
}
}
return data as T;
}
public void SetState(T state) {
CallContext.LogicalSetData(_name, new ObjectHandle(state));
}
}
}
| using System;
using System.Runtime.Remoting.Messaging;
using System.Web;
namespace Orchard.Environment.State {
/// <summary>
/// Holds some state for the current HttpContext or thread
/// </summary>
/// <typeparam name="T">The type of data to store</typeparam>
public class ContextState<T> where T : class {
private readonly string _name;
private readonly Func<T> _defaultValue;
public ContextState(string name) {
_name = name;
}
public ContextState(string name, Func<T> defaultValue) {
_name = name;
_defaultValue = defaultValue;
}
public T GetState() {
if (HttpContext.Current == null) {
var data = CallContext.GetData(_name);
if (data == null) {
if (_defaultValue != null) {
CallContext.SetData(_name, data = _defaultValue());
return data as T;
}
}
return data as T;
}
if (HttpContext.Current.Items[_name] == null) {
HttpContext.Current.Items[_name] = _defaultValue == null ? null : _defaultValue();
}
return HttpContext.Current.Items[_name] as T;
}
public void SetState(T state) {
if (HttpContext.Current == null) {
CallContext.SetData(_name, state);
}
else {
HttpContext.Current.Items[_name] = state;
}
}
}
}
| bsd-3-clause | C# |
e07dab6f1012500901806287565d222ed12f2a1e | Add property Count to ChangedItemsCollection | twsouthwick/poshgit2 | src/PoshGit2/Status/ChangedItemsCollection.cs | src/PoshGit2/Status/ChangedItemsCollection.cs | using System.Collections.Generic;
using System.Linq;
namespace PoshGit2
{
public class ChangedItemsCollection
{
public ChangedItemsCollection()
{
var empty = new List<string>().AsReadOnly();
Added = empty;
Modified = empty;
Deleted = empty;
Unmerged = empty;
}
public bool HasAny => Added.Any() || Modified.Any() || Deleted.Any() || Unmerged.Any();
public IReadOnlyCollection<string> Added { get; set; }
public IReadOnlyCollection<string> Modified { get; set; }
public IReadOnlyCollection<string> Deleted { get; set; }
public IReadOnlyCollection<string> Unmerged { get; set; }
public int Count => Added.Count + Modified.Count + Deleted.Count + Unmerged.Count;
public int Length => Count;
public override string ToString()
{
return $"{Added.Count} | {Modified.Count} | {Deleted.Count} | {Unmerged.Count}";
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace PoshGit2
{
public class ChangedItemsCollection
{
public ChangedItemsCollection()
{
var empty = new List<string>().AsReadOnly();
Added = empty;
Modified = empty;
Deleted = empty;
Unmerged = empty;
}
public bool HasAny => Added.Any() || Modified.Any() || Deleted.Any() || Unmerged.Any();
public IReadOnlyCollection<string> Added { get; set; }
public IReadOnlyCollection<string> Modified { get; set; }
public IReadOnlyCollection<string> Deleted { get; set; }
public IReadOnlyCollection<string> Unmerged { get; set; }
public override string ToString()
{
return $"{Added.Count} | {Modified.Count} | {Deleted.Count} | {Unmerged.Count}";
}
}
}
| mit | C# |
be067b02e59f955dbaef3f8510fd737807b604a4 | handle case when no account doc exists but vacancies do | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Portal.Client/PortalClient.cs | src/SFA.DAS.EAS.Portal.Client/PortalClient.cs | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.EAS.Portal.Client.Application.Queries;
using SFA.DAS.EAS.Portal.Client.Services.DasRecruit;
using SFA.DAS.EAS.Portal.Client.Types;
using StructureMap;
namespace SFA.DAS.EAS.Portal.Client
{
public class PortalClient : IPortalClient
{
private readonly IGetAccountQuery _getAccountQuery;
private readonly IDasRecruitService _dasRecruitService;
public PortalClient(IContainer container)
{
_getAccountQuery = container.GetInstance<IGetAccountQuery>();
_dasRecruitService = container.GetInstance<IDasRecruitService>();
}
//todo: might be better to just accept publicHashedAccountId, and decode it here
public async Task<Account> GetAccount(long accountId, string publicHashedAccountId,
bool hasPayeScheme, CancellationToken cancellationToken = default)
{
// we potentially map 1 more vacancy than necessary, but it keeps the code clean
var vacanciesTask = hasPayeScheme ?
_dasRecruitService.GetVacancies(publicHashedAccountId, 2, cancellationToken) : null;
var account = await _getAccountQuery.Get(accountId, cancellationToken);
// at a later date, we might want to create an empty account doc and add the vacancy details to it, but for now, let's keep it simple
if (!hasPayeScheme || account == null)
return account;
var vacancies = await vacanciesTask;
if (vacancies == null)
return account;
var vacanciesCount = vacancies.Count();
switch (vacanciesCount)
{
case 0:
account.VacancyCardinality = Cardinality.None;
break;
case 1:
account.VacancyCardinality = Cardinality.One;
account.SingleVacancy = vacancies.Single();
break;
default:
account.VacancyCardinality = Cardinality.Many;
break;
}
return account;
}
}
} | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.EAS.Portal.Client.Application.Queries;
using SFA.DAS.EAS.Portal.Client.Services.DasRecruit;
using SFA.DAS.EAS.Portal.Client.Types;
using StructureMap;
namespace SFA.DAS.EAS.Portal.Client
{
public class PortalClient : IPortalClient
{
private readonly IGetAccountQuery _getAccountQuery;
private readonly IDasRecruitService _dasRecruitService;
public PortalClient(IContainer container)
{
_getAccountQuery = container.GetInstance<IGetAccountQuery>();
_dasRecruitService = container.GetInstance<IDasRecruitService>();
}
//todo: might be better to just accept publicHashedAccountId, and decode it here
public async Task<Account> GetAccount(long accountId, string publicHashedAccountId,
bool hasPayeScheme, CancellationToken cancellationToken = default)
{
// we potentially map 1 more vacancy tha necessary, but it keeps the code clean
var vacanciesTask = hasPayeScheme ?
_dasRecruitService.GetVacancies(publicHashedAccountId, 2, cancellationToken) : null;
var account = await _getAccountQuery.Get(accountId, cancellationToken);
if (!hasPayeScheme)
return account;
var vacancies = await vacanciesTask;
if (vacancies == null)
return account;
var vacanciesCount = vacancies.Count();
switch (vacanciesCount)
{
case 0:
account.VacancyCardinality = Cardinality.None;
break;
case 1:
account.VacancyCardinality = Cardinality.One;
account.SingleVacancy = vacancies.Single();
break;
default:
account.VacancyCardinality = Cardinality.Many;
break;
}
return account;
}
}
} | mit | C# |
a8bb1414708f2aef23e3f40bad63f79fb1558fcf | Create powerpanel.cs | p-blomberg/spaceengineers-ingame-scripts | powerpanel.cs | powerpanel.cs | const String LCD_NAME = "Power Panel";
const String MULTIPLIERS = ".kMGTPEZY";
void Main(string argument)
{
// Find solar panels. Sum their output.
List<IMyTerminalBlock> solars = new List<IMyTerminalBlock>();
GridTerminalSystem.GetBlocksOfType<IMySolarPanel>(solars);
String info = "";
// Why can't we have a nice API instead?
System.Text.RegularExpressions.Regex solarRegex = new System.Text.RegularExpressions.Regex(
"Max Output: (\\d+\\.?\\d*) (\\w?)W.*Current Output: (\\d+\\.?\\d*) (\\w?)W",
System.Text.RegularExpressions.RegexOptions.Singleline);
double total_max = 0.0f;
double total_current = 0.0f;
int active_solars = 0;
for(int i = 0;i<solars.Count;i++) {
info = solars[i].DetailedInfo;
double currentOutput = 0.0f;
double maxOutput = 0.0f;
double parsedDouble;
System.Text.RegularExpressions.Match match = solarRegex.Match(info);
if(match.Success) {
if(Double.TryParse(match.Groups[1].Value, out parsedDouble)) {
maxOutput = parsedDouble * Math.Pow(1000.0, MULTIPLIERS.IndexOf(match.Groups[2].Value));
}
if(Double.TryParse(match.Groups[3].Value, out parsedDouble)) {
currentOutput = parsedDouble * Math.Pow(1000.0, MULTIPLIERS.IndexOf(match.Groups[4].Value));
}
if(currentOutput > 0.0) {
active_solars++;
}
}
total_max += maxOutput;
total_current += currentOutput;
}
List<String> text = new List<String>();
text.Add("Updated: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
text.Add("-----------------");
text.Add("Solar panel status");
text.Add("Max output: " + Format(total_max) + "W");
text.Add("Current output: " + Format(total_current) + "W");
text.Add("Active panels: " + active_solars + " of " + solars.Count);
text.Add("-----------------");
// Find LCDs and update them
List<IMyTerminalBlock> lcds = new List<IMyTerminalBlock>();
GridTerminalSystem.SearchBlocksOfName(LCD_NAME, lcds);
IMyTextPanel panel = null;
for (int i = 0;i<lcds.Count;i++) {
if(lcds[i] is IMyTextPanel) {
panel = (IMyTextPanel)lcds[i];
panel.WritePublicText(String.Join("\n", text.ToArray()), false);
panel.ShowPublicTextOnScreen();
}
}
}
String Format(double power) {
int count = 0;
while (power > 1000.0) {
power = power / 1000;
count++;
}
return "" + Math.Round(power,2).ToString("##0.00") + " " + MULTIPLIERS.Substring(count,1);
}
| bsd-3-clause | C# | |
ee6d65ed8475bdbacb6c3370c529bac514d8c16e | Add touch event manager | smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Input/TouchEventManager.cs | osu.Framework/Input/TouchEventManager.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Framework.Input.States;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input
{
/// <summary>
/// A manager that manages states and events for a single touch.
/// </summary>
public class TouchEventManager : ButtonEventManager<MouseButton>
{
protected Vector2? TouchDownPosition;
public TouchEventManager(MouseButton source)
: base(source)
{
}
public void HandlePositionChange(InputState state, Vector2 lastPosition)
{
var position = state.Touch.TouchPositions[Button];
if (position == lastPosition)
return;
HandleTouchMove(state, position, lastPosition);
}
protected void HandleTouchMove(InputState state, Vector2 position, Vector2 lastPosition)
{
PropagateButtonEvent(InputQueue, new TouchMoveEvent(state, new Touch(Button, position), TouchDownPosition, lastPosition));
}
protected override Drawable HandleButtonDown(InputState state, List<Drawable> targets)
{
TouchDownPosition = state.Touch.GetTouchPosition(Button);
if (TouchDownPosition is Vector2 downPosition && ButtonDownInputQueue == null)
return PropagateButtonEvent(targets, new TouchDownEvent(state, new Touch(Button, downPosition)));
return null;
}
protected override void HandleButtonUp(InputState state, List<Drawable> targets)
{
if (state.Touch.GetTouchPosition(Button) is Vector2 position && ButtonDownInputQueue != null)
PropagateButtonEvent(targets, new TouchUpEvent(state, new Touch(Button, position), TouchDownPosition));
TouchDownPosition = null;
}
}
}
| mit | C# | |
f672f3dd8659c6be24924f5a2df6ebbbd7cdf0a3 | Create SimpleObjectFadeInOut.cs | felladrin/unity3d-scripts,felladrin/unity-scripts | SimpleObjectFadeInOut.cs | SimpleObjectFadeInOut.cs | using UnityEngine;
using UnityEngine.SceneManagement;
public class SimpleObjectFadeInOut : MonoBehaviour
{
public float Speed = 0.5F;
public int TimeInSecondsBeforeStartFadingOut = 1;
bool apprearing = true;
SpriteRenderer spriteRenderer;
Color spriteRendererColor;
void Start ()
{
spriteRenderer = gameObject.GetComponent<SpriteRenderer> ();
spriteRendererColor = spriteRenderer.color;
spriteRendererColor.a = 0;
spriteRenderer.color = spriteRendererColor;
}
void Update ()
{
spriteRendererColor = spriteRenderer.color;
var currentOpacity = spriteRenderer.color.a;
if (apprearing) {
if (currentOpacity < 1) {
spriteRendererColor.a = currentOpacity + Speed * Time.deltaTime;
spriteRenderer.color = spriteRendererColor;
} else {
Invoke ("SetAppearingFalse", TimeInSecondsBeforeStartFadingOut);
}
} else {
if (currentOpacity > 0) {
spriteRendererColor.a = currentOpacity - Speed * Time.deltaTime;
spriteRenderer.color = spriteRendererColor;
}
}
}
void SetAppearingFalse ()
{
apprearing = false;
}
}
| mit | C# | |
0d58195a77a4a213040ee1a764c96ab434c6c96a | Update QueueConverter.cs | Shidesu/RiotSharp,Challengermode/RiotSharp,frederickrogan/RiotSharp,florinciubotariu/RiotSharp,oisindoherty/RiotSharp,Oucema90/RiotSharp,jono-90/RiotSharp,BenFradet/RiotSharp,JanOuborny/RiotSharp,aktai0/RiotSharp | RiotSharp/Misc/QueueConverter.cs | RiotSharp/Misc/QueueConverter.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
namespace RiotSharp
{
class QueueConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(string).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var token = JToken.Load(reader);
if (token.Value<string>() == null) return null;
var str = token.Value<string>();
switch (str)
{
case "RANKED_SOLO_5x5":
return Queue.RankedSolo5x5;
case "RANKED_TEAM_3x3":
return Queue.RankedTeam3x3;
case "RANKED_TEAM_5x5":
return Queue.RankedTeam5x5;
case "TEAM_BUILDER_DRAFT_RANKED_5x5":
return Queue.TeamBuilderDraftRanked5x5;
case "TEAM_BUILDER_DRAFT_UNRANKED_5x5":
return Queue.TeamBuilderDraftUnranked5x5;
default:
return null;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((Queue)value).ToCustomString());
}
}
}
| using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
namespace RiotSharp
{
class QueueConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(string).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var token = JToken.Load(reader);
if (token.Value<string>() == null) return null;
var str = token.Value<string>();
switch (str)
{
case "RANKED_SOLO_5x5":
return Queue.RankedSolo5x5;
case "RANKED_TEAM_3x3":
return Queue.RankedTeam3x3;
case "RANKED_TEAM_5x5":
return Queue.RankedTeam5x5;
case "TEAM_BUILDER_DRAFT_RANKED_5x5":
return Queue.TeamBuilderDraftRanked5x5;
case "TEAM_BUILDER_DRAFT_UNRANKED_5x5":
return Queue.TeamBuilderDraftUnranked5x5
default:
return null;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((Queue)value).ToCustomString());
}
}
}
| mit | C# |
dbf54ff6946a06e9b83200423866d0e02acb6b27 | Add copyright to footer | cake-contrib/Cake.Prca.Website,cake-contrib/Cake.Prca.Website | input/_Footer.cshtml | input/_Footer.cshtml | <p class="text-muted">
Copyright © <a href="http://bbtsoftware.ch" target="_blank">BBT Software AG</a> and <a href="https://github.com/cake-contrib/Cake.Prca/graphs/contributors" target="_blank">contributors</a>.
<br/>
Website generated by <a href="http://wyam.io" target="_blank">Wyam</a>
</p>
| mit | C# | |
b30b4b05df951a1739690f5e8ba94c5b16a4a9f4 | Add simple CyclicArray for structures | AikenParker/Expanse,LemonLube/Expanse | StandaloneUtility/CyclicArray.cs | StandaloneUtility/CyclicArray.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace Expanse
{
/// <summary>
/// Fixed array data structure that cycles the index when adding more elements than the specified size.
/// </summary>
/// <typeparam name="T">Type of the structure to be contained.</typeparam>
public struct CyclicArray<T> : IEnumerable<T> where T : struct
{
private T[] array; // Internal array data structure
private int index; // Index of the most recently added item
private bool allSet; // Flag is true if all array slots have been set
/// <summary>
/// Creates a new Cyclic array data structure.
/// </summary>
/// <param name="size">Length of the array to be allocated.</param>
public CyclicArray(int size)
{
this.array = new T[size];
this.index = -1;
this.allSet = false;
}
/// <summary>
/// Adds a new item into the array.
/// </summary>
/// <param name="inItem">The item to be added to the array.</param>
public void Add(T inItem)
{
if (++this.index == this.array.Length)
{
this.index = 0;
this.allSet = true;
}
array[this.index] = inItem;
}
/// <summary>
/// Adds a new item into the array.
/// </summary>
/// <param name="inItem">The item to be added to the array.</param>
/// <param name="outItem">The item to be replaced by the new item in the array.</param>
/// <returns>Returns true if an item was replaced in the array.</returns>
public bool Add(T inItem, out T outItem)
{
if (++this.index == this.array.Length)
{
this.index = 0;
this.allSet = true;
}
outItem = array[this.index];
array[this.index] = inItem;
return allSet;
}
/// <summary>
/// Returns the item in the array with an index relative to the most recent.
/// Will only accept values between -Length and 0.
/// </summary>
/// <param name="index">Index of item relative to index of most recent item.</param>
/// <returns>The item of index relative to the most recent item.</returns>
public T this[int index]
{
get
{
if (index > 0 || index <= -array.Length || (!allSet && index < -this.index))
throw new ArgumentOutOfRangeException("index");
index += this.index;
if (index < -array.Length)
index += array.Length;
return this.array[index];
}
set
{
if (index > 0 || index <= -array.Length || (!allSet && index < -this.index))
throw new ArgumentOutOfRangeException("index");
index += this.index;
if (index < -array.Length)
index += array.Length;
this.array[index] = value;
}
}
/// <summary>
/// Index of the most recent item added to the array.
/// </summary>
public int Index
{
get { return this.index; }
}
/// <summary>
/// Is true if all items in the array have been set at least once.
/// </summary>
public bool AllSet
{
get { return this.allSet; }
}
/// <summary>
/// Gets the size of the internal array.
/// </summary>
public int Length
{
get { return this.array.Length; }
}
/// <summary>
/// Gets the internal array.
/// </summary>
public T[] Array
{
get { return this.array; }
}
/// <summary>
/// Gets an enumerater of the internal array.
/// </summary>
/// <returns>The enumerator of the internal array.</returns>
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)array).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)array).GetEnumerator();
}
}
}
| mit | C# | |
c2fdaaa8fccbc016baa6f0af9418afaafa42a9d3 | Create KidEntry.cs | fairmat/OpenKID,fairmat/OpenKID | client-sample/c-sharp/Model/KidEntry.cs | client-sample/c-sharp/Model/KidEntry.cs | ///
// This file contains utility classes to access easily OpenKID repositories
// in order to extract information from them
//
// LICENCE:
// Copyright (c) 2016 Fairmat SRL.
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// <copyright>Copyright (c) 2016 Fairmat SRL (http://www.fairmat.com)</copyright>
// <license>MIT.</license>
// <version>0.1</version>
///
///
// An implementation of several utils to access OpenKID repositories.
//
// <copyright>Copyright (c) 2016 Fairmat SRL (http://www.fairmat.com)</copyright>
// <license>MIT.</license>
// <version>0.1</version>
///
using System;
using System.Collections.Generic;
namespace openKid.Model
{
public class KidEntry
{
public string Issuer { get; set; }
public string Isin { get; set; }
public string ProductName { get; set; }
public DateTime? FirstPublished { get; set; }
public DateTime? LastUpdated { get; set; }
public string HistoryUrl { get; set; }
public IList<KidVersion> Versions { get; set; }
}
}
| mit | C# | |
35f886799786dd7571747b15cd3e8c88b55cd9fd | Add exception handling for other input and add comments | kyulee1/coreclr,yizhang82/coreclr,yizhang82/coreclr,poizan42/coreclr,ruben-ayrapetyan/coreclr,wateret/coreclr,AlexGhiondea/coreclr,JosephTremoulet/coreclr,cshung/coreclr,parjong/coreclr,krk/coreclr,AlexGhiondea/coreclr,AlexGhiondea/coreclr,krk/coreclr,poizan42/coreclr,wtgodbe/coreclr,JosephTremoulet/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,mmitche/coreclr,dpodder/coreclr,poizan42/coreclr,rartemev/coreclr,wtgodbe/coreclr,rartemev/coreclr,parjong/coreclr,mmitche/coreclr,krk/coreclr,JosephTremoulet/coreclr,yizhang82/coreclr,dpodder/coreclr,dpodder/coreclr,wateret/coreclr,rartemev/coreclr,yizhang82/coreclr,wateret/coreclr,dpodder/coreclr,botaberg/coreclr,botaberg/coreclr,yizhang82/coreclr,ruben-ayrapetyan/coreclr,kyulee1/coreclr,cshung/coreclr,rartemev/coreclr,hseok-oh/coreclr,krk/coreclr,wtgodbe/coreclr,botaberg/coreclr,rartemev/coreclr,JosephTremoulet/coreclr,wtgodbe/coreclr,parjong/coreclr,AlexGhiondea/coreclr,krk/coreclr,ruben-ayrapetyan/coreclr,hseok-oh/coreclr,cshung/coreclr,cshung/coreclr,yizhang82/coreclr,wateret/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,hseok-oh/coreclr,AlexGhiondea/coreclr,botaberg/coreclr,dpodder/coreclr,wateret/coreclr,krk/coreclr,hseok-oh/coreclr,JosephTremoulet/coreclr,kyulee1/coreclr,poizan42/coreclr,botaberg/coreclr,parjong/coreclr,wtgodbe/coreclr,parjong/coreclr,wateret/coreclr,AlexGhiondea/coreclr,parjong/coreclr,rartemev/coreclr,mmitche/coreclr,hseok-oh/coreclr,kyulee1/coreclr,poizan42/coreclr,mmitche/coreclr,botaberg/coreclr,ruben-ayrapetyan/coreclr,hseok-oh/coreclr,kyulee1/coreclr,JosephTremoulet/coreclr,kyulee1/coreclr,mmitche/coreclr,dpodder/coreclr,mmitche/coreclr,ruben-ayrapetyan/coreclr | src/mscorlib/shared/System/UnitySerializationHolder.cs | src/mscorlib/shared/System/UnitySerializationHolder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using System.Reflection;
namespace System
{
/// <summary>
/// Holds Null class for which we guarantee that there is only ever one instance of.
/// This only exists for backwarts compatibility with
/// </summary>
#if CORECLR
internal
#else
public // On CoreRT this must be public.
#endif
sealed class UnitySerializationHolder : ISerializable, IObjectReference
{
internal const int NullUnity = 0x0002;
private readonly int _unityType;
/// <summary>
/// A helper method that returns the SerializationInfo that a class utilizing
/// UnitySerializationHelper should return from a call to GetObjectData. It contains
/// the unityType (defined above) and any optional data (used only for the reflection types).
/// </summary>
public static void GetUnitySerializationInfo(SerializationInfo info, int unityType, string data, Assembly assembly)
{
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("Data", data, typeof(string));
info.AddValue("UnityType", unityType);
info.AddValue("AssemblyName", assembly?.FullName ?? string.Empty);
}
public UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
// We are ignoring any other serialization input as we are only concerned about DBNull.
_unityType = info.GetInt32("UnityType");
}
public void GetObjectData(SerializationInfo info, StreamingContext context) =>
throw new NotSupportedException(SR.NotSupported_UnitySerHolder);
public object GetRealObject(StreamingContext context)
{
// We are only support deserializing DBNull and throwing for everything else.
if (_unityType != NullUnity)
{
throw new ArgumentException(SR.Argument_InvalidUnity);
}
// We are always returning the same DBNull instance.
return DBNull.Value;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using System.Reflection;
namespace System
{
/// <summary>
/// Holds Null class for which we guarantee that there is only ever one instance of.
/// This only exists for backwarts compatibility with
/// </summary>
#if CORECLR
internal
#else
public // On CoreRT this must be public.
#endif
sealed class UnitySerializationHolder : ISerializable, IObjectReference
{
internal const int NullUnity = 0x0002;
public static void GetUnitySerializationInfo(SerializationInfo info, int unityType, string data, Assembly assembly)
{
// A helper method that returns the SerializationInfo that a class utilizing
// UnitySerializationHelper should return from a call to GetObjectData. It contains
// the unityType (defined above) and any optional data (used only for the reflection
// types.)
info.SetType(typeof(UnitySerializationHolder));
info.AddValue("Data", data, typeof(string));
info.AddValue("UnityType", unityType);
info.AddValue("AssemblyName", assembly?.FullName ?? string.Empty);
}
public UnitySerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
// We are ignoring any serialization input as we are only concerned about DBNull.
}
public void GetObjectData(SerializationInfo info, StreamingContext context) =>
throw new NotSupportedException(SR.NotSupported_UnitySerHolder);
public object GetRealObject(StreamingContext context)
{
// We are always returning the same DBNull instance and ignoring serialization input.
return DBNull.Value;
}
}
}
| mit | C# |
1977d3cbb01403b4949467dd1fa6e58c13354ead | Add Q203 | txchen/localleet | csharp/Q203_RemoveLinkedListElements.cs | csharp/Q203_RemoveLinkedListElements.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Remove all elements from a linked list of integers that have value val.
//
// Example
// Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
// Return: 1 --> 2 --> 3 --> 4 --> 5
// https://leetcode.com/problems/remove-linked-list-elements/
namespace LocalLeet
{
public class Q203
{
public ListNode<int> RemoveElements(ListNode<int> head, int val)
{
ListNode<int> preA = new ListNode<int>(0);
preA.Next = head;
var cur = preA;
while (cur.Next != null)
{
if (cur.Next.Val == val)
{
cur.Next = cur.Next.Next;
}
else
{
cur = cur.Next;
}
}
return preA.Next;
}
[Fact]
public void Q203_RemoveLinkedListElements()
{
TestHelper.Run(input => RemoveElements(input[0].ToListNode2<int>(), input[1].ToInt()).SerializeListNode2());
}
}
}
| mit | C# | |
21ca44397cf754ec21aec6ccb61d703600bde00d | add dictionary extensions | SorenZ/Alamut.DotNet | src/Alamut.Helpers/Collection/DictionaryExtensions.cs | src/Alamut.Helpers/Collection/DictionaryExtensions.cs |
using System.Collections.Generic;
namespace Alamut.Helpers.Collection
{
public static class DictionaryExtensions
{
/// <summary>
/// update the source dic or insert new fields from provided information by newOne
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="source"></param>
/// <param name="newOne"></param>
public static void Upsert<TKey, TValue>(this Dictionary<TKey, TValue> source, Dictionary<TKey, TValue> newOne)
{
foreach (var item in newOne)
{
source[item.Key] = item.Value;
}
}
}
} | mit | C# | |
b416045304f4743d657f20f1e19afa4d6c6e4c2e | Add GetSource and Reader methods to FineFundamental | young-zhang/Lean,JKarathiya/Lean,andrewhart098/Lean,young-zhang/Lean,tomhunter-gh/Lean,andrewhart098/Lean,redmeros/Lean,kaffeebrauer/Lean,tomhunter-gh/Lean,AlexCatarino/Lean,QuantConnect/Lean,squideyes/Lean,AnshulYADAV007/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,Phoenix1271/Lean,AnObfuscator/Lean,AlexCatarino/Lean,JKarathiya/Lean,StefanoRaggi/Lean,Phoenix1271/Lean,AnObfuscator/Lean,Mendelone/forex_trading,kaffeebrauer/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,jameschch/Lean,StefanoRaggi/Lean,squideyes/Lean,QuantConnect/Lean,StefanoRaggi/Lean,redmeros/Lean,jameschch/Lean,AlexCatarino/Lean,redmeros/Lean,Mendelone/forex_trading,kaffeebrauer/Lean,jameschch/Lean,squideyes/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,tomhunter-gh/Lean,devalkeralia/Lean,AnObfuscator/Lean,Phoenix1271/Lean,kaffeebrauer/Lean,devalkeralia/Lean,JKarathiya/Lean,devalkeralia/Lean,JKarathiya/Lean,AnshulYADAV007/Lean,andrewhart098/Lean,Mendelone/forex_trading,jameschch/Lean,AnObfuscator/Lean,squideyes/Lean,young-zhang/Lean,andrewhart098/Lean,Mendelone/forex_trading,Jay-Jay-D/LeanSTP,young-zhang/Lean,AnshulYADAV007/Lean,AlexCatarino/Lean,Jay-Jay-D/LeanSTP,redmeros/Lean,devalkeralia/Lean,QuantConnect/Lean,AnshulYADAV007/Lean,kaffeebrauer/Lean,Phoenix1271/Lean,tomhunter-gh/Lean,AnshulYADAV007/Lean,QuantConnect/Lean | Common/Data/Fundamental/FineFundamental.cs | Common/Data/Fundamental/FineFundamental.cs | /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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;
using System.IO;
using Newtonsoft.Json;
namespace QuantConnect.Data.Fundamental
{
/// <summary>
/// Definition of the FineFundamental class
/// </summary>
public partial class FineFundamental
{
/// <summary>
/// The end time of this data.
/// </summary>
[JsonIgnore]
public override DateTime EndTime
{
get { return Time + QuantConnect.Time.OneDay; }
set { Time = value - QuantConnect.Time.OneDay; }
}
/// <summary>
/// Creates the universe symbol used for fine fundamental data
/// </summary>
/// <param name="market">The market</param>
/// <returns>A fine universe symbol for the specified market</returns>
public static Symbol CreateUniverseSymbol(string market)
{
market = market.ToLower();
var ticker = "qc-universe-fine-" + market;
var sid = SecurityIdentifier.GenerateEquity(SecurityIdentifier.DefaultDate, ticker, market);
return new Symbol(sid, ticker);
}
/// <summary>
/// Return the URL string source of the file. This will be converted to a stream
/// </summary>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
var source =
Path.Combine(Globals.DataFolder, "equity", config.Market, "fundamental", "fine",
config.Symbol.Value, date.ToString("yyyyMMdd") + ".zip");
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
}
/// <summary>
/// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object
/// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone.
/// </summary>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
return JsonConvert.DeserializeObject<FineFundamental>(line);
}
}
}
| /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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;
using Newtonsoft.Json;
namespace QuantConnect.Data.Fundamental
{
/// <summary>
/// Definition of the FineFundamental class
/// </summary>
public partial class FineFundamental
{
/// <summary>
/// The end time of this data.
/// </summary>
[JsonIgnore]
public override DateTime EndTime
{
get { return Time + QuantConnect.Time.OneDay; }
set { Time = value - QuantConnect.Time.OneDay; }
}
/// <summary>
/// Creates the universe symbol used for fine fundamental data
/// </summary>
/// <param name="market">The market</param>
/// <returns>A fine universe symbol for the specified market</returns>
public static Symbol CreateUniverseSymbol(string market)
{
market = market.ToLower();
var ticker = "qc-universe-fine-" + market;
var sid = SecurityIdentifier.GenerateEquity(SecurityIdentifier.DefaultDate, ticker, market);
return new Symbol(sid, ticker);
}
}
}
| apache-2.0 | C# |
80044fcfe8dd212e9587942972f4eb3ce7450244 | Set CheckUnexpectedExtensions to lazy load (#162) | RichardHowells/Dnn.Platform,robsiera/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,EPTamminga/Dnn.Platform,EPTamminga/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,robsiera/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.Platform,RichardHowells/Dnn.Platform,EPTamminga/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,RichardHowells/Dnn.Platform | Extensions/Settings/Dnn.PersonaBar.Security/Components/Checks/CheckUnexpectedExtensions.cs | Extensions/Settings/Dnn.PersonaBar.Security/Components/Checks/CheckUnexpectedExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Dnn.PersonaBar.Security.Components.Checks
{
public class CheckUnexpectedExtensions : IAuditCheck
{
public string Id => "CheckUnexpectedExtensions";
public bool LazyLoad => true;
public CheckResult Execute()
{
var result = new CheckResult(SeverityEnum.Unverified, Id);
var invalidFolders = new List<string>();
var investigatefiles = Utility.FindUnexpectedExtensions(invalidFolders).ToList();
if (investigatefiles.Count > 0)
{
result.Severity = SeverityEnum.Failure;
foreach (var filename in investigatefiles)
{
result.Notes.Add("file:" + filename);
}
}
else
{
result.Severity = SeverityEnum.Pass;
}
if (invalidFolders.Count > 0)
{
var folders = string.Join("", invalidFolders.Select(f => $"<p>{f}</p>").ToArray());
result.Notes.Add($"<p>The following folders are inaccessible due to permission restrictions:</p>{folders}");
}
return result;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Dnn.PersonaBar.Security.Components.Checks
{
public class CheckUnexpectedExtensions : IAuditCheck
{
public string Id => "CheckUnexpectedExtensions";
public bool LazyLoad => false;
public CheckResult Execute()
{
var result = new CheckResult(SeverityEnum.Unverified, Id);
var invalidFolders = new List<string>();
var investigatefiles = Utility.FindUnexpectedExtensions(invalidFolders).ToList();
if (investigatefiles.Count > 0)
{
result.Severity = SeverityEnum.Failure;
foreach (var filename in investigatefiles)
{
result.Notes.Add("file:" + filename);
}
}
else
{
result.Severity = SeverityEnum.Pass;
}
if (invalidFolders.Count > 0)
{
var folders = string.Join("", invalidFolders.Select(f => $"<p>{f}</p>").ToArray());
result.Notes.Add($"<p>The following folders are inaccessible due to permission restrictions:</p>{folders}");
}
return result;
}
}
} | mit | C# |
aa08ecf85474d4ef90471aa75699e4d14608d643 | Fix issue with line endings in AddAzureApiManagementApiToProduct | naveedaz/azure-powershell,krkhan/azure-powershell,krkhan/azure-powershell,ClogenyTechnologies/azure-powershell,pankajsn/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell,rohmano/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,ClogenyTechnologies/azure-powershell,krkhan/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell | src/ResourceManager/ApiManagement/Commands.ApiManagement.ServiceManagement/Commands/AddAzureApiManagementApiToProduct.cs | src/ResourceManager/ApiManagement/Commands.ApiManagement.ServiceManagement/Commands/AddAzureApiManagementApiToProduct.cs | //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Commands
{
using Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models;
using System;
using System.Management.Automation;
[Cmdlet(VerbsCommon.Add, Constants.ApiManagementApiToProduct)]
[OutputType(typeof(bool))]
public class AddAzureApiManagementApiToProduct : AzureApiManagementCmdletBase
{
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = true,
HelpMessage = "Instance of PsApiManagementContext. This parameter is required.")]
[ValidateNotNullOrEmpty]
public PsApiManagementContext Context { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = true,
HelpMessage = "Identifier of existing Product to add API to. This parameter is required.")]
[ValidateNotNullOrEmpty]
public String ProductId { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = true,
HelpMessage = "Identifier of existing APIs to be added to the product. This parameter is required.")]
[ValidateNotNullOrEmpty]
public String ApiId { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = false,
HelpMessage = "If specified will write true in case operation succeeds. This parameter is optional. Default value is false.")]
public SwitchParameter PassThru { get; set; }
public override void ExecuteApiManagementCmdlet()
{
Client.ApiAddToProduct(Context, ProductId, ApiId);
if (PassThru)
{
WriteObject(true);
}
}
}
} | //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Commands
{
using Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models;
using System;
using System.Management.Automation;
[Cmdlet(VerbsCommon.Add, Constants.ApiManagementApiToProduct)]
[OutputType(typeof(bool))]
public class AddAzureApiManagementApiToProduct : AzureApiManagementCmdletBase
{
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = true,
HelpMessage = "Instance of PsApiManagementContext. This parameter is required.")]
[ValidateNotNullOrEmpty]
public PsApiManagementContext Context { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = true,
HelpMessage = "Identifier of existing Product to add API to. This parameter is required.")]
[ValidateNotNullOrEmpty]
public String ProductId { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = true,
HelpMessage = "Identifier of existing APIs to be added to the product. This parameter is required.")]
[ValidateNotNullOrEmpty]
public String ApiId { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
Mandatory = false,
HelpMessage = "If specified will write true in case operation succeeds. This parameter is optional. Default value is false.")]
public SwitchParameter PassThru { get; set; }
public override void ExecuteApiManagementCmdlet()
{
Client.ApiAddToProduct(Context, ProductId, ApiId);
if (PassThru)
{
WriteObject(true);
}
}
}
} | apache-2.0 | C# |
ded24a65f8179bdb5c5f2c501c470f56f3791f01 | Create BradleyWyatt.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/BradleyWyatt.cs | src/Firehose.Web/Authors/BradleyWyatt.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class BradleyWyatt : IAmACommunityMember
{
public string FirstName => "Bradley";
public string LastName => "Wyatt";
public string ShortBioOrTagLine => "Finding wayt to do the most work with the least effort possible";
public string StateOrRegion => "Chicago, Illinois";
public string EmailAddress => "brad@thelazyadministrator.com";
public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09";
public string TwitterHandle => "bwya77";
public string GitHubHandle => "bwya77";
public Uri WebSite => new Uri("https://www.thelazyadministrator.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.com/feed/"); } }
}
}
| mit | C# | |
3b9d633292a75f7338857d00c638b7e50f35c0e6 | Create PixelPerfectCamera.cs | UnityCommunity/UnityLibrary | Scripts/2D/Camera/PixelPerfectCamera.cs | Scripts/2D/Camera/PixelPerfectCamera.cs | using UnityEngine;
// pixel perfect camera helpers, from old unity 2D tutorial videos
[ExecuteInEditMode]
public class PixelPerfectCamera : MonoBehaviour {
public float pixelsToUnits = 100;
void Start ()
{
GetComponent<Camera>().orthographicSize = Screen.height / pixelsToUnits / 2;
}
}
| mit | C# | |
8cf8c4eb02b4b537d806ea9078df7bef835647f5 | Add SafeWait (anti dead lock) | lerthe61/Snippets,lerthe61/Snippets | dotNet/Tasks/SafeWait.cs | dotNet/Tasks/SafeWait.cs | Task.Run(() => this.FunctionAsync()).Wait(); | unlicense | C# | |
654cfd4a4794e54ced02ccff37be1cd744579bc9 | Add missing TypeExtensions file | sharpdx/SharpDX,andrewst/SharpDX,sharpdx/SharpDX,andrewst/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,sharpdx/SharpDX,mrvux/SharpDX,mrvux/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,andrewst/SharpDX,mrvux/SharpDX | Source/SharpDX/Reflection/TypeExtensions.cs | Source/SharpDX/Reflection/TypeExtensions.cs | using System.Collections.Generic;
#if BEFORE_NET45
// Copyright (c) 2010-2017 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace System.Reflection
{
internal static class SharpDXTypeExtensions
{
public static Type GetTypeInfo(this Type type)
{
return type;
}
public static T GetCustomAttribute<T>(this Type type) where T : Attribute
{
var attrs = type.GetCustomAttributes(typeof(T), true);
if(attrs.Length == 0)
{
return null;
}
return (T)attrs[0];
}
public static T GetCustomAttribute<T>(this MemberInfo memberInfo, bool inherited) where T : Attribute
{
var attrs = memberInfo.GetCustomAttributes(typeof(T), inherited);
if (attrs.Length == 0)
{
return null;
}
return (T)attrs[0];
}
public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo memberInfo, bool inherited) where T : Attribute
{
var attrs = memberInfo.GetCustomAttributes(typeof(T), inherited);
foreach(var attr in attrs)
{
yield return (T)attr;
}
}
}
}
#endif | mit | C# | |
61446401e74ab6e2eb9183934fb99e616181befc | change the version to 3.2.3 | SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk,RachelTucker/ds3_net_sdk,RachelTucker/ds3_net_sdk | VersionInfo.cs | VersionInfo.cs | /*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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;
// 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("3.2.3.0")]
[assembly: AssemblyFileVersion("3.2.3.0")]
| /*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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;
// 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("3.2.2.0")]
[assembly: AssemblyFileVersion("3.2.2.0")]
| apache-2.0 | C# |
698f80a964c65d423505cc6c9237d68f9fa9bb2c | Implement CartSpecs to Control Specification | MrWooJ/WJStore | WJStore.Domain/Entities/Specifications/CartSpecs/CartCountShouldBeGreaterThanZeroSpec.cs | WJStore.Domain/Entities/Specifications/CartSpecs/CartCountShouldBeGreaterThanZeroSpec.cs | using WJStore.Domain.Interfaces.Validation;
namespace WJStore.Domain.Entities.Specifications.CartSpecs
{
public class CartCountShouldBeGreaterThanZeroSpec : ISpecification<Cart>
{
public bool IsSatisfiedBy(Cart cart)
{
return cart.Count > 0;
}
}
}
| mit | C# | |
bfe80b06179ec2886da1c6818eadfcd96740e62d | Add missing properties of LogEntry | jerriep/auth0.net,auth0/auth0.net,jerriep/auth0.net,auth0/auth0.net,jerriep/auth0.net | src/Auth0.ManagementApi/Models/LogEntry.cs | src/Auth0.ManagementApi/Models/LogEntry.cs | using System;
using Newtonsoft.Json;
namespace Auth0.ManagementApi.Models
{
/// <summary>
/// Information about a log entry
/// </summary>
public class LogEntry
{
/// <summary>
/// The unique identifier for the log entry
/// </summary>
[JsonProperty("_id")]
public string Id { get; set; }
/// <summary>
/// The date when the event was created
/// </summary>
[JsonProperty("date")]
public DateTime Date { get; set; }
/// <summary>
/// The log event type
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
/// <summary>
/// The identifier of the client
/// </summary>
[JsonProperty("client_id")]
public string ClientId { get; set; }
/// <summary>
/// The name of the client
/// </summary>
[JsonProperty("client_name")]
public string ClientName { get; set; }
/// <summary>
/// The name of the connection
/// </summary>
[JsonProperty("connection")]
public string Connection { get; set; }
/// <summary>
/// The id of the connection
/// </summary>
[JsonProperty("connection_id")]
public string ConnectionId { get; set; }
/// <summary>
/// The strategy used
/// </summary>
[JsonProperty("strategy")]
public string Strategy { get; set; }
/// <summary>
/// The strategy type
/// </summary>
[JsonProperty("strategy_type")]
public string StrategyType { get; set; }
/// <summary>
/// The IP address of the log event source
/// </summary>
[JsonProperty("ip")]
public string IpAddress { get; set; }
/// <summary>
/// Additional details about the event's ip trace location. If the ip matches either as private or localhost it returns an empty object
/// </summary>
[JsonProperty("location_info")]
public dynamic LocationInfo { get; set; }
/// <summary>
/// Additional (and very useful) details about the event.
/// </summary>
[JsonProperty("details")]
public dynamic Details { get; set; }
/// <summary>
/// The user's browser user-agent
/// </summary>
[JsonProperty("user_agent")]
public string UserAgent { get; set; }
/// <summary>
/// The user's unique identifier
/// </summary>
[JsonProperty("user_id")]
public string UserId { get; set; }
/// <summary>
/// The user's name
/// </summary>
[JsonProperty("user_name")]
public string UserName { get; set; }
}
} | using System;
using Newtonsoft.Json;
namespace Auth0.ManagementApi.Models
{
/// <summary>
/// Information about a log entry
/// </summary>
public class LogEntry
{
/// <summary>
/// The unique identifier for the log entry
/// </summary>
[JsonProperty("_id")]
public string Id { get; set; }
/// <summary>
/// The date when the event was created
/// </summary>
[JsonProperty("date")]
public DateTime Date { get; set; }
/// <summary>
/// The log event type
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
/// <summary>
/// The identifier of the client
/// </summary>
[JsonProperty("client_id")]
public string ClientId { get; set; }
/// <summary>
/// The name of the client
/// </summary>
[JsonProperty("client_name")]
public string ClientName { get; set; }
/// <summary>
/// The IP address of the log event source
/// </summary>
[JsonProperty("ip")]
public string IpAddress { get; set; }
/// <summary>
/// Additional details about the event's ip trace location. If the ip matches either as private or localhost it returns an empty object
/// </summary>
[JsonProperty("location_info")]
public dynamic LocationInfo { get; set; }
/// <summary>
/// Additional (and very useful) details about the event.
/// </summary>
[JsonProperty("details")]
public dynamic Details { get; set; }
/// <summary>
/// The user's unique identifier
/// </summary>
[JsonProperty("user_id")]
public string UserId { get; set; }
}
} | mit | C# |
5876e68efaae79c1b76ada607544a170ff293f8f | Add Q198 | txchen/localleet | csharp/Q198_HouseRobber.cs | csharp/Q198_HouseRobber.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
//
// Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
// https://leetcode.com/problems/house-robber/
namespace LocalLeet
{
public class Q198
{
public int Rob(int[] nums)
{
if (nums.Length == 0)
{
return 0;
}
if (nums.Length <= 1)
{
return nums[0];
}
nums[1] = Math.Max(nums[0], nums[1]);
for (int i = 2; i < nums.Length; i++)
{
nums[i] = Math.Max(nums[i-2] + nums[i], nums[i-1]); // rob current or not
}
return nums[nums.Length - 1];
}
[Fact]
public void Q198_HouseRobber()
{
TestHelper.Run(input => Rob(input.EntireInput.ToIntArray()).ToString());
}
}
}
| mit | C# | |
22bcf2cddc2db7d1f1ebd4c1e67efd904efcb937 | add ForwardingApp unit tests | johnbeisner/cli,dasMulli/cli,ravimeda/cli,livarcocc/cli-1,svick/cli,dasMulli/cli,blackdwarf/cli,blackdwarf/cli,ravimeda/cli,ravimeda/cli,EdwardBlair/cli,blackdwarf/cli,svick/cli,EdwardBlair/cli,livarcocc/cli-1,svick/cli,livarcocc/cli-1,dasMulli/cli,Faizan2304/cli,harshjain2/cli,johnbeisner/cli,harshjain2/cli,EdwardBlair/cli,harshjain2/cli,johnbeisner/cli,Faizan2304/cli,Faizan2304/cli,blackdwarf/cli | test/dotnet-msbuild.Tests/GivenForwardingApp.cs | test/dotnet-msbuild.Tests/GivenForwardingApp.cs | using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using FluentAssertions;
using Microsoft.DotNet.Tools.Test.Utilities;
namespace Microsoft.DotNet.Cli
{
public class GivenForwardingApp
{
[WindowsOnlyFact]
public void DotnetExeIsExecuted()
{
new ForwardingApp("<apppath>", new string[0])
.GetProcessStartInfo().FileName.Should().Be("dotnet.exe");
}
[NonWindowsOnlyFact]
public void DotnetIsExecuted()
{
new ForwardingApp("<apppath>", new string[0])
.GetProcessStartInfo().FileName.Should().Be("dotnet");
}
[Fact]
public void ItForwardsArgs()
{
new ForwardingApp("<apppath>", new string[] { "one", "two", "three" })
.GetProcessStartInfo().Arguments.Should().Be("exec <apppath> one two three");
}
[Fact]
public void ItAddsDepsFileArg()
{
new ForwardingApp("<apppath>", new string[] { "<arg>" }, depsFile: "<deps-file>")
.GetProcessStartInfo().Arguments.Should().Be("exec --depsfile <deps-file> <apppath> <arg>");
}
[Fact]
public void ItAddsRuntimeConfigArg()
{
new ForwardingApp("<apppath>", new string[] { "<arg>" }, runtimeConfig: "<runtime-config>")
.GetProcessStartInfo().Arguments.Should().Be("exec --runtimeconfig <runtime-config> <apppath> <arg>");
}
[Fact]
public void ItAddsAdditionalProbingPathArg()
{
new ForwardingApp("<apppath>", new string[] { "<arg>" }, additionalProbingPath: "<additionalprobingpath>")
.GetProcessStartInfo().Arguments.Should().Be("exec --additionalprobingpath <additionalprobingpath> <apppath> <arg>");
}
[Fact]
public void ItQuotesArgsWithSpaces()
{
new ForwardingApp("<apppath>", new string[] { "a b c" })
.GetProcessStartInfo().Arguments.Should().Be("exec <apppath> \"a b c\"");
}
[Fact]
public void ItEscapesArgs()
{
new ForwardingApp("<apppath>", new string[] { "a\"b\"c" })
.GetProcessStartInfo().Arguments.Should().Be("exec <apppath> a\\\"b\\\"c");
}
[Fact]
public void ItSetsEnvironmentalVariables()
{
var startInfo = new ForwardingApp("<apppath>", new string[0], environmentVariables: new Dictionary<string, string>
{
{ "env1", "env1value" },
{ "env2", "env2value" }
})
.GetProcessStartInfo();
startInfo.EnvironmentVariables["env1"].Should().Be("env1value");
startInfo.EnvironmentVariables["env2"].Should().Be("env2value");
}
}
}
| mit | C# | |
2dd88f73d980b292409f003dcf68e38ea1578050 | Create DLV.cs | etormadiv/njRAT_0.7d_Stub_ReverseEngineering | j_csharp/OK/DLV.cs | j_csharp/OK/DLV.cs | //Reversed by Etor Madiv
public static void DLV(string n)
{
try
{
F.Registry.CurrentUser.OpenSubKey(System.String.Concat("Software\\", RG), true).DeleteValue(n);
}
catch(Exception)
{
}
}
| unlicense | C# | |
486d7b4dfdf6a5b23075af0999f788a742764c1e | Fix log FieldValueFactorModifier | elastic/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net | src/Nest/QueryDsl/Compound/FunctionScore/Functions/FieldValue/FieldValueFactorModifier.cs | src/Nest/QueryDsl/Compound/FunctionScore/Functions/FieldValue/FieldValueFactorModifier.cs | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Nest
{
[JsonConverter(typeof(StringEnumConverter))]
public enum FieldValueFactorModifier
{
[EnumMember(Value = "none")]
None,
[EnumMember(Value = "log")]
Log,
[EnumMember(Value = "log1p")]
Log1P,
[EnumMember(Value = "log2p")]
Log2P,
[EnumMember(Value = "ln")]
Ln,
[EnumMember(Value = "ln1p")]
Ln1P,
[EnumMember(Value = "ln2p")]
Ln2P,
[EnumMember(Value = "square")]
Square,
[EnumMember(Value = "sqrt")]
SquareRoot,
[EnumMember(Value = "reciprocal")]
Reciprocal
}
} | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Nest
{
[JsonConverter(typeof(StringEnumConverter))]
public enum FieldValueFactorModifier
{
[EnumMember(Value = "none")]
None,
[EnumMember(Value = "count")]
Log,
[EnumMember(Value = "log1p")]
Log1P,
[EnumMember(Value = "log2p")]
Log2P,
[EnumMember(Value = "ln")]
Ln,
[EnumMember(Value = "ln1p")]
Ln1P,
[EnumMember(Value = "ln2p")]
Ln2P,
[EnumMember(Value = "square")]
Square,
[EnumMember(Value = "sqrt")]
SquareRoot,
[EnumMember(Value = "reciprocal")]
Reciprocal
}
} | apache-2.0 | C# |
b5bc31ca46a633fa28eb34cfee85adb10e7babe8 | Fix for updating sources. | cube-soft/Cube.Core,cube-soft/Cube.Core | Components/Messenger.cs | Components/Messenger.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 GalaSoft.MvvmLight.Messaging;
namespace Cube.Xui
{
/* --------------------------------------------------------------------- */
///
/// MessengerOperator
///
/// <summary>
/// Messenger の拡張用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
public static class MessengerOperator
{
/* ----------------------------------------------------------------- */
///
/// Send
///
/// <summary>
/// 既定のメッセージを送信します。
/// </summary>
///
/// <param name="src">Messenger オブジェクト</param>
///
/// <remarks>
/// Messenger は型で判別しているため、不要な場合でもメッセージ
/// オブジェクトを送信する必要がある。Send 拡張メソッドは、
/// 型を指定すると既定のオブジェクトを送信する。
/// </remarks>
///
/* ----------------------------------------------------------------- */
public static void Send<T>(this IMessenger src) where T : new() => src.Send(new T());
}
}
| apache-2.0 | C# | |
9736b9daf942c407fc380bf7e848104d7ffcc24a | work on Hebb Neuron | Boshchuk/neural_network | HebbNeuron/HebbNeuron/HebbNeuron.cs | HebbNeuron/HebbNeuron/HebbNeuron.cs | using System.Collections.Generic;
using System.Linq;
namespace HebbNeuron
{
public class HebbNeuron
{
public int Weight1 { get; set; }
public int Weight2 { get; set; }
public int Threshold { get; set; }
/// <summary>
/// Demostrate work of Neoron
/// </summary>
/// <param name="samples">Sample data</param>
public void Test(IEnumerable<int> samples)
{
var sampleA = samples.ToArray();
int y = 0;
for (int i = 0; i < sampleA.Length; i++)
{
var weightedSum = Weight1 * sampleA[0] +
Weight2 * sampleA[1] +
Threshold;
if (weightedSum > 0)
{
y = 1;
}
else
{
y = -1;
}
}
System.Console.WriteLine(string.Format("({0}, {1}): {2}", sampleA[0], sampleA[1]), y);
}
}
} | unlicense | C# | |
04820694f9e54888046809d882693155d688fc43 | Add game view | feliwir/openSage,feliwir/openSage | src/OpenSage.Game/Diagnostics/GameView.cs | src/OpenSage.Game/Diagnostics/GameView.cs | using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using OpenSage.Input;
using OpenSage.Mathematics;
using Veldrid;
namespace OpenSage.Diagnostics
{
internal sealed class GameView : DiagnosticView
{
public override string DisplayName { get; } = "Game View";
public override bool Closable { get; } = false;
public GameView(DiagnosticViewContext context)
: base(context)
{
}
protected override void DrawOverride(ref bool isGameViewFocused)
{
var windowPos = ImGui.GetCursorScreenPos();
var availableSize = ImGui.GetContentRegionAvail();
availableSize.Y -= ImGui.GetTextLineHeightWithSpacing();
Game.Panel.EnsureFrame(
new Mathematics.Rectangle(
(int) windowPos.X,
(int) windowPos.Y,
(int) availableSize.X,
(int) availableSize.Y));
var inputMessages = TranslateInputMessages(Game.Window.MessageQueue);
Game.Tick(inputMessages);
var imagePointer = ImGuiRenderer.GetOrCreateImGuiBinding(
Game.GraphicsDevice.ResourceFactory,
Game.Panel.Framebuffer.ColorTargets[0].Target);
if (ImGui.ImageButton(
imagePointer,
availableSize,
GetTopLeftUV(),
GetBottomRightUV(),
0,
Vector4.Zero,
Vector4.One))
{
isGameViewFocused = true;
}
if (isGameViewFocused)
{
ImGui.TextColored(
new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
"Press [ESC] to unfocus the game view.");
}
else
{
ImGui.Text("Click in the game view to capture mouse input.");
}
}
private IEnumerable<InputMessage> TranslateInputMessages(IEnumerable<InputMessage> inputMessages)
{
foreach (var message in inputMessages)
{
var windowPos = Game.Panel.Frame.Location;
Point2D getPositionInPanel()
{
var pos = message.Value.MousePosition;
pos = new Point2D(pos.X - windowPos.X, pos.Y - windowPos.Y);
return pos;
}
var translatedMessage = message;
switch (message.MessageType)
{
case InputMessageType.MouseLeftButtonDown:
case InputMessageType.MouseLeftButtonUp:
case InputMessageType.MouseMiddleButtonDown:
case InputMessageType.MouseMiddleButtonUp:
case InputMessageType.MouseRightButtonDown:
case InputMessageType.MouseRightButtonUp:
translatedMessage = InputMessage.CreateMouseButton(
message.MessageType,
getPositionInPanel());
break;
case InputMessageType.MouseMove:
translatedMessage = InputMessage.CreateMouseMove(
getPositionInPanel());
break;
}
yield return translatedMessage;
}
}
}
}
| mit | C# | |
b4cd40c4447bb3aabc073072565b6b10cc198d86 | Fix build | CatenaLogic/RepositoryCleaner | src/RepositoryCleaner.Tests/DummyFacts.cs | src/RepositoryCleaner.Tests/DummyFacts.cs | namespace RepositoryCleaner.Tests
{
using NUnit.Framework;
[TestFixture]
public class DummyFacts
{
[Test]
public void DummyTest()
{
}
}
}
| mit | C# | |
17ba3f01a8073ccbd513bc99a5c27d3925c28e20 | Transform function | gjulianm/Ocell | Library/IEnumerableExtension.cs | Library/IEnumerableExtension.cs | using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
namespace Ocell.Library
{
public static class IEnumerableExtension
{
public static IEnumerable<TTransform> Transform<TTransform, TSource>(this IEnumerable<TSource> list, Func<TSource, TTransform> transformer)
{
foreach (var item in list)
yield return transformer.Invoke(item);
}
}
}
| mpl-2.0 | C# | |
1d8a28b2d7b4e2f848fa91ab697740c0ca212286 | implement command line invoking | quwahara/Nana | NanaLib/ILASM/ILASMRunner.cs | NanaLib/ILASM/ILASMRunner.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Nana.ILASM
{
public class ILASMRunner
{
public string ILASMpath;
public void DetectILASM()
{
if (ILASMpath == null)
{
ILASMpath = Environment.GetEnvironmentVariable(@"NANA_ILASM_PATH");
}
if (ILASMpath == null)
{
string l = Path.DirectorySeparatorChar.ToString();
string systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
string netfwdir = systemRoot + l + @"Microsoft.NET\Framework\v2.0.50727";
ILASMpath = netfwdir + l + @"ilasm.exe";
}
if (false == File.Exists(ILASMpath))
{
throw new Exception("Could not detect ilasm.exe. You can set ilasm.exe path to environment variable 'NANA_ILASM_PATH'. Detected path:" + ILASMpath);
}
}
public int Run(string srcpath)
{
Process p;
p = new Process();
p.StartInfo.FileName = ILASMpath;
p.StartInfo.Arguments = srcpath;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived);
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.CancelErrorRead();
p.CancelOutputRead();
return p.ExitCode;
}
void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.Error.WriteLine(e.Data);
}
}
}
| mit | C# | |
2ad5244ba60387f8909b6ae732608388a9ee62bf | Test really committed. | iskiselev/JSIL,iskiselev/JSIL,hach-que/JSIL,iskiselev/JSIL,hach-que/JSIL,FUSEEProjectTeam/JSIL,hach-que/JSIL,iskiselev/JSIL,FUSEEProjectTeam/JSIL,sq/JSIL,sq/JSIL,FUSEEProjectTeam/JSIL,hach-que/JSIL,sq/JSIL,iskiselev/JSIL,FUSEEProjectTeam/JSIL,FUSEEProjectTeam/JSIL,sq/JSIL,hach-que/JSIL,sq/JSIL | Tests/SimpleTestCases/StructHashCode.cs | Tests/SimpleTestCases/StructHashCode.cs | using System;
using System.Collections.Generic;
public static class Program {
public static void Main (string[] args)
{
var s1 = new Pair<int, int>(1, 1);
var s2 = new Pair<int, int>(1, 1);
var s3 = new Pair<int, int>(1, 2);
var obj1 = new ClassWithCustomHashCode(1);
var obj2 = new ClassWithCustomHashCode(2);
var s4 = new Pair<int, object>(1, obj1);
var s5 = new Pair<int, object>(1, obj1);
var s6 = new Pair<int, object>(1, obj2);
var s7 = new Pair<int, object>(1, obj2);
var s8 = new Pair<int, object>(1, null);
var s9 = new Pair<int, object>(1, null);
Console.WriteLine(s1.GetHashCode() == s2.GetHashCode() ? "true" : "false");
Console.WriteLine(s1.GetHashCode() == s3.GetHashCode() ? "true" : "false");
Console.WriteLine(s4.GetHashCode() == s5.GetHashCode() ? "true" : "false");
Console.WriteLine(s4.GetHashCode() == s6.GetHashCode() ? "true" : "false");
Console.WriteLine(s4.GetHashCode() == s8.GetHashCode() ? "true" : "false");
Console.WriteLine(s6.GetHashCode() == s7.GetHashCode() ? "true" : "false");
Console.WriteLine(s8.GetHashCode() == s9.GetHashCode() ? "true" : "false");
}
}
public class ClassWithCustomHashCode
{
private int _hashCode;
public ClassWithCustomHashCode(int hashCode)
{
_hashCode = hashCode;
}
public override int GetHashCode()
{
return _hashCode;
}
}
public struct Pair<T, K>
{
private T _f1;
private K _f2;
public Pair(T f1, K f2)
{
_f1 = f1;
_f2 = f2;
}
} | mit | C# | |
86bde4b6b253e87fd92ae8026878a4a5128f35cf | Use the correct icon for osu!direct in the toolbar | ZLima12/osu,peppy/osu,johnneijzen/osu,Drezi126/osu,NeoAdonis/osu,NeoAdonis/osu,johnneijzen/osu,naoey/osu,smoogipoo/osu,DrabWeb/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,Frontear/osuKyzer,smoogipoo/osu,Nabile-Rahmani/osu,ppy/osu,Damnae/osu,UselessToucan/osu,naoey/osu,smoogipooo/osu,ppy/osu,DrabWeb/osu,2yangk23/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,2yangk23/osu,ppy/osu,naoey/osu,peppy/osu | osu.Game/Overlays/Toolbar/ToolbarDirectButton.cs | osu.Game/Overlays/Toolbar/ToolbarDirectButton.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Game.Graphics;
namespace osu.Game.Overlays.Toolbar
{
internal class ToolbarDirectButton : ToolbarOverlayToggleButton
{
public ToolbarDirectButton()
{
SetIcon(FontAwesome.fa_osu_chevron_down_o);
}
[BackgroundDependencyLoader]
private void load(DirectOverlay direct)
{
StateContainer = direct;
}
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Game.Graphics;
namespace osu.Game.Overlays.Toolbar
{
internal class ToolbarDirectButton : ToolbarOverlayToggleButton
{
public ToolbarDirectButton()
{
SetIcon(FontAwesome.fa_download);
}
[BackgroundDependencyLoader]
private void load(DirectOverlay direct)
{
StateContainer = direct;
}
}
} | mit | C# |
9714c160b21425a5da8ee38602f34df4e1597aa4 | Add TokenController | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.WebUI/Controllers/TokenController.cs | src/Diploms.WebUI/Controllers/TokenController.cs | using Diploms.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Diploms.Dto.Login;
using Diploms.WebUI.Authentication;
namespace Diploms.Controllers
{
[Route("api/[controller]")]
public class TokenController : Controller
{
private readonly JwtIssuerOptions _jwtOptions;
private readonly JsonSerializerSettings _serializerSettings;
private readonly ITokenService _tokenService;
public TokenController(IOptions<JwtIssuerOptions> jwtOptions, ITokenService service)
{
this._tokenService = service;
this._jwtOptions = jwtOptions.Value;
service.ThrowIfInvalidOptions(_jwtOptions);
_serializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
}
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] LoginDto user)
{
return await _tokenService.IssueToken(user, _jwtOptions, _serializerSettings);
}
[HttpPost("refresh")]
public async Task<IActionResult> Refresh([FromBody] string token)
{
return await _tokenService.RefreshToken(token, _jwtOptions, _serializerSettings);
}
}
} | mit | C# | |
9482ca4335f382e5686ff7aeb588b75bdedd964c | Add kind of database | xin9le/DeclarativeSql | src/DeclarativeSql/DbKind.cs | src/DeclarativeSql/DbKind.cs | namespace DeclarativeSql
{
/// <summary>
/// Represents kind of database.
/// </summary>
public enum DbKind
{
/// <summary>
/// SQL Server
/// </summary>
SqlServer = 0,
/// <summary>
/// MySQL / Amazon Aurora / MariaDB
/// </summary>
MySql,
/// <summary>
/// SQLite
/// </summary>
Sqlite,
/// <summary>
/// PostgreSQL
/// </summary>
PostgreSql,
/// <summary>
/// Oracle
/// </summary>
Oracle,
}
}
| mit | C# | |
54a4847b637eececf463da14c698d027d0848877 | Create MichaelMilitoni.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/MichaelMilitoni.cs | src/Firehose.Web/Authors/MichaelMilitoni.cs | mit | C# | ||
e022fbb75064bff6e59ada83491f523791731cdb | Add extension for 'GetAll' | pardahlman/akeneo-csharp | Akeneo/Extensions/AkeneoClientExtension.cs | Akeneo/Extensions/AkeneoClientExtension.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Akeneo.Client;
using Akeneo.Model;
namespace Akeneo.Extensions
{
public static class AkeneoClientExtensions
{
public static Task<List<TModel>> GetAllAsync<TModel>(this IAkeneoClient client, int limit = 10, CancellationToken ct = default(CancellationToken)) where TModel : ModelBase
{
return client.GetAllAsync<TModel>(null, limit, ct);
}
public static async Task<List<TModel>> GetAllAsync<TModel>(this IAkeneoClient client, string parentCode, int limit = 10, CancellationToken ct = default(CancellationToken)) where TModel : ModelBase
{
var result = new List<TModel>();
var page = 1;
bool hasMore = false;
do
{
var pagination = await client.GetManyAsync<TModel>(parentCode, page, limit, ct: ct);
result.AddRange(pagination.GetItems());
hasMore = pagination.Links.ContainsKey("next");
page++;
} while (hasMore);
return result;
}
}
}
| mit | C# | |
94fc1231ce8e6143779905896239e88a9eff748f | Fix merge error | AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS | src/Package/Impl/Documentation/OpenDocumentationCommand.cs | src/Package/Impl/Documentation/OpenDocumentationCommand.cs | using System;
using System.Diagnostics;
using Microsoft.VisualStudio.R.Package.Commands;
namespace Microsoft.VisualStudio.R.Package.Documentation {
internal class OpenDocumentationCommand : PackageCommand {
private string _url;
public OpenDocumentationCommand(Guid group, int id, string url) :
base(group, id) {
_url = url;
}
protected override void SetStatus() {
Enabled = true;
}
protected override void Handle() {
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = true;
psi.FileName = _url;
Process.Start(psi);
}
}
}
| using System;
<<<<<<< HEAD
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
=======
using System.Diagnostics;
>>>>>>> e8f84d926731d276426348f7abea135faeefadda
using Microsoft.VisualStudio.R.Package.Commands;
namespace Microsoft.VisualStudio.R.Package.Documentation {
internal class OpenDocumentationCommand : PackageCommand {
private string _url;
public OpenDocumentationCommand(Guid group, int id, string url) :
base(group, id) {
_url = url;
}
<<<<<<< HEAD
internal override void SetStatus() {
Enabled = true;
}
internal override void Handle() {
=======
protected override void SetStatus() {
Enabled = true;
}
protected override void Handle() {
>>>>>>> e8f84d926731d276426348f7abea135faeefadda
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = true;
psi.FileName = _url;
Process.Start(psi);
}
}
}
| mit | C# |
12e5bf232bec6b77c85a49f1fc00193d6b87bf19 | Verify BST property | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | ElementsOfProgrammingInterviews/BinaryTrees/bst_property.cs | ElementsOfProgrammingInterviews/BinaryTrees/bst_property.cs | using System;
using System.Collections.Generic;
using System.Linq;
class Node {
public int Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
class Program {
static Node Fill(int low, int high) {
if (low > high) {
return null;
}
int mid = low + (high - low) / 2;
return new Node { Value = mid,
Left = Fill(low, mid - 1),
Right = Fill(mid + 1, high) };
}
static IEnumerable<Node> Inorder(Node root) {
Stack<Node> stack = new Stack<Node>();
while (stack.Any() || root != null) {
if (root == null) {
root = stack.Pop();
yield return root;
root = root.Right;
} else {
stack.Push(root);
root = root.Left;
}
}
}
static bool IsBst(Node root, int low, int high) {
return root == null || (low <= root.Value && root.Value <= high &&
IsBst(root.Left, low, root.Value) &&
IsBst(root.Right, root.Value, high));
}
static void Main() {
Node root = Fill(1, 10);
Console.WriteLine(String.Join(",", Inorder(root).Select(x => x.Value)));
Console.WriteLine(IsBst(root, int.MinValue, int.MaxValue));
root.Value = 0;
Console.WriteLine(IsBst(root, int.MinValue, int.MaxValue));
}
}
| mit | C# | |
364d932c5cbd0dfd1108b187f493c79102f8102e | Create CursorBehavior.cs | brenpolley/leapmotion-cursorBehaviour | CursorBehavior.cs | CursorBehavior.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CursorBehavior : MonoBehaviour {
public int _tickNumber; //number of 'ticks' surrounding the cursor
public GameObject _tickTemplate; //tick Sprite
public float _disatnceMin; //minimum distance from objects
public float _distanceMax; //maximum distance from objects
private List<GameObject> _ticks; //list of all tick objects
private List<Vector3> _tickPos; //list of positions of all tick objects
// Use this for initialization
void Start () {
_ticks = new List<GameObject>();
_tickPos = new List<Vector3>();
expandTicks();
}
// Update is called once per frame
void Update () {
castRayForward();
}
void castRayForward(){
/*
* cast a ray directly forward from the cursor
* if the ray collides with an object resize the distance between the ticks and the cursor
*/
float _distance;
Debug.DrawRay(transform.position, transform.forward * 2f, Color.blue);
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.forward, out hit, 100.0f)){
_distance = hit.distance;
for(int i = 0; i < _tickNumber; i++){
_ticks[i].renderer.enabled = true;
}
resizeCursor(_distance);
}
// if nothing is in front of the cursor, hide the ticks
else{
for(int i = 0; i < _tickNumber; i++){
_ticks[i].renderer.enabled = false;
}
}
}
//adjust the distance between the ticks and the cursor
void resizeCursor(float _dis){
//clamp the distance to fall within defined distance range
float _newDistance = Mathf.Clamp(_dis, _disatnceMin, _distanceMax);
//calculate the ratio of the distance to the distance range
float _range = _distanceMax - _disatnceMin;
float _percentDis = Mathf.Clamp(_newDistance/_range, 0f, 1.0f);
//adjust the x and y positions of each tick based on the ratio calculated above
for(int i = 0; i < _tickNumber; i++){
Vector3 _moveTo = new Vector3(_tickPos[i].x * _percentDis, _tickPos[i].y *_percentDis, _tickPos[i].z);
_ticks[i].transform.localPosition = _moveTo;
}
}
//distribute the tick objects around the cursor
void expandTicks(){
//for each tick object...
for (int j = 0; j < _tickNumber; j++){
//...calcucate evenly distributed points around cursor
float i = (j * 1.0f) / _tickNumber;
float _angle = i * Mathf.PI * 2f;
float _degrees = _angle * Mathf.Rad2Deg;
float _x = Mathf.Sin(_degrees * Mathf.Deg2Rad);
float _y = Mathf.Cos(_degrees * Mathf.Deg2Rad);
Vector3 _pos = new Vector3(_x, _y, 0) + transform.position;
//clone tick object and position it
GameObject _tick = Instantiate(_tickTemplate, _pos, Quaternion.identity) as GameObject;
_tick.transform.parent = transform;
//hide tick object
_tick.renderer.enabled = false;
//rotate tick object to point toward cursor
_tick.transform.Rotate(-Vector3.forward, _degrees);
//add tick object and position to lists
_ticks.Add(_tick);
_tickPos.Add(_tick.transform.localPosition);
}
}
}
| mit | C# | |
8c95f5277784141df67861794e8bb3f026613502 | Add missing core tests. | McNeight/SharpZipLib | tests/Core/Core.cs | tests/Core/Core.cs | using NUnit.Framework;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Tests.Core
{
[TestFixture]
public class Core
{
[Test]
public void FilterQuoting()
{
string[] filters = NameFilter.SplitQuoted("");
Assert.AreEqual(0, filters.Length);
filters = NameFilter.SplitQuoted(";;;");
Assert.AreEqual(4, filters.Length);
foreach(string filter in filters) {
Assert.AreEqual("", filter);
}
filters = NameFilter.SplitQuoted("a;a;a;a;a");
Assert.AreEqual(5, filters.Length);
foreach (string filter in filters) {
Assert.AreEqual("a", filter);
}
filters = NameFilter.SplitQuoted(@"a\;;a\;;a\;;a\;;a\;");
Assert.AreEqual(5, filters.Length);
foreach (string filter in filters) {
Assert.AreEqual("a;", filter);
}
}
[Test]
public void ValidFilter()
{
Assert.IsTrue(NameFilter.IsValidFilterExpression("a"));
Assert.IsFalse(NameFilter.IsValidFilterExpression(@"\,)"));
}
}
}
| mit | C# | |
010323605a42593493ab6c4af9c6e1f9f1f90d8c | Bring TimedExpiryGlyphStore back from the dead | EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/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# | |
fdb5608581b538c9d16c0801b7b16600645d0516 | Add test fixture for secret splitting | 0culus/ElectronicCash | ElectronicCash.Tests/SecretSplittingTests.cs | ElectronicCash.Tests/SecretSplittingTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] _message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] _randBytes = Helpers.GetRandomBytes(Helpers.GetString(_message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(_message, _randBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(_message));
}
}
}
| mit | C# | |
c0d1e02606a1bb8c26254ba785a6ff8880c94d66 | Create Main.cs | neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers | POH7/SantaFuku/Main.cs | POH7/SantaFuku/Main.cs | // Try POH
// author: Leonardone @ NEETSDKASU
using System;
using System.Collections.Generic;
using System.Linq;
public class Solver
{
public static void Main()
{
int x, y, z, n; Ib(Gis(), out x, out y, out z, out n);
var xs = Arr(0, x).ToList();
var ys = Arr(0, y).ToList();
foreach (var da in NGis(n))
{
(da[0] == 0 ? xs : ys).Add(da[1]);
}
xs.Sort();
ys.Sort();
x = xs.Zip(xs.Skip(1), (a, b) => b - a).Min();
y = ys.Zip(ys.Skip(1), (a, b) => b - a).Min();
Console.WriteLine(x * y * z);
}
///////////////////////////////////////////////////////////////////
static string Gs() { return Console.ReadLine(); }
static int Gi() { return int.Parse(Gs()); }
static long Gl() { return long.Parse(Gs()); }
static string[] Gss() { return Gs().Split(" ".ToCharArray()); }
static int[] Gis() { return Gss().Select( int.Parse ).ToArray(); }
static T[] NGt<T>(int n, Func<T> f) { return Enumerable.Range(0, n).Select( _ => f() ).ToArray(); }
static string[] NGs(int n) { return NGt(n, Gs); }
static int[] NGi(int n) { return NGt(n, Gi); }
static string[][] NGss(int n) { return NGt(n, Gss); }
static int[][] NGis(int n) { return NGt(n, Gis); }
static void Ib(int[] a, out int v1, out int v2) { v1 = a[0]; v2 = a[1]; }
static void Ib(int[] a, out int v1, out int v2, out int v3) { v1 = a[0]; v2 = a[1]; v3 = a[2]; }
static void Ib(int[] a, out int v1, out int v2, out int v3, out int v4) { v1 = a[0]; v2 = a[1]; v3 = a[2]; v4 = a[3]; }
static T[] Arr<T>(params T[] p) { return p; }
///////////////////////////////////////////////////////////////////
}
| mit | C# | |
8421f795a45c62844484f555135dc74dcd386de2 | Add ArrayPointer class for creating pointers to fixed-size arrays | whampson/bft-spec,whampson/cascara | Src/WHampson.Cascara/Types/ArrayPointer.cs | Src/WHampson.Cascara/Types/ArrayPointer.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.Collections;
namespace WHampson.Cascara.Types
{
public class ArrayPointer<T> : Pointer<T>, IEnumerable
where T : struct, ICascaraType
{
public ArrayPointer(IntPtr addr, int count)
: base(addr)
{
Count = count;
}
private int Count
{
get;
}
public IEnumerator GetEnumerator()
{
return new ArrayPointerEnumerator<T>(this);
}
private class ArrayPointerEnumerator<T> : IEnumerator
where T : struct, ICascaraType
{
private ArrayPointer<T> arr;
private int position;
public ArrayPointerEnumerator(ArrayPointer<T> arr)
{
this.arr = arr;
Reset();
}
public object Current
{
get { return arr[position]; }
}
public bool MoveNext()
{
position++;
return position < arr.Count;
}
public void Reset()
{
position = -1;
}
}
}
}
| mit | C# | |
99fb5ec03f0562003dc2528c739e4a00002d3d39 | Add a test which shows that the ProjectFile works immutable | mfalda/FAKE,brianary/FAKE,ArturDorochowicz/FAKE,MiloszKrajewski/FAKE,MiloszKrajewski/FAKE,daniel-chambers/FAKE,featuresnap/FAKE,xavierzwirtz/FAKE,mglodack/FAKE,pmcvtm/FAKE,JonCanning/FAKE,mfalda/FAKE,NaseUkolyCZ/FAKE,JonCanning/FAKE,naveensrinivasan/FAKE,yonglehou/FAKE,tpetricek/FAKE,brianary/FAKE,pacificIT/FAKE,Kazark/FAKE,MiloszKrajewski/FAKE,beeker/FAKE,dlsteuer/FAKE,tpetricek/FAKE,ovu/FAKE,dmorgan3405/FAKE,xavierzwirtz/FAKE,NaseUkolyCZ/FAKE,darrelmiller/FAKE,satsuper/FAKE,darrelmiller/FAKE,darrelmiller/FAKE,neoeinstein/FAKE,gareth-evans/FAKE,pmcvtm/FAKE,modulexcite/FAKE,warnergodfrey/FAKE,modulexcite/FAKE,jayp33/FAKE,mat-mcloughlin/FAKE,dlsteuer/FAKE,mglodack/FAKE,ilkerde/FAKE,molinch/FAKE,haithemaraissia/FAKE,rflechner/FAKE,mglodack/FAKE,molinch/FAKE,MiloszKrajewski/FAKE,mglodack/FAKE,satsuper/FAKE,mat-mcloughlin/FAKE,jayp33/FAKE,rflechner/FAKE,haithemaraissia/FAKE,hitesh97/FAKE,beeker/FAKE,dmorgan3405/FAKE,Kazark/FAKE,ArturDorochowicz/FAKE,dmorgan3405/FAKE,daniel-chambers/FAKE,naveensrinivasan/FAKE,neoeinstein/FAKE,mfalda/FAKE,featuresnap/FAKE,ilkerde/FAKE,neoeinstein/FAKE,dmorgan3405/FAKE,rflechner/FAKE,hitesh97/FAKE,tpetricek/FAKE,pacificIT/FAKE,RMCKirby/FAKE,wooga/FAKE,warnergodfrey/FAKE,daniel-chambers/FAKE,jayp33/FAKE,ilkerde/FAKE,rflechner/FAKE,hitesh97/FAKE,ctaggart/FAKE,leflings/FAKE,philipcpresley/FAKE,pmcvtm/FAKE,naveensrinivasan/FAKE,mat-mcloughlin/FAKE,yonglehou/FAKE,ArturDorochowicz/FAKE,ovu/FAKE,naveensrinivasan/FAKE,philipcpresley/FAKE,MichalDepta/FAKE,philipcpresley/FAKE,warnergodfrey/FAKE,leflings/FAKE,brianary/FAKE,wooga/FAKE,ovu/FAKE,haithemaraissia/FAKE,haithemaraissia/FAKE,pmcvtm/FAKE,wooga/FAKE,yonglehou/FAKE,NaseUkolyCZ/FAKE,warnergodfrey/FAKE,beeker/FAKE,leflings/FAKE,pacificIT/FAKE,dlsteuer/FAKE,pacificIT/FAKE,ctaggart/FAKE,modulexcite/FAKE,gareth-evans/FAKE,tpetricek/FAKE,ovu/FAKE,beeker/FAKE,mat-mcloughlin/FAKE,xavierzwirtz/FAKE,daniel-chambers/FAKE,NaseUkolyCZ/FAKE,Kazark/FAKE,satsuper/FAKE,featuresnap/FAKE,ctaggart/FAKE,modulexcite/FAKE,neoeinstein/FAKE,wooga/FAKE,hitesh97/FAKE,leflings/FAKE,MichalDepta/FAKE,ctaggart/FAKE,darrelmiller/FAKE,JonCanning/FAKE,brianary/FAKE,mfalda/FAKE,dlsteuer/FAKE,JonCanning/FAKE,philipcpresley/FAKE,xavierzwirtz/FAKE,gareth-evans/FAKE,featuresnap/FAKE,molinch/FAKE,Kazark/FAKE,yonglehou/FAKE,RMCKirby/FAKE,MichalDepta/FAKE,jayp33/FAKE,gareth-evans/FAKE,satsuper/FAKE,RMCKirby/FAKE,ArturDorochowicz/FAKE,RMCKirby/FAKE,ilkerde/FAKE,MichalDepta/FAKE,molinch/FAKE | src/test/Test.FAKECore/ProjectSystemSpecs.cs | src/test/Test.FAKECore/ProjectSystemSpecs.cs | using Fake.MSBuild;
using Machine.Specifications;
namespace Test.FAKECore
{
public class when_checking_for_files
{
static ProjectSystem.ProjectFile _project;
Because of = () => _project = ProjectSystem.ProjectFile.FromFile("ProjectTestFiles/FakeLib.fsproj");
It should_find_the_SpecsRemovement_helper_in_the_MSBuild_folder = () =>
_project.Files.ShouldContain("MSBuild\\SpecsRemovement.fs");
It should_find_the_SpecsRemover_which_has_some_strange_xml = () =>
_project.Files.ShouldContain("MSBuild\\SpecsRemover.fs");
It should_find_the_semver_helper = () =>
_project.Files.ShouldContain("SemVerHelper.fs");
It should_not_find_the_SpecsRemovement_helper = () =>
_project.Files.ShouldNotContain("SpecsRemovement.fs");
It should_not_find_the_badadadum_helper = () =>
_project.Files.ShouldNotContain("badadadumHelper.fs");
}
public class when_adding_files
{
static ProjectSystem.ProjectFile _project;
static ProjectSystem.ProjectFile _project2;
Establish context = () => _project = ProjectSystem.ProjectFile.FromFile("ProjectTestFiles/FakeLib.fsproj");
Because of = () => _project2 = _project.AddFile("badadadumHelper.fs");
It should_find_the_SpecsRemovement_helper_in_the_MSBuild_folder = () =>
_project2.Files.ShouldContain("MSBuild\\SpecsRemovement.fs");
It should_find_the_badadadum_helper = () =>
_project2.Files.ShouldContain("badadadumHelper.fs");
It should_work_immutable = () =>
_project.Files.ShouldNotContain("badadadumHelper.fs");
}
} | using Fake.MSBuild;
using Machine.Specifications;
namespace Test.FAKECore
{
public class when_checking_for_files
{
static ProjectSystem.ProjectFile _project;
Because of = () => _project = ProjectSystem.ProjectFile.FromFile("ProjectTestFiles/FakeLib.fsproj");
It should_find_the_SpecsRemovement_helper_in_the_MSBuild_folder = () =>
_project.Files.ShouldContain("MSBuild\\SpecsRemovement.fs");
It should_find_the_SpecsRemover_which_has_some_strange_xml = () =>
_project.Files.ShouldContain("MSBuild\\SpecsRemover.fs");
It should_find_the_semver_helper = () =>
_project.Files.ShouldContain("SemVerHelper.fs");
It should_not_find_the_SpecsRemovement_helper = () =>
_project.Files.ShouldNotContain("SpecsRemovement.fs");
It should_not_find_the_badadadum_helper = () =>
_project.Files.ShouldNotContain("badadadumHelper.fs");
}
public class when_adding_files
{
static ProjectSystem.ProjectFile _project;
Establish context = () => _project = ProjectSystem.ProjectFile.FromFile("ProjectTestFiles/FakeLib.fsproj");
Because of = () => _project = _project.AddFile("badadadumHelper.fs");
It should_find_the_SpecsRemovement_helper_in_the_MSBuild_folder = () =>
_project.Files.ShouldContain("MSBuild\\SpecsRemovement.fs");
It should_find_the_badadadum_helper = () =>
_project.Files.ShouldContain("badadadumHelper.fs");
}
} | apache-2.0 | C# |
8bfceaf0be3cde0dc48eeddd4c8ff0bd91965382 | add e50 with lydia.cs | neutronest/eulerproject-douby,neutronest/eulerproject-douby,neutronest/eulerproject-douby,neutronest/eulerproject-douby,neutronest/eulerproject-douby | e50/50.cs | e50/50.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Lydia_么么要玉潇
{
public class Test
{
static void Main()
{
long ans = 0;
init();
for (int i = 0; i < primes_sum.Count; i++) {
for (int j = 0; j < i; j++) {
long v = primes_sum[i] - primes_sum[j];
if (isPrime(v)) {
ans = Math.Max(ans, v);
}
}
}
Console.WriteLine(ans);
}
static void init() {
primes = new List<int>();
primes_sum = new List<long>();
for (int i = 2; i < SIZE; i++) {
if (isPrime(i)) {
primes.Add(i);
}
}
long sum = 0;
foreach (int prime in primes) {
sum += prime;
if (sum > SIZE) {
break;
}
primes_sum.Add(sum);
}
}
static bool isPrime(long v) {
for (long i = 2; i <= Math.Sqrt(v) + 1; i++) {
if (v % i == 0) {
return false;
}
}
return true;
}
const int SIZE = 1000000;
static List<int> primes;
static List<long> primes_sum;
}
}
| mit | C# | |
f5ead292ce9310ee2c21bba29b3adf6753462338 | Add a logging effect to debug | Kerbas-ad-astra/SmokeScreen,sarbian/SmokeScreen | DebugEffect.cs | DebugEffect.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SmokeScreen
{
[EffectDefinition("DEBUG_EFFECT")]
class DebugEffect : EffectBehaviour
{
public override void OnEvent()
{
Print(effectName.PadRight(16) + "OnEvent single -------------------------------------------------------");
}
private float lastPower = -1;
public override void OnEvent(float power)
{
if (Math.Abs(lastPower - power) > 0.01f)
{
lastPower = power;
Print(effectName.PadRight(16) + " " + instanceName + "OnEvent pow = " + power.ToString("F2"));
}
}
public override void OnInitialize()
{
Print("OnInitialize");
}
public override void OnLoad(ConfigNode node)
{
Print("OnLoad");
}
public override void OnSave(ConfigNode node)
{
Print("OnSave");
}
private static void Print(String s)
{
print("[SmokeScreen DebugEffect] " + s);
}
}
}
| bsd-2-clause | C# | |
55dad6cf67eaa7113c967b33563890dbca422ce6 | Add Clip | Schlechtwetterfront/snipp | Models/Clip.cs | Models/Clip.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Windows;
namespace clipman.Models
{
public class Clip : INotifyPropertyChanged
{
public String Content
{
get;
set;
}
public DateTime Created
{
get;
set;
}
public String Title
{
get { return Content.Trim(); }
}
public Clip()
{
}
public Clip(String content)
{
Content = content;
Created = DateTime.Now;
}
public static Clip Capture()
{
return new Clip(Clipboard.GetText());
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
}
| apache-2.0 | C# | |
9a14741856974be767a6f266b431aad9d2487412 | Create StarScythe.cs | Minesap/TheMinepack | Items/StarScythe.cs | Items/StarScythe.cs | using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
using Minepack.Items;
namespace Minepack.Items.Weapons {
public class StarScythe : ModItem
{
public override void SetDefaults()
{
item.name = "StarScythe";
item.width = 60;
item.damage = 87;
item.melee = true;
item.useAnimation = 21;
item.useStyle = 1;
item.useTime = 21;
item.useTurn = true;
item.knockBack = 8f;
item.UseSound = SoundID.Item71;
item.autoReuse = true;
item.height = 56;
item.maxStack = 1;
item.toolTip = "Shoots a starry scythe";
item.value = 1350000;
item.rare = 10;
item.shoot = mod.ProjectileType("StarScythe");
item.shootSpeed = 12f;
}
}}
| mit | C# | |
b85b382203042826e02b22ebb0b419fd6da64ca6 | add the serializer interface scaffold | bolorundurowb/vCardLib | vCardLib/Interfaces/ISerializer.cs | vCardLib/Interfaces/ISerializer.cs | using System.Collections.Generic;
using vCardLib.Models;
namespace vCardLib.Interfaces
{
public interface ISerializer
{
string AddPhoneNumbers(IEnumerable<PhoneNumber> phoneNumbers);
string AddEmailAddresses(IEnumerable<EmailAddress> emailAddresses);
string AddAddresses(IEnumerable<Address> addresses);
string AddPhotos(IEnumerable<Photo> photos);
string AddExpertises(IEnumerable<Expertise> expertises);
string AddHobbies(IEnumerable<Hobby> hobbies);
string AddInterests(IEnumerable<Interest> interests);
}
} | mit | C# | |
97d11781c58b9e4c2da4f5cd0781afd5de70a368 | Create BasicAuthMiddleware.cs | am-creations/Owin.BasicAuthenticationMiddleware | BasicAuthMiddleware.cs | BasicAuthMiddleware.cs | using Microsoft.Owin;
using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace AMC.Owin
{
public class BasicAuthMiddleware : OwinMiddleware
{
public const string AuthMode = "Basic";
public BasicAuthMiddleware(OwinMiddleware next)
: base(next)
{
}
public BasicAuthMiddleware(OwinMiddleware next, Func<string, string, Task<IIdentity>> validationCallback)
: this(next)
{
IndentityVerificationCallback = validationCallback;
}
Func<string, string, Task<IIdentity>> IndentityVerificationCallback
{
get;
set;
}
public override async Task Invoke(IOwinContext context)
{
var request = context.Request;
var response = context.Response;
response.OnSendingHeaders(o =>
{
var rResp = (IOwinResponse)o;
if (rResp.StatusCode == 401)
{
rResp.Headers["WWW-Authenticate"] = AuthMode;
}
}, response);
var header = request.Headers["Authorization"];
if (!string.IsNullOrWhiteSpace(header))
{
var authHeader = AuthenticationHeaderValue.Parse(header);
if (AuthMode.Equals(authHeader.Scheme, StringComparison.OrdinalIgnoreCase))
{
var parameter = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter));
var parts = parameter.Split(':');
var userName = parts[0];
var password = parts[1];
if (IndentityVerificationCallback != null)
{
var identity = await IndentityVerificationCallback.Invoke(userName, password);
if (identity != null)
{
request.User = new ClaimsPrincipal(identity);
}
}
}
}
await Next.Invoke(context);
}
}
}
| apache-2.0 | C# | |
9e95eb963155adff3a79f15eccd7706d54f4e01e | fix build | tom-scott/Unified_Data_API_Client_DotNet,sportingsolutions/SS.Integration.UnifiedDataAPIClient.DotNet,ChrisL89/SS.Integration.UnifiedDataAPIClient.DotNet,sportingsolutions/SS.Integration.UnifiedDataAPIClient.DotNet | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Spin.TradingServices.C2E")]
[assembly: AssemblyCompany("Sporting Index Ltd.")]
[assembly: AssemblyCopyright("Copyright (c) Sporting Index Ltd. 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;;
[assembly: AssemblyProduct("Spin.TradingServices.C2E")]
[assembly: AssemblyCompany("Sporting Index Ltd.")]
[assembly: AssemblyCopyright("Copyright (c) Sporting Index Ltd. 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
656b2754c1d659f06e2f122d8d80631539f751ef | Create ViewArticle.aspx.cs | liamning/BlueCrossStaffPortal | ViewArticle.aspx.cs | ViewArticle.aspx.cs | using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ViewArticle : System.Web.UI.Page
{
public System.Text.StringBuilder imageContent = new System.Text.StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ID"] == null) return;
int ID = Convert.ToInt32(Request.QueryString["ID"]);
News article = new News();
NewsInfo articleInfo = article.getArticle(ID);
labHeadline.InnerText = articleInfo.Headline;
labSummary.InnerText = articleInfo.Summary;
labContent.InnerHtml = articleInfo.Content;
//show the image in the gallery
List<ImageInfo> articleImages = articleInfo.getImageList();
if(articleImages.Count >= 3)
imgSummary.ImageUrl = "Service/ImageService.aspx?ID=" + articleImages[2].ID.ToString();
ImageInfo imageinfo;
for (int i = 3; i < articleImages.Count; i++)
{
imageinfo = articleImages[i];
imageContent.Append("<div><a href='Service/ImageService.aspx?ID=");
imageContent.Append(imageinfo.ID.ToString());
imageContent.Append("' title='");
imageContent.Append(imageinfo.Description);
imageContent.Append("'><img src='Service/PreviewImageService.aspx?maxLength=199&ID=");
imageContent.Append(imageinfo.ID.ToString());
imageContent.Append("'");
imageContent.Append(" /></a><p>");
imageContent.Append(imageinfo.Description);
imageContent.Append("</p></div>");
}
//show the attachment in the news details page
List<FileInfo> articleAttachment = articleInfo.getFileList();
System.Text.StringBuilder attachmentContent = new System.Text.StringBuilder();
FileInfo fileInfo;
for (int i = 0; i < articleAttachment.Count; i++)
{
if (i == 0)
{
attachmentContent.Append("<br/><p><u><b>Attachment: </b></u></p>");
}
fileInfo = articleAttachment[i];
attachmentContent.Append("<a href='Service/FileService.aspx?ID=");
attachmentContent.Append(fileInfo.ID);
attachmentContent.Append("'>");
attachmentContent.Append(fileInfo.Description);
attachmentContent.Append("</a><br/>");
}
labAttachment.InnerHtml = attachmentContent.ToString();
File file = new File();
System.Text.StringBuilder newsLetters = file.getQuickLinkList(2);
divNewsLetters.InnerHtml = newsLetters.ToString();
this.ControlDataBind();
}
protected void ControlDataBind()
{
System.Data.DataTable EventType = SystemPara.getSystemPara("SuggestionType");
foreach (System.Data.DataRow row in EventType.Rows)
{
this.comSuggestionType.Items.Add(new ListItem(row["Description"].ToString(), row["ID"].ToString()));
}
}
}
| bsd-2-clause | C# | |
3a4c0043baa6b4e8bb1be779ff37832d232d8564 | Create main.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | LoginPasswordUtil/C-Sharp-Version/main.cs | LoginPasswordUtil/C-Sharp-Version/main.cs | using System.Diagnostics.Process;
namespace ACLoginUtil{
}
| apache-2.0 | C# | |
9ab21acbc939ba89a996595a8be484c8fe8dcaaa | Add unit test | huysentruitw/pem-utils | tests/DerConverter.Tests/Asn/DerAsnUtcTime.cs | tests/DerConverter.Tests/Asn/DerAsnUtcTime.cs | using DerConverter.Asn;
using NUnit.Framework;
using System.Linq;
namespace DerConverter.Tests.Asn
{
[TestFixture]
public class DerAsnUtcTimeTests
{
[Test]
public void DerAsnUtcTime_Parse_ShouldDecodeCorrectly()
{
var data = new byte[]
{
0x17, 0x0D,
0x31, 0x33, 0x30, 0x32, 0x30, 0x37, 0x32, 0x31, 0x34, 0x38, 0x34, 0x37, 0x5A
};
var type = DerAsnType.Parse(data);
Assert.That(type is DerAsnUtcTime, Is.True);
Assert.That(type.Value, Is.EqualTo(data.Skip(2).ToArray()));
}
[Test]
public void DerAsnUtcTime_GetBytes_ShouldEncodeCorrectly()
{
var type = new DerAsnUtcTime(new byte[] { 0x31, 0x33, 0x30, 0x32, 0x30, 0x37, 0x32, 0x31, 0x34, 0x38, 0x34, 0x37, 0x5A });
var data = type.GetBytes();
Assert.That((DerAsnTypeTag)data[0], Is.EqualTo(DerAsnTypeTag.UtcTime));
Assert.That(data[1], Is.EqualTo(0xD));
Assert.That(data.Skip(2).ToArray(), Is.EqualTo(new byte[] { 0x31, 0x33, 0x30, 0x32, 0x30, 0x37, 0x32, 0x31, 0x34, 0x38, 0x34, 0x37, 0x5A }));
}
}
}
| apache-2.0 | C# | |
cc46fa3cb7af47dc869c0f8aeb03268072fc2b55 | Create ServiceProviderCollection.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/ServiceProviderCollection.cs | TIKSN.Framework.IntegrationTests/ServiceProviderCollection.cs | using Xunit;
namespace TIKSN.Framework.IntegrationTests
{
[CollectionDefinition("ServiceProviderCollection")]
public class ServiceProviderCollection : ICollectionFixture<ServiceProviderFixture>
{
}
} | mit | C# | |
a5026cf1aae8d465499a5281402a716c5c7c7215 | Add tests for F.Map | farity/farity | Farity.Tests/MapTests.cs | Farity.Tests/MapTests.cs | using System.Linq;
using Xunit;
namespace Farity.Tests
{
public class MapTests
{
[Fact]
public void MapExecutesFunctionsForAllElementsInTheList()
{
var expected = new[] {"1", "2", "3", "4", "5"};
var source = new[] { 1, 2, 3, 4, 5 };
var actual = F.Map(x => x.ToString(), source);
Assert.Equal(expected, actual);
}
}
} | mit | C# | |
19d0360bd98b3845594c29da092e609cac8a7c64 | Create ConsoleControlChar.cs | cheong00/MSDNDemos,cheong00/MSDNDemos,cheong00/MSDNDemos,cheong00/MSDNDemos | ConsoleControlChar/ConsoleControlChar.cs | ConsoleControlChar/ConsoleControlChar.cs | using System;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleControlChar
{
/// <summary>
/// Examle on how to print non-printable character in Console application,
/// also how to change font in Console application.
///
/// This example will need /unsafe option to compile.
/// Just use "csc /unsafe ConsoleControlChar.cs" to compile this project
/// </summary>
class Program
{
#region Support change of font
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool GetCurrentConsoleFontEx(
IntPtr consoleOutput,
bool maximumWindow,
ref CONSOLE_FONT_INFO_EX lpConsoleCurrentFontEx);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetCurrentConsoleFontEx(
IntPtr consoleOutput,
bool maximumWindow,
CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
private const int STD_OUTPUT_HANDLE = -11;
private const int TMPF_TRUETYPE = 4;
private const int LF_FACESIZE = 32;
private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[StructLayout(LayoutKind.Sequential)]
internal struct COORD
{
internal short X;
internal short Y;
internal COORD(short x, short y)
{
X = x;
Y = y;
}
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CONSOLE_FONT_INFO_EX
{
internal uint cbSize;
internal uint nFont;
internal COORD dwFontSize;
internal int FontFamily;
internal int FontWeight;
internal fixed char FaceName[LF_FACESIZE];
}
private unsafe static void SetConsoleFont(string fontName)
{
IntPtr hnd = GetStdHandle(STD_OUTPUT_HANDLE);
if (hnd != INVALID_HANDLE_VALUE)
{
CONSOLE_FONT_INFO_EX info = new CONSOLE_FONT_INFO_EX();
info.cbSize = (uint)Marshal.SizeOf(info);
bool tt = false;
// First determine whether there's already a TrueType font.
if (GetCurrentConsoleFontEx(hnd, false, ref info))
{
tt = (info.FontFamily & TMPF_TRUETYPE) == TMPF_TRUETYPE;
if (tt)
{
Console.WriteLine("The console already is using a TrueType font.");
return;
}
// Set console font to Lucida Console.
CONSOLE_FONT_INFO_EX newInfo = new CONSOLE_FONT_INFO_EX();
newInfo.cbSize = (uint)Marshal.SizeOf(newInfo);
newInfo.FontFamily = TMPF_TRUETYPE;
IntPtr ptr = new IntPtr(newInfo.FaceName);
Marshal.Copy(fontName.ToCharArray(), 0, ptr, fontName.Length);
// Get some settings from current font.
newInfo.dwFontSize = new COORD(info.dwFontSize.X, info.dwFontSize.Y);
newInfo.FontWeight = info.FontWeight;
SetCurrentConsoleFontEx(hnd, false, newInfo);
}
}
}
#endregion Support change of font
static void Main(string[] args)
{
SetConsoleFont("Arial Unicode MS");
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(Char.ConvertFromUtf32(0x2400));
Console.ReadKey();
}
}
}
| mit | C# | |
cc5b44e46681eb6b46c6c0fc1109cd5b64dd108b | Add test scene | ppy/osu,smoogipoo/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,johnneijzen/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,2yangk23/osu | osu.Game.Rulesets.Osu.Tests/Mods/TestSceneOsuModDoubleTime.cs | osu.Game.Rulesets.Osu.Tests/Mods/TestSceneOsuModDoubleTime.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.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Osu.Tests.Mods
{
public class TestSceneOsuModDoubleTime : ModSandboxTestScene
{
public TestSceneOsuModDoubleTime()
: base(new OsuRuleset())
{
}
[TestCase(0.5)]
[TestCase(1.01)]
[TestCase(1.5)]
[TestCase(2)]
[TestCase(5)]
public void TestDefaultRate(double rate) => CreateModTest(new ModTestCaseData("1.5x", new OsuModDoubleTime { SpeedChange = { Value = rate } })
{
PassCondition = () => ((ScoreAccessibleTestPlayer)Player).ScoreProcessor.JudgedHits >= 2
});
protected override TestPlayer CreateReplayPlayer(Score score) => new ScoreAccessibleTestPlayer(score);
private class ScoreAccessibleTestPlayer : TestPlayer
{
public new ScoreProcessor ScoreProcessor => base.ScoreProcessor;
public ScoreAccessibleTestPlayer(Score score)
: base(score)
{
}
}
}
}
| mit | C# | |
3105736cda04f0662c35f607576b46b3dc9f0f7f | make base class for boss and mob viewmodels | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Controls/Npc/NpcViewModel.cs | TCC.Core/Controls/Npc/NpcViewModel.cs | using System;
using System.Windows.Threading;
using TCC.Data.NPCs;
namespace TCC.Controls.NPCs
{
public class NpcViewModel : TSPropertyChanged
{
public const uint Delay = 5000;
protected readonly DispatcherTimer _deleteTimer;
public event Action Disposed;
public event Action HpFactorChanged;
public NPC NPC { get; set; }
public NpcViewModel(NPC npc)
{
NPC = npc;
_deleteTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(Delay) };
_deleteTimer.Tick += (s, ev) =>
{
_deleteTimer.Stop();
InvokeDisposed();
};
}
protected void InvokeDisposed() => Disposed?.Invoke();
protected void InvokeHpChanged() => HpFactorChanged?.Invoke();
}
}
| mit | C# | |
576bbd8023e58a354cdde7d1dc393f2382716237 | Create IPrivacyAudit.cs | saturn72/saturn72 | src/Core/Saturn72.Core/Audit/IPrivacyAudit.cs | src/Core/Saturn72.Core/Audit/IPrivacyAudit.cs | using System;
namespace Saturn72.Core.Audit
{
public interface IPrivacyAudit
{
bool IsPrivate { get; set; }
DateTime? SetToPrivateOnUtc { get; set; }
long? SetToPrivateByUserId { get; set; }
}
}
| mit | C# | |
ae999b440afacfedefb2a322a07b727752cf140d | Create Problem26.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem26.cs | Problems/Problem26.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem26
{
private int upper = 1000;
private int maxPrecision = 3000;
private Sieve s = new Sieve(1000);
private int RecurringCycleSize(string number)
{
while (number.Length > 2 && number[number.Length - 1] == '0' && number[number.Length - 2] == '0')
{
// Remove Irrelevant Zeroes
number = number.Substring(0, number.Length - 1);
}
if (number.Length > 20) // Number has Cycle
{
int min_cycle_size = maxPrecision;
for (int i = 0; i < number.Length - 1 && min_cycle_size > 1; i++)
{
for (int size = (number.Length-i) / 2; size >= 1; size--)
{
string cycleBase = number.Substring(i, size);
bool allEqual = true;
for (int x = 1; x < (number.Length - i) / size; x++)
{
allEqual &= cycleBase == number.Substring(i + (x * size), size);
if (!allEqual) break;
}
if(allEqual)
{
if (size < min_cycle_size)
{
min_cycle_size = size;
}
}
}
}
return min_cycle_size;
}
else
{
return 0;
}
}
public string Run()
{
int max = 0;
int maxI = 0;
BigInteger baseNumber = new BigInteger(10000000000);
for (int bse = 1; bse < maxPrecision; bse++)
{
// Add 1 zero precision per time around
baseNumber *= 10;
}
for (int i = upper - (upper/10); i <= upper; i++)
{
if (s.prime[i])
{
BigInteger val = baseNumber / i;
string str = val.ToString("G");
int cycle_size = RecurringCycleSize(str);
if (cycle_size < maxPrecision && cycle_size > max)
{
max = cycle_size;
maxI = i;
Console.WriteLine("1/" + i.ToString() + ": " + cycle_size.ToString());
}
}
}
return "1/" + maxI.ToString() + " (" + max.ToString() + ") = " + (1m/maxI).ToString();
}
}
}
| mit | C# | |
59b62753ad40dd0fbce520f89b07c3a09f9f09e0 | Implement test for client login. | moegirlwiki/Kaleidoscope | test/ActionLibraryTest/Actions/ClientLoginTest.cs | test/ActionLibraryTest/Actions/ClientLoginTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moegirlpedia.MediaWikiInterop.Actions;
using Moegirlpedia.MediaWikiInterop.Actions.Models;
using Moegirlpedia.MediaWikiInterop.Actions.QueryProviders;
using Moegirlpedia.MediaWikiInterop.Primitives.DependencyInjection;
using System;
using System.Threading.Tasks;
namespace ActionLibraryTest.Actions
{
[TestClass]
public class ClientLoginTest
{
private const string ApiEndpoint = "https://zh.moegirl.org/api.php";
[TestMethod]
public async Task TestClientLogin()
{
var apiFactory = ApiConnectionFactory.CreateConnection(ApiEndpoint);
using (var apiConnection = apiFactory.CreateConnection())
using (var session = apiConnection.CreateSession())
{
// First, token
var queryResponse = await apiConnection.CreateAction<QueryAction>().RunActionAsync(config =>
{
config.AddQueryProvider(new TokenQueryProvider
{
Types = TokenQueryProvider.TokenTypes.Login
});
}, session);
var tokenResponse = queryResponse.GetQueryTypedResponse<Tokens>();
Assert.IsNotNull(tokenResponse?.Response?.LoginToken);
// Then, login
var loginResponse = await apiConnection.CreateAction<ClientLoginAction>().RunActionAsync(config =>
{
config.LoginToken = tokenResponse.Response.LoginToken;
config.ReturnUrl = "https://zh.moegirl.org/Mainpage";
config.AddCredential("username", Environment.GetEnvironmentVariable("UT_USERNAME"));
config.AddCredential("password", Environment.GetEnvironmentVariable("UT_PASSWORD"));
}, session);
Assert.AreEqual(ClientLoginResponse.AuthManagerLoginResult.Pass, loginResponse.Status, loginResponse.Message);
}
}
}
}
| mit | C# | |
67d8455bd95c519220c70b17c88338619b75c787 | Add new file userAuth.cpl/Droid/Properties/AssemblyInfo.cs | ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl | userAuth.cpl/Droid/Properties/AssemblyInfo.cs | userAuth.cpl/Droid/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("userAuth.cpl.Droid")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("RonThomas")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# | |
e60fa8b141e10094ade43feeefed7c3fc99f140b | Add unit tests for PaymentLinkClient | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Tests.Unit/Client/PaymentLinkClientTests.cs | Mollie.Tests.Unit/Client/PaymentLinkClientTests.cs | using System;
using System.Globalization;
using System.Net.Http;
using System.Threading.Tasks;
using Mollie.Api.Client;
using Mollie.Api.Models;
using Mollie.Api.Models.List;
using Mollie.Api.Models.PaymentLink.Request;
using Mollie.Api.Models.PaymentLink.Response;
using NUnit.Framework;
using RichardSzalay.MockHttp;
namespace Mollie.Tests.Unit.Client {
[TestFixture]
public class PaymentLinkClientTests : BaseClientTests {
private const decimal DefaultPaymentAmount = 50;
private const string DefaultPaymentLinkId = "pl_4Y0eZitmBnQ6IDoMqZQKh";
private const string DefaultDescription = "A car";
private const string DefaultWebhookUrl = "http://www.mollie.com";
private const string DefaultRedirectUrl = "http://www.mollie.com";
private readonly string defaultPaymentLinkJsonResponse = @$"{{
""resource"": ""payment-link"",
""id"": ""{DefaultPaymentLinkId}"",
""mode"": ""test"",
""profileId"": ""pfl_QkEhN94Ba"",
""createdAt"": ""2021-03-20T09:13:37+00:00"",
""paidAt"": null,
""updatedAt"": null,
""expiresAt"": ""2021-06-06T11:00:00+00:00"",
""amount"": {{
""value"": ""{DefaultPaymentAmount.ToString(CultureInfo.InvariantCulture)}"",
""currency"": ""EUR""
}},
""description"": ""{DefaultDescription}"",
""redirectUrl"": ""{DefaultRedirectUrl}"",
""webhookUrl"": ""{DefaultWebhookUrl}"",
""_links"": {{
""self"": {{
""href"": ""https://api.mollie.com/v2/payment-links/pl_4Y0eZitmBnQ6IDoMqZQKh"",
""type"": ""application/json""
}},
""paymentLink"": {{
""href"": ""https://useplink.com/payment/4Y0eZitmBnQ6IDoMqZQKh/"",
""type"": ""text/html""
}},
""documentation"": {{
""href"": ""https://docs.mollie.com/reference/v2/payment-links-api/create-payment-link"",
""type"": ""text/html""
}}
}}
}}";
[Test]
public async Task CreatePaymentLinkAsync_PaymentLinkWithRequiredParameters_ResponseIsDeserializedInExpectedFormat() {
// Given: we create a payment link request with only the required parameters
PaymentLinkRequest paymentLinkRequest = new PaymentLinkRequest() {
Description = "Test",
Amount = new Amount(Currency.EUR, 50),
WebhookUrl = "http://www.mollie.com",
RedirectUrl = "http://www.mollie.com",
ExpiresAt = DateTime.Now.AddDays(1)
};
var mockHttp = new MockHttpMessageHandler();
mockHttp.When($"{BaseMollieClient.ApiEndPoint}*")
.Respond("application/json", defaultPaymentLinkJsonResponse);
HttpClient httpClient = mockHttp.ToHttpClient();
PaymentLinkClient paymentLinkClient = new PaymentLinkClient("abcde", httpClient);
// When: We send the request
PaymentLinkResponse response = await paymentLinkClient.CreatePaymentLinkAsync(paymentLinkRequest);
// Then
mockHttp.VerifyNoOutstandingExpectation();
VerifyPaymentLinkResponse(response);
}
[Test]
public async Task GetPaymentLinkAsync_ResponseIsDeserializedInExpectedFormat() {
// Given: we retrieve a payment link
var mockHttp = new MockHttpMessageHandler();
mockHttp.When($"{BaseMollieClient.ApiEndPoint}*")
.Respond("application/json", defaultPaymentLinkJsonResponse);
HttpClient httpClient = mockHttp.ToHttpClient();
PaymentLinkClient paymentLinkClient = new PaymentLinkClient("abcde", httpClient);
// When: We send the request
PaymentLinkResponse response = await paymentLinkClient.GetPaymentLinkAsync(DefaultPaymentLinkId);
// Then
mockHttp.VerifyNoOutstandingExpectation();
VerifyPaymentLinkResponse(response);
}
private void VerifyPaymentLinkResponse(PaymentLinkResponse response) {
Assert.AreEqual(DefaultPaymentAmount.ToString(CultureInfo.InvariantCulture), response.Amount.Value);
Assert.AreEqual(DefaultDescription, response.Description);
Assert.AreEqual(DefaultPaymentLinkId, response.Id);
Assert.AreEqual(DefaultRedirectUrl, response.RedirectUrl);
Assert.AreEqual(DefaultWebhookUrl, response.WebhookUrl);
}
}
} | mit | C# | |
719c96e88c0ca25cd044b2afd9f0b4202f36e527 | Update version to 1.0.0.3 | affandar/durabletask,ddobric/durabletask,jasoneilts/durabletask,Azure/durabletask,yonglehou/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.3")]
[assembly: AssemblyFileVersion("1.0.0.3")]
[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.1")]
[assembly: AssemblyFileVersion("1.0.0.2")]
[assembly: InternalsVisibleTo("FrameworkUnitTests")] | apache-2.0 | C# |
af6ff34b4dc44bf38e814870bf2b121e3ab5de65 | Create DateTimeRange.cs | HerrLoesch/ObjectFiller.NET,blmeyers/ObjectFiller.NET,DoubleLinePartners/ObjectFiller.NET,Tynamix/ObjectFiller.NET | ObjectFiller/Plugins/DateTime/DateTimeRange.cs | ObjectFiller/Plugins/DateTime/DateTimeRange.cs | using System;
namespace Tynamix.ObjectFiller
{
public class DateTimeRange : IRandomizerPlugin<DateTime>, IRandomizerPlugin<DateTime?>
{
private readonly DateTime _earliestDate;
private readonly DateTime _latestDate;
public DateTimeRange(DateTime earliestDate)
: this(earliestDate, DateTime.Now)
{
}
public DateTimeRange(DateTime earliestDate, DateTime latestDate)
{
_earliestDate = earliestDate;
_latestDate = latestDate;
}
public DateTime GetValue()
{
int seconds = Random.Next(0, 60);
int minute = Random.Next(0, 60);
int hour = Random.Next(0, 24);
int month = Random.Next(_earliestDate.Month, _latestDate.Month + 1);
int day = Random.Next(_earliestDate.Day, month == 2 && _latestDate.Day > 28 ? 29 : _latestDate.Day);
int year = Random.Next(_earliestDate.Year, _latestDate.Year + 1);
return new DateTime(year, month, day, hour, minute, seconds);
}
DateTime? IRandomizerPlugin<DateTime?>.GetValue()
{
return GetValue();
}
}
}
| mit | C# | |
e17e24e6307590234d98ae86d641b1bec469be9d | Create hideSetColour.cs | Gytaco/RevitAPI,Gytaco/RevitAPI | Macros/CS/Views/hideSetColour.cs | Macros/CS/Views/hideSetColour.cs | /*
This code will hide and set the colours of any elements in yoru active view. There are additional search functionalities
I have left in as tags to query and access objects.
*/
public void hideSetColour()
{
//sets the variable to the current application
Application app = this.Application;
//sets the variable to the current document
Document doc = this.ActiveUIDocument.Document;
//gets the active view
ElementId aview = this.ActiveUIDocument.ActiveView.Id;
#region setup a colour override
/*
//create a new colour
Color color = new Color(150, 200, 200);
//gets the element of the fill pattern solid fill
var fpcoll = from elem in new FilteredElementCollector(doc)
.OfClass(typeof(FillPatternElement))
let type = elem as FillPatternElement
where type.Name == "Solid fill"
select type;
//gets the element id from the element
var fpid = fpcoll.Select(fp => fp.Id).FirstOrDefault();
//set the colour of the projection surface colour and the fill pattern
var col = new OverrideGraphicSettings();
col.SetProjectionFillColor(color);
col.SetProjectionFillPatternId(fpid);
*/
#endregion
#region Linq to get Views by Name
/*
//LINQ query that uses a filtered element collector to get the view by name
var viewget = from elem in new FilteredElementCollector(doc)
.OfClass(typeof(ViewPlan))
let type = elem as ViewPlan
where type.Name == "Level 1"
select type;
//gets the element id of the view
ElementId eid = viewget.Select(view => view.Id).FirstOrDefault();
*/
#endregion
//basic option to use a filter
ICollection<ElementId> fiid = new FilteredElementCollector(doc, aview).OfCategory(BuiltInCategory.OST_Walls)
.WhereElementIsNotElementType().ToElementIds();
#region Linq to get elements by multiple categories
/*
//how to use multiple categories in a filtered collection
ICollection<ElementId> fiid = new FilteredElementCollector(doc, eid)
//applies a logical filter which allows user to add multiple categories
.WherePasses(new LogicalOrFilter(new List<ElementFilter>
{
new ElementCategoryFilter(BuiltInCategory.OST_Walls),
new ElementCategoryFilter(BuiltInCategory.OST_Floors)
}))
.WhereElementIsNotElementType().ToElementIds();
*/
#endregion
#region Linq to get elements by parameter values
/*
//Using LINQ lets the user select objects via a parameter value
var elemget = from elem in new FilteredElementCollector(doc, eid)
.OfClass(typeof(Wall)).WhereElementIsNotElementType()
let type = elem as Wall
where type.Name == "Generic - 300mm"
select type;
ICollection<ElementId> fiid = elemget.Select(elid => elid.Id).ToList();
*/
#endregion
//starts the transaction
using (Transaction t = new Transaction(doc, "Hide Elements"))
{
t.Start();
//uses the GetElement method to get the View
View flrplan = doc.GetElement(aview) as View;
//methods to hide the elements in the view based on their element id's
flrplan.HideElements(fiid);
#region set colour by element override
/*
var leftid = new FilteredElementCollector(doc, aview).WhereElementIsNotElementType().ToElementIds();
//apply the override by element to the remaining visible elements
foreach (ElementId feid in leftid)
{
flrplan.SetElementOverrides(feid, col);
}
*/
#endregion
t.Commit();
}
}
| mit | C# | |
217e32eeeb41e078b200f76e341fdc742065d0dd | Add Composite implementation for Indexers | ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton | src/CK.Glouton.Lucene/CompositeIndexer.cs | src/CK.Glouton.Lucene/CompositeIndexer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CK.Monitoring;
namespace CK.Glouton.Lucene
{
class CompositeIndexer : IIndexer
{
private List<IIndexer> _indexers;
public CompositeIndexer ()
{
_indexers = new List<IIndexer>();
}
public void IndexLog(ILogEntry entry, IReadOnlyDictionary<string, string> clientData)
{
foreach (IIndexer indexer in _indexers) indexer.IndexLog(entry, clientData);
}
public void Add (IIndexer indexer)
{
if(!_indexers.Contains(indexer)) _indexers.Add(indexer);
}
public bool Remove(IIndexer indexer)
{
if( _indexers.Contains( indexer ) )
{
_indexers.Remove( indexer );
return true;
}
return false;
}
}
}
| mit | C# | |
4f79211ac9e4254cf0a04809e0fb68dfe65f7094 | Create Node.cs | GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/ServerStatus | GUI/Node.cs | GUI/Node.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using Aga.Controls.Tree;
namespace OpenHardwareMonitor.GUI {
public class Node {
private TreeModel treeModel;
private Node parent;
private NodeCollection nodes;
private string text;
private Image image;
private bool visible;
private TreeModel RootTreeModel() {
Node node = this;
while (node != null) {
if (node.Model != null)
return node.Model;
node = node.parent;
}
return null;
}
public Node() : this(string.Empty) { }
public Node(string text) {
this.text = text;
this.nodes = new NodeCollection(this);
this.visible = true;
}
public TreeModel Model {
get { return treeModel; }
set { treeModel = value; }
}
public Node Parent {
get { return parent; }
set {
if (value != parent) {
if (parent != null)
parent.nodes.Remove(this);
if (value != null)
value.nodes.Add(this);
}
}
}
public Collection<Node> Nodes {
get { return nodes; }
}
public virtual string Text {
get { return text; }
set {
if (text != value) {
text = value;
}
}
}
public Image Image {
get { return image; }
set {
if (image != value) {
image = value;
}
}
}
public virtual bool IsVisible {
get { return visible; }
set {
if (value != visible) {
visible = value;
TreeModel model = RootTreeModel();
if (model != null && parent != null) {
int index = 0;
for (int i = 0; i < parent.nodes.Count; i++) {
Node node = parent.nodes[i];
if (node == this)
break;
if (node.IsVisible || model.ForceVisible)
index++;
}
if (model.ForceVisible) {
model.OnNodeChanged(parent, index, this);
} else {
if (value)
model.OnNodeInserted(parent, index, this);
else
model.OnNodeRemoved(parent, index, this);
}
}
if (IsVisibleChanged != null)
IsVisibleChanged(this);
}
}
}
public delegate void NodeEventHandler(Node node);
public event NodeEventHandler IsVisibleChanged;
public event NodeEventHandler NodeAdded;
public event NodeEventHandler NodeRemoved;
private class NodeCollection : Collection<Node> {
private Node owner;
public NodeCollection(Node owner) {
this.owner = owner;
}
protected override void ClearItems() {
while (this.Count != 0)
this.RemoveAt(this.Count - 1);
}
protected override void InsertItem(int index, Node item) {
if (item == null)
throw new ArgumentNullException("item");
if (item.parent != owner) {
if (item.parent != null)
item.parent.nodes.Remove(item);
item.parent = owner;
base.InsertItem(index, item);
TreeModel model = owner.RootTreeModel();
if (model != null)
model.OnStructureChanged(owner);
if (owner.NodeAdded != null)
owner.NodeAdded(item);
}
}
protected override void RemoveItem(int index) {
Node item = this[index];
item.parent = null;
base.RemoveItem(index);
TreeModel model = owner.RootTreeModel();
if (model != null)
model.OnStructureChanged(owner);
if (owner.NodeRemoved != null)
owner.NodeRemoved(item);
}
protected override void SetItem(int index, Node item) {
if (item == null)
throw new ArgumentNullException("item");
RemoveAt(index);
InsertItem(index, item);
}
}
}
}
| mit | C# | |
903e3ea1991d77bc6494281458b9fdc96b33a949 | Add a script for check if we are a tank. | TheNoobCompany/WorldQuestTNB | Profiles/Quester/IsTankScript.cs | Profiles/Quester/IsTankScript.cs | switch (ObjectManager.Me.WowSpecialization())
{
case WoWSpecialization.PaladinProtection:
case WoWSpecialization.WarriorProtection:
case WoWSpecialization.MonkBrewmaster:
case WoWSpecialization.DruidGuardian:
case WoWSpecialization.DeathknightBlood:
return true;
default:
return false;
}
// Usage: <ScriptCondition>=IsTankScript.cs</ScriptCondition> | mit | C# | |
d15f002dbda5ed715529c310dd0c308ada31cb57 | Create DailyScraper.cs | aloisdg/DailyScraper | DailyScraper.cs | DailyScraper.cs | using System;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
public class Program
{
public enum CategoryType
{
Other,
Easy,
Intermediate,
Hard
}
public class Item
{
public string Title { get; set; }
public string Link { get; set; }
public DateTime Date { get; set; }
public CategoryType Category { get; set; }
}
public static void Main()
{
const string url = "https://www.reddit.com/r/dailyprogrammer/.rss";
var xdoc = XDocument.Load(url);
var items = from item in xdoc.Descendants("item")
let title = item.Element("title").Value
select new Item
{
Title = title,
Link = item.Element("link").Value,
Date = DateTime.Parse(item.Element("pubDate").Value),
Category = ExtractCategory(title)
};
var sorted = items.OrderBy(x => x.Category);
var array = Split(sorted);
Print(array);
}
private static CategoryType ExtractCategory(string title)
{
var categories = new Dictionary<string, CategoryType>
{
{ "[Easy]", CategoryType.Easy },
{ "[Intermediate]", CategoryType.Intermediate },
{ "[Hard]", CategoryType.Hard }
};
return categories.FirstOrDefault(x => title.Contains(x.Key)).Value;
}
private static void Print(Item[,] array)
{
Console.WriteLine("Other | Easy | Intermediate | Hard ");
Console.WriteLine("------|------|--------------|------");
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
var item = array[i, j];
Console.Write("| " + (item != null ?
string.Format("[{0}]({1})", item.Title, item.Link)
: " "));
}
Console.WriteLine(" |");
}
}
private static Item[,] Split(IEnumerable<Item> items)
{
var splitedItems = items.GroupBy(j => j.Category).ToArray();
var array = new Item[splitedItems.Max(x => x.Count()), splitedItems.Length];
for (var i = 0; i < splitedItems.Length; i++)
for (var j = 0; j < splitedItems.ElementAt(i).Count(); j++)
array[j, i] = splitedItems.ElementAt(i).ElementAt(j);
return array;
}
}
| mit | C# | |
4316f3e4ddb7418def2cf03d8247d2d8f73ad8d9 | add a test for code actions | hal-ler/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,hach-que/omnisharp-roslyn,hitesh97/omnisharp-roslyn,sreal/omnisharp-roslyn,nabychan/omnisharp-roslyn,khellang/omnisharp-roslyn,nabychan/omnisharp-roslyn,hach-que/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,sriramgd/omnisharp-roslyn,jtbm37/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,hitesh97/omnisharp-roslyn,hal-ler/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,sreal/omnisharp-roslyn,khellang/omnisharp-roslyn,sriramgd/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,jtbm37/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,haled/omnisharp-roslyn,haled/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,fishg/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,fishg/omnisharp-roslyn | tests/OmniSharp.Tests/CodeActionsFacts.cs | tests/OmniSharp.Tests/CodeActionsFacts.cs | #if ASPNET50
using System.Collections.Generic;
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Services;
using Xunit;
namespace OmniSharp.Tests
{
public class CodingActionsFacts
{
[Fact]
public async Task Can_get_code_actions()
{
var source =
@"using System;
public class Class1
{
public void Whatever()
{
int$ i = 1;
}
}";
var refactorings = await FindRefactoringsAsync(source);
Assert.Contains("Use 'var' keyword", refactorings);
}
private async Task<IEnumerable<string>> FindRefactoringsAsync(string source)
{
var workspace = TestHelpers.CreateSimpleWorkspace(source);
var controller = new CodeActionController(workspace, new[] { new NRefactoryCodeActionProvider() });
var request = CreateRequest(source);
var response = await controller.GetCodeActions(request);
return response.CodeActions;
}
private CodeActionRequest CreateRequest(string source, string fileName = "dummy.cs")
{
var lineColumn = TestHelpers.GetLineAndColumnFromDollar(source);
return new CodeActionRequest
{
Line = lineColumn.Line,
Column = lineColumn.Column,
FileName = fileName,
Buffer = source.Replace("$", ""),
};
}
}
}
#endif | mit | C# | |
6129b8ca1fae1c35ce44ce97350cc74ba0fae37a | Create Sigmoid.cs | Quadrat1c/OpJinx | Epoch/Network/Sigmoid.cs | Epoch/Network/Sigmoid.cs | using System;
namespace Epoch.Network
{
public static class Sigmoid
{
public static double Output(double x)
{
return x < -45.0 ? 0.0 : x > 45.0 ? 1.0 : 1.0 / (1.0 + Math.Exp(-x));
}
public static double Derivative(double x)
{
return x * (1 - x);
}
}
}
| mit | C# | |
b98529ab920c8767cf1763713f0b52537a7a6d6e | Create Vector3.Lerp.cs | carcarc/unity3d | Vector3.Lerp.cs | Vector3.Lerp.cs | // Smoothly interpolate between the camera's current position and it's target position.
transform.position = Vector3.Lerp (start.position, end.position, Time.deltaTime);
| mit | C# | |
b14a9b65572500861e9082d6310836592b796cce | Create CorrelationID.cs | tiksn/TIKSN-Framework | TIKSN.Core/Integration/Correlation/CorrelationID.cs | TIKSN.Core/Integration/Correlation/CorrelationID.cs | using System;
using System.Linq;
namespace TIKSN.Integration.Correlation
{
/// <summary>
/// Correlation ID
/// </summary>
public struct CorrelationID : IEquatable<CorrelationID>
{
/// <summary>
/// Empty Correlation ID.
/// </summary>
public static readonly CorrelationID Empty = new CorrelationID();
private readonly byte[] _byteArrayRepresentation;
private readonly string _stringRepresentation;
internal CorrelationID(string stringRepresentation, byte[] byteArrayRepresentation)
{
_stringRepresentation = stringRepresentation ?? throw new ArgumentNullException(nameof(stringRepresentation));
_byteArrayRepresentation = byteArrayRepresentation ?? throw new ArgumentNullException(nameof(byteArrayRepresentation));
}
public static implicit operator byte[](CorrelationID correlationId)
{
return correlationId._byteArrayRepresentation;
}
public static implicit operator string(CorrelationID correlationId)
{
return correlationId._stringRepresentation;
}
/// <summary>
/// Indicates whether this instance and a <paramref name="other"/> are equal by their binary representation.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(CorrelationID other)
{
return _byteArrayRepresentation.SequenceEqual(other._byteArrayRepresentation);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj == null || !(obj is CorrelationID))
return false;
var other = (CorrelationID)obj;
return Equals(other);
}
/// <summary>
/// Returns binary representation.
/// </summary>
/// <returns></returns>
public byte[] ToByteArray()
{
return _byteArrayRepresentation;
}
/// <summary>
/// Returns string representation.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _stringRepresentation;
}
}
} | mit | C# | |
535697d2b2aef9ac90e17eaad724de87eee18cf5 | Add tests for LimitResult and OrderBy when splitting request | ZEISS-PiWeb/PiWeb-Api | src/Api.Rest.Tests/HttpClient/Data/DataServiceRestClientTest.cs | src/Api.Rest.Tests/HttpClient/Data/DataServiceRestClientTest.cs | #region copyright
/* * * * * * * * * * * * * * * * * * * * * * * * * */
/* Carl Zeiss Industrielle Messtechnik GmbH */
/* Softwaresystem PiWeb */
/* (c) Carl Zeiss 2021 */
/* * * * * * * * * * * * * * * * * * * * * * * * * */
#endregion
namespace Zeiss.PiWeb.Api.Rest.Tests.HttpClient.Data
{
#region usings
using System;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json;
using NUnit.Framework;
using Zeiss.PiWeb.Api.Rest.Dtos.Data;
using Zeiss.PiWeb.Api.Rest.HttpClient.Data;
#endregion
[TestFixture]
public class DataServiceRestClientTest
{
#region constants
private const int Port = 8081;
#endregion
#region members
private static readonly Uri Uri = new Uri( $"http://localhost:{Port}/" );
#endregion
#region methods
[Test]
public async Task RequestSplit_OrderSpecified_OrderIsCorrect()
{
using var server = WebServer.StartNew( Port );
//maxUriLength of 80 leads request splitting per part uuid
using var client = new DataServiceRestClient( Uri, 80 );
//attribute 999 is our reference order which we expect in our result
var firstMeasurementSet = new[]
{
new SimpleMeasurementDto
{ Attributes = new[] { new AttributeDto( 5, 3 ), new AttributeDto( 55, 10 ), new AttributeDto( 999, 2 ) } },
new SimpleMeasurementDto
{ Attributes = new[] { new AttributeDto( 5, 1 ), new AttributeDto( 55, 99 ), new AttributeDto( 999, 0 ) } },
new SimpleMeasurementDto
{ Attributes = new[] { new AttributeDto( 5, 6 ), new AttributeDto( 55, 99 ), new AttributeDto( 999, 5 ) } }
};
var secondMeasurementSet = new[]
{
new SimpleMeasurementDto
{ Attributes = new[] { new AttributeDto( 5, 4 ), new AttributeDto( 55, 99 ), new AttributeDto( 999, 4 ) } },
new SimpleMeasurementDto
{ Attributes = new[] { new AttributeDto( 5, 2 ), new AttributeDto( 55, 99 ), new AttributeDto( 999, 1 ) } },
new SimpleMeasurementDto
{ Attributes = new[] { new AttributeDto( 5, 3 ), new AttributeDto( 55, 20 ), new AttributeDto( 999, 3 ) } }
};
server.RegisterReponse( "/DataServiceRest/measurements?partUuids=%7B11111111-1111-1111-1111-111111111111%7D&order=5%20Asc%2C55%20Asc", JsonConvert.SerializeObject( firstMeasurementSet ) );
server.RegisterReponse( "/DataServiceRest/measurements?partUuids=%7B22222222-2222-2222-2222-222222222222%7D&order=5%20Asc%2C55%20Asc", JsonConvert.SerializeObject( secondMeasurementSet ) );
var result = await client.GetMeasurements( filter: new MeasurementFilterAttributesDto
{
PartUuids = new[] { Guid.Parse( "11111111-1111-1111-1111-111111111111" ), Guid.Parse( "22222222-2222-2222-2222-222222222222" ) },
OrderBy = new[] { new OrderDto( 5, OrderDirectionDto.Asc, EntityDto.Measurement ), new OrderDto( 55, OrderDirectionDto.Asc, EntityDto.Measurement ) }
} );
//check that the order is correct according to our attribute 999
var index = 0;
foreach( var measurement in result )
{
measurement.Attributes.FirstOrDefault( a => a.Key == 999 )?.Value.Should().Be( index.ToString() );
index++;
}
}
[Test]
public async Task RequestSplit_LimitResultSpecified_LimitCorrect()
{
using var server = WebServer.StartNew( Port );
//maxUriLength of 80 leads request splitting per part uuid
using var client = new DataServiceRestClient( Uri, 80 );
var firstMeasurementSet = new[] { new SimpleMeasurementDto(), new SimpleMeasurementDto(), new SimpleMeasurementDto() };
var secondMeasurementSet = new[] { new SimpleMeasurementDto(), new SimpleMeasurementDto(), new SimpleMeasurementDto() };
server.RegisterReponse( "/DataServiceRest/measurements?partUuids=%7B11111111-1111-1111-1111-111111111111%7D&limitResult=5&order=4%20Desc", JsonConvert.SerializeObject( firstMeasurementSet ) );
server.RegisterReponse( "/DataServiceRest/measurements?partUuids=%7B22222222-2222-2222-2222-222222222222%7D&limitResult=5&order=4%20Desc", JsonConvert.SerializeObject( secondMeasurementSet ) );
var result = await client.GetMeasurements( filter: new MeasurementFilterAttributesDto
{
PartUuids = new[] { Guid.Parse( "11111111-1111-1111-1111-111111111111" ), Guid.Parse( "22222222-2222-2222-2222-222222222222" ) },
LimitResult = 5
} );
result.Length.Should().Be( 5 );
}
#endregion
}
} | bsd-3-clause | C# | |
0c7202fb1d1dd4ff6ac7b79c1171ea5473f3cd52 | add missing file | commonsensesoftware/Its.Cqrs,commonsensesoftware/Its.Cqrs,commonsensesoftware/Its.Cqrs | Domain/ExceptionExtensions.cs | Domain/ExceptionExtensions.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using System.Reflection;
namespace Microsoft.Its.Domain
{
internal static class ExceptionExtensions
{
private static readonly Type[] uninterestingExceptionTypes =
{
typeof (AggregateException),
typeof (TargetInvocationException)
};
public static Exception FindInterestingException(this Exception exception)
{
while (uninterestingExceptionTypes.Contains(exception.GetType()) &&
exception.InnerException != null)
{
exception = exception.InnerException;
}
return exception;
}
}
} | mit | C# | |
40d0d65fcddf6ebe369500f9d6957539ef511af9 | Create task_1_3_8_2.cs | AndrewTurlanov/ANdrew | task_1_3_8_2.cs | task_1_3_8_2.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("Введите пароль");
string UserPassword = Console.ReadLine();
string password = "pas2017";
int i = 1;
while (UserPassword != password)
{
i++;
if (i <= 5)
{
Console.WriteLine("Пароль неверный, попробуйте еще раз");
UserPassword = Console.ReadLine();
}
else
{
Console.WriteLine("Все попытки исчерпаны");
break;
}
}
if (UserPassword == password)
{
Console.WriteLine("Вы увидели секретное сообщение");
}
}
}
}
| apache-2.0 | C# | |
78760937b8faf83fc936123d3d073751eace8b54 | Add missing file | felipebz/ndapi | Ndapi/PropertyAttribute.cs | Ndapi/PropertyAttribute.cs | using System;
namespace Ndapi
{
internal sealed class PropertyAttribute : Attribute
{
internal int PropertyId { get; }
public PropertyAttribute(int propertyId)
{
PropertyId = propertyId;
}
}
} | mit | C# | |
eec9735ec9587e0255a632e8559e1987d8e78e65 | Add Polyline helper | tom-englert/TomsToolbox | TomsToolbox.Wpf/XamlExtensions/Polyline.cs | TomsToolbox.Wpf/XamlExtensions/Polyline.cs | namespace TomsToolbox.Wpf.XamlExtensions
{
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
/// <summary>
/// Extensions to properly display a <see cref="System.Windows.Shapes.Polyline"/> in the coordinates of the containing canvas.
/// It normalizes the points and aligns the polyline so the coordinates of the points match the coordinates of the canvas.
/// </summary>
public static class Polyline
{
/// <summary>
/// Gets the data points in the canvas coordinates.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The data points</returns>
[AttachedPropertyBrowsableForType(typeof(System.Windows.Shapes.Polyline))]
public static ICollection<Point> GetDataPoints(DependencyObject element)
{
return (ICollection<Point>)element.GetValue(DataPointsProperty);
}
/// <summary>
/// Sets the data points in the canvas coordinates.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="value">The value.</param>
public static void SetDataPoints(DependencyObject element, ICollection<Point> value)
{
element.SetValue(DataPointsProperty, value);
}
/// <summary>
/// Identifies the <see cref="P:TomsToolbox.Wpf.XamlExtensions.Polyline.DataPoints"/> attached property
/// </summary>
/// <AttachedPropertyComments>
/// <summary>
/// A helper property to normalize the data points and align the <see cref="System.Windows.Shapes.Polyline"/> in the containing canvas, so the data
/// points match the coordinates of the canvas.
/// </summary>
/// </AttachedPropertyComments>
public static readonly DependencyProperty DataPointsProperty = DependencyProperty.RegisterAttached(
"DataPoints", typeof(ICollection<Point>), typeof(Polyline),
new FrameworkPropertyMetadata(default(ICollection<Point>), Points_Changed));
private static void Points_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
if (!(sender is System.Windows.Shapes.Polyline target))
return;
if (!(args.NewValue is ICollection<Point> points))
{
target.Points = null;
return;
}
var bounds = points.GetBoundingRect();
var offset = (Vector)bounds.TopLeft;
target.Points = new PointCollection(points.Select(item => item - offset));
target.Stretch = Stretch.Fill;
Canvas.SetTop(target, bounds.Top);
Canvas.SetLeft(target, bounds.Left);
Canvas.SetRight(target, bounds.Right);
Canvas.SetBottom(target, bounds.Bottom);
}
/// <summary>
/// Gets the bounding rectangle of all points.
/// </summary>
/// <param name="points">The points.</param>
/// <returns>The bounding rectangle.</returns>
public static Rect GetBoundingRect(this ICollection<Point> points)
{
if (!points.Any())
return Rect.Empty;
var xMin = points.Min(p => p.X);
var xMax = points.Max(p => p.X);
var yMin = points.Min(p => p.Y);
var yMax = points.Max(p => p.Y);
return new Rect(xMin, yMin, xMax - xMin, yMax - yMin);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.