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 |
|---|---|---|---|---|---|---|---|---|
9f7a756a06f420325e9a92d861f4ff3f20dea520 | Add trace class. | honestegg/cassette,andrewdavey/cassette,damiensawyer/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,damiensawyer/cassette,damiensawyer/cassette,honestegg/cassette | src/Cassette/Trace.cs | src/Cassette/Trace.cs | using System.Diagnostics;
namespace Cassette
{
static class Trace
{
public static readonly TraceSource Source = new TraceSource("Cassette");
}
}
| mit | C# | |
3f8977e362a5dc76981fafd1e9fb039d8fc443d2 | Introduce IUtterance interface. | AIWolfSharp/AIWolf_NET | AIWolfLib/IUtterance.cs | AIWolfLib/IUtterance.cs | //
// IUtterance.cs
//
// Copyright (c) 2018 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// 発話クラスが実装すべきプロパティとメソッド
/// </summary>
#else
/// <summary>
/// Abstract utterance class.
/// </summary>
#endif
public interface IUtterance
{
#if JHELP
/// <summary>
/// 発話のインデックス
/// </summary>
#else
/// <summary>
/// The index number of this utterance.
/// </summary>
#endif
int Idx { get; }
#if JHELP
/// <summary>
/// 発話日
/// </summary>
#else
/// <summary>
/// The day of this utterance.
/// </summary>
#endif
int Day { get; }
#if JHELP
/// <summary>
/// 発話ターン
/// </summary>
#else
/// <summary>
/// The turn of this utterance.
/// </summary>
#endif
int Turn { get; }
#if JHELP
/// <summary>
/// 発話エージェント
/// </summary>
#else
/// <summary>
/// The agent who uttered.
/// </summary>
#endif
Agent Agent { get; }
#if JHELP
/// <summary>
/// 発話テキスト
/// </summary>
#else
/// <summary>
/// The contents of this utterance.
/// </summary>
#endif
string Text { get; }
}
}
| mit | C# | |
48b4cc2e0afed35b4360e4469926a855b96fc163 | Create Exercise_14.cs | jesushilarioh/Questions-and-Exercises-in-C-Sharp | Exercise_14.cs | Exercise_14.cs | using System;
public class Exercise_14
{
public static void Main()
{
/**********************************************************************
*
* 14. Write a program to convert from celsius degrees to Kelvin and
* Fahreheit.
*
* By: Jesus Hilario Hernandez
* Last Updated: October 4th 2017
*
**********************************************************************/
Console.Write("Enter the amount of celsius: ");
var C = Convert.ToDouble(Console.ReadLine());
var K = C + 273.15;
var F = (C * (9/5.0) + 32);
Console.WriteLine("Kelvin = {0}", K);
Console.WriteLine("Fahrenheit = {0}", F);
}
}
| mit | C# | |
d593823ea10b3938a02e961adaa94b403437daf9 | add GitBranchSearchController.cs | mikefourie/GitMonitor,mikefourie/GitMonitor,mikefourie/GitMonitor | src/GitMonitor/Controllers/Api/GitBranchSearchController.cs | src/GitMonitor/Controllers/Api/GitBranchSearchController.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="GitBranchSearchController.cs" company="FreeToDev">Copyright Mike Fourie</copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace GitMonitor.Controllers
{
using GitMonitor.Models;
using GitMonitor.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
[Route("api/branches")]
public class GitBranchSearchController : Controller
{
private readonly ILogger<GitController> locallogger;
private readonly ICommitRepository localRepository;
private readonly IOptions<MonitoredPathConfig> localMonitoredPathConfig;
public GitBranchSearchController(ICommitRepository repository, ILogger<GitController> logger, IOptions<MonitoredPathConfig> monitoredPathConfig)
{
this.localRepository = repository;
this.locallogger = logger;
this.localMonitoredPathConfig = monitoredPathConfig;
}
[Route("{repositoryName}/{sha}")]
public JsonResult GetBranches(string repositoryName, string sha)
{
GitSearch search = new GitSearch
{
Sha = sha,
Branches = this.localRepository.SearchBranchesForCommit(this.localMonitoredPathConfig.Value, repositoryName, sha, string.Empty)
};
return this.Json(search);
}
[Route("{repositoryName}/{sha}/{filter}")]
public JsonResult GetBranches(string repositoryName, string sha, string filter)
{
GitSearch search = new GitSearch
{
Sha = sha,
Branches = this.localRepository.SearchBranchesForCommit(this.localMonitoredPathConfig.Value, repositoryName, sha, filter)
};
return this.Json(search);
}
}
} | mit | C# | |
ad885f3d367e95a5c9f41e510bdfe51980cee7b5 | Add unit tests for UaTcpChannelOptions | convertersystems/opc-ua-client | UaClient.UnitTests/UnitTests/UaApplicationOptionsTests.cs | UaClient.UnitTests/UnitTests/UaApplicationOptionsTests.cs | using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
using Workstation.ServiceModel.Ua;
using Xunit;
namespace Workstation.UaClient.UnitTests
{
public class UaApplicationOptionsTests
{
[Fact]
public void UaTcpTransportChannelOptionsDefaults()
{
var lowestBufferSize = 1024u;
var options = new UaTcpTransportChannelOptions();
options.LocalMaxChunkCount
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalMaxMessageSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalReceiveBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalSendBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
}
[Fact]
public void UaTcpSecureChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSecureChannelOptions();
TimeSpan.FromMilliseconds(options.TimeoutHint)
.Should().BeGreaterOrEqualTo(shortestTimespan);
options.DiagnosticsHint
.Should().Be(0);
}
[Fact]
public void UaTcpSessionChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSessionChannelOptions();
TimeSpan.FromMilliseconds(options.SessionTimeout)
.Should().BeGreaterOrEqualTo(shortestTimespan);
}
}
}
| mit | C# | |
5e548e97175937722a1b79297bf251c4c13a2b1a | Fix flaky repro test | CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net | src/Tests/Reproduce/GithubIssue2173.cs | src/Tests/Reproduce/GithubIssue2173.cs | using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using Xunit;
namespace Tests.Reproduce
{
[Collection(TypeOfCluster.Indexing)]
public class GithubIssue2173
{
private readonly IndexingCluster _cluster;
public GithubIssue2173(IndexingCluster cluster)
{
_cluster = cluster;
}
[I] public void UpdateByQueryWithInvalidScript()
{
var client = _cluster.Client();
var response = client.UpdateByQuery<Project>(u => u
.Script("invalid groovy")
);
response.IsValid.Should().BeFalse();
}
}
}
| using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tests.Framework;
using Tests.Framework.MockData;
namespace Tests.Reproduce
{
public class GithubIssue2173
{
[I]
public void UpdateByQueryWithInvalidScript()
{
var client = TestClient.GetClient();
var response = client.UpdateByQuery<Project>(typeof(Project), typeof(Project), u => u
.Script("invalid groovy")
);
response.IsValid.Should().BeFalse();
}
}
}
| apache-2.0 | C# |
9b84d921f3221133b9c2ea4bba5fd76b0b247e5c | Create generics.cs | ashoktandan007/csharp,wchild30/asterisk | generics.cs | generics.cs | using System;
class Pro<T>
{
public Pro(T n)
{
Console.WriteLine(n);
}
}
class foo
{
static void Main()
{
Pro<int> obj = new Pro<int>(55);
Pro<string> obj1 = new Pro<string>("ashok");
Console.ReadLine();
}
}
| apache-2.0 | C# | |
6933a41b7504404785625f22be86fad35bf402f1 | Add back high resolution cover regressions | peppy/osu,johnneijzen/osu,ppy/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,Nabile-Rahmani/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,UselessToucan/osu,smoogipooo/osu,EVAST9919/osu,2yangk23/osu,naoey/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu-new,NeoAdonis/osu,naoey/osu,Drezi126/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,Frontear/osuKyzer,DrabWeb/osu,smoogipoo/osu,naoey/osu,peppy/osu,DrabWeb/osu,DrabWeb/osu,ZLima12/osu | osu.Game/Beatmaps/BeatmapSetOnlineInfo.cs | osu.Game/Beatmaps/BeatmapSetOnlineInfo.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 System;
using Newtonsoft.Json;
namespace osu.Game.Beatmaps
{
/// <summary>
/// Beatmap set info retrieved for previewing locally without having the set downloaded.
/// </summary>
public class BeatmapSetOnlineInfo
{
/// <summary>
/// The date this beatmap set was submitted to the online listing.
/// </summary>
public DateTimeOffset Submitted { get; set; }
/// <summary>
/// The date this beatmap set was ranked.
/// </summary>
public DateTimeOffset? Ranked { get; set; }
/// <summary>
/// The date this beatmap set was last updated.
/// </summary>
public DateTimeOffset? LastUpdated { get; set; }
/// <summary>
/// Whether or not this beatmap set has a background video.
/// </summary>
public bool HasVideo { get; set; }
/// <summary>
/// The different sizes of cover art for this beatmap set.
/// </summary>
public BeatmapSetOnlineCovers Covers { get; set; }
/// <summary>
/// A small sample clip of this beatmap set's song.
/// </summary>
public string Preview { get; set; }
/// <summary>
/// The beats per minute of this beatmap set's song.
/// </summary>
public double BPM { get; set; }
/// <summary>
/// The amount of plays this beatmap set has.
/// </summary>
public int PlayCount { get; set; }
/// <summary>
/// The amount of people who have favourited this beatmap set.
/// </summary>
public int FavouriteCount { get; set; }
}
public class BeatmapSetOnlineCovers
{
public string CoverLowRes { get; set; }
[JsonProperty(@"cover@2x")]
public string Cover { get; set; }
public string CardLowRes { get; set; }
[JsonProperty(@"card@2x")]
public string Card { get; set; }
public string ListLowRes { get; set; }
[JsonProperty(@"list@2x")]
public string List { get; set; }
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
namespace osu.Game.Beatmaps
{
/// <summary>
/// Beatmap set info retrieved for previewing locally without having the set downloaded.
/// </summary>
public class BeatmapSetOnlineInfo
{
/// <summary>
/// The date this beatmap set was submitted to the online listing.
/// </summary>
public DateTimeOffset Submitted { get; set; }
/// <summary>
/// The date this beatmap set was ranked.
/// </summary>
public DateTimeOffset? Ranked { get; set; }
/// <summary>
/// The date this beatmap set was last updated.
/// </summary>
public DateTimeOffset? LastUpdated { get; set; }
/// <summary>
/// Whether or not this beatmap set has a background video.
/// </summary>
public bool HasVideo { get; set; }
/// <summary>
/// The different sizes of cover art for this beatmap set.
/// </summary>
public BeatmapSetOnlineCovers Covers { get; set; }
/// <summary>
/// A small sample clip of this beatmap set's song.
/// </summary>
public string Preview { get; set; }
/// <summary>
/// The beats per minute of this beatmap set's song.
/// </summary>
public double BPM { get; set; }
/// <summary>
/// The amount of plays this beatmap set has.
/// </summary>
public int PlayCount { get; set; }
/// <summary>
/// The amount of people who have favourited this beatmap set.
/// </summary>
public int FavouriteCount { get; set; }
}
public class BeatmapSetOnlineCovers
{
public string CoverLowRes { get; set; }
public string Cover { get; set; }
public string CardLowRes { get; set; }
public string Card { get; set; }
public string ListLowRes { get; set; }
public string List { get; set; }
}
}
| mit | C# |
a5840c98c6a8eed026c2646732921e1958626ba0 | Create Camlookat.cs | afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game | Real_Game/Assets/Scripts/Camlookat.cs | Real_Game/Assets/Scripts/Camlookat.cs | //SmoothLookAt.cs
//Written by Jake Bayer
//Written and uploaded November 18, 2012
//This is a modified C# version of the SmoothLookAt JS script. Use it the same way as the Javascript version.
using UnityEngine;
using System.Collections;
///<summary>
///Looks at a target
///</summary>
[AddComponentMenu("Camera-Control/Smooth Look At CS")]
public class SmoothLookAt : MonoBehaviour {
public Transform target; //an Object to lock on to
public float damping = 6.0f; //to control the rotation
public bool smooth = true;
public float minDistance = 10.0f; //How far the target is from the camera
public string property = "";
private Color color;
private float alpha = 1.0f;
private Transform _myTransform;
void Awake() {
_myTransform = transform;
}
// Use this for initialization
void Start () {
// if(renderer.material.HasProperty(property)) {
// color = renderer.material.GetColor(property);
// }
// else {
// property = "";
// }
// if(rigidbody) {
// rigidbody.freezeRotation = true;
// }
}
// Update is called once per frame
void Update () {
}
void LateUpdate() {
if(target) {
if(smooth) {
//Look at and dampen the rotation
Quaternion rotation = Quaternion.LookRotation(target.position - _myTransform.position);
_myTransform.rotation = Quaternion.Slerp(_myTransform.rotation, rotation, Time.deltaTime * damping);
}
else { //Just look at
_myTransform.rotation = Quaternion.FromToRotation(-Vector3.forward, (new Vector3(target.position.x, target.position.y, target.position.z) - _myTransform.position).normalized);
float distance = Vector3.Distance(target.position, _myTransform.position);
if(distance < minDistance) {
alpha = Mathf.Lerp(alpha, 0.0f, Time.deltaTime * 2.0f);
}
else {
alpha = Mathf.Lerp(alpha, 1.0f, Time.deltaTime * 2.0f);
}
// if(!string.IsNullOrEmpty(property)) {
// color.a = Mathf.Clamp(alpha, 0.0f, 1.0f);
// renderer.material.SetColor(property, color);
// }
}
}
}
}
| mit | C# | |
01b26b3a9ffe821732600ec8282bc5699e0e59ef | Create 20170714.cs | twilightspike/cuddly-disco,twilightspike/cuddly-disco | main/20170714.cs | main/20170714.cs | int aaa;
int bbb;
int ccc;
| mit | C# | |
e7502f621b34a43e6943449135405615d85d68ef | Update Blu.Build.cs | marcthenarc/BLUI,jgagner92/BLUI,csfinch/BLUI,jgagner92/BLUI,jgagner92/BLUI,marcthenarc/BLUI,bemon/BLUI,marcthenarc/BLUI,csfinch/BLUI,brandonwamboldt/BLUI,brandonwamboldt/BLUI,bemon/BLUI,AaronShea/BLUI,brandonwamboldt/BLUI,csfinch/BLUI,AaronShea/BLUI,AaronShea/BLUI,bemon/BLUI | Source/Blu/Blu.Build.cs | Source/Blu/Blu.Build.cs | using UnrealBuildTool;
using System.IO;
using System;
public class Blu : ModuleRules
{
private string ModulePath
{
get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
}
private string ThirdPartyPath
{
get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); }
}
public Blu(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"InputCore",
"RenderCore",
"RHI",
"Slate",
"SlateCore",
"UMG",
"Json"
});
PrivateIncludePaths.AddRange(
new string[] {
"Blu/Private",
});
if(Target.Platform == UnrealTargetPlatform.Win64)
{
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Win/lib", "libcef.lib"));
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Win/lib", "libcef_dll_wrapper.lib"));
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ThirdPartyPath, "cef/Win")
});
} else if(Target.Platform == UnrealTargetPlatform.Linux)
{
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Linux/lib", "libcef.so"));
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Linux/lib", "libcef_dll_wrapper.a"));
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ThirdPartyPath, "cef/Linux")
});
} else if(Target.Platform == UnrealTargetPlatform.Mac)
{
string Configuration;
switch(Target.Configuration)
{
case UnrealTargetConfiguration.Debug:
Configuration = "Debug";
break;
case UnrealTargetConfiguration.DebugGame:
Configuration = "Debug";
break;
default:
Configuration = "Release";
break;
}
PublicFrameworks.Add(Path.Combine(ThirdPartyPath, "cef", "Mac", Configuration, "Chromium Embedded Framework.framework"));
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ThirdPartyPath, "cef", "Mac")
});
}
else
{
throw new BuildException("BLUI: Platform not supported");
}
}
}
| using UnrealBuildTool;
using System.IO;
using System;
public class Blu : ModuleRules
{
private string ModulePath
{
get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
}
private string ThirdPartyPath
{
get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); }
}
public Blu(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"InputCore",
"RenderCore",
"RHI",
"Slate",
"SlateCore",
"UMG",
"Json"
});
PrivateIncludePaths.AddRange(
new string[] {
"Blu/Private",
});
if(Target.Platform == UnrealTargetPlatform.Win64)
{
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Win/lib", "libcef.lib"));
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Win/lib", "libcef_dll_wrapper.lib"));
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ThirdPartyPath, "cef/Win")
});
} else if(Target.Platform == UnrealTargetPlatform.Linux)
{
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Linux/lib", "libcef.so"));
PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyPath, "cef/Linux/lib", "libcef_dll_wrapper.a"));
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ThirdPartyPath, "cef/Linux")
});
} else if(Target.Platform == UnrealTargetPlatform.Mac)
{
string Configuration;
switch(Target.Configuration)
{
case UnrealTargetConfiguration.Debug:
Configuration = "Debug";
break;
case UnrealTargetConfiguration.DebugGame:
Configuration = "Debug";
break;
default:
Configuration = "Release";
break;
}
PublicFrameworks.Add(Path.Combine(ThirdPartyPath, "cef", "Mac", Configuration, "Chromium Embedded Framework.framework"));
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(ThirdPartyPath, "cef", "Mac")
});
}
else
{
throw new BuildException("BLUI: Platform not supported");
}
}
} | mit | C# |
de4d5413e92f41229084ed501c05a1dde6759ed7 | Add IDependencyContainer | Vtek/Bartender | src/Bartender/IDependencyContainer.cs | src/Bartender/IDependencyContainer.cs | using System.Collections.Generic;
namespace Bartender
{
/// <summary>
/// Define a dependency container
/// </summary>
public interface ILocator
{
/// <summary>
/// Gets a service.
/// </summary>
/// <returns>The service.</returns>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
TService GetService<TService>() where TService : class;
/// <summary>
/// Gets all services.
/// </summary>
/// <returns>The all services.</returns>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
IEnumerable<TService> GetAllServices<TService>() where TService : class;
}
} | mit | C# | |
ca2c2097016521c16a345e6a173d4e62c78cac0a | add FastRandom | johnneijzen/osu,2yangk23/osu,smoogipoo/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,naoey/osu,ZLima12/osu,DrabWeb/osu,ppy/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,naoey/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,ZLima12/osu,DrabWeb/osu,johnneijzen/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu | osu.Game.Rulesets.Catch/MathUtils/FastRandom.cs | osu.Game.Rulesets.Catch/MathUtils/FastRandom.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
namespace osu.Game.Rulesets.Catch.MathUtils
{
/// <summary>
/// A PRNG specified in http://heliosphan.org/fastrandom.html.
/// </summary>
internal class FastRandom
{
private const double int_to_real = 1.0 / (int.MaxValue + 1.0);
private const uint int_mask = 0x7FFFFFFF;
private const uint y = 842502087;
private const uint z = 3579807591;
private const uint w = 273326509;
private uint _x, _y = y, _z = z, _w = w;
public FastRandom(int seed)
{
_x = (uint)seed;
}
public FastRandom()
: this(Environment.TickCount)
{
}
/// <summary>
/// Generates a random unsigned integer within the range [<see cref="uint.MinValue"/>, <see cref="uint.MaxValue"/>).
/// </summary>
/// <returns>The random value.</returns>
public uint NextUInt()
{
uint t = _x ^ _x << 11;
_x = _y;
_y = _z;
_z = _w;
return _w = _w ^ _w >> 19 ^ t ^ t >> 8;
}
/// <summary>
/// Generates a random integer value within the range [0, <see cref="int.MaxValue"/>).
/// </summary>
/// <returns>The random value.</returns>
public int Next() => (int)(int_mask & NextUInt());
/// <summary>
/// Generates a random integer value within the range [0, <paramref name="upperBound"/>).
/// </summary>
/// <param name="upperBound">The upper bound.</param>
/// <returns>The random value.</returns>
public int Next(int upperBound) => (int)(NextDouble() * upperBound);
/// <summary>
/// Generates a random integer value within the range [<paramref name="lowerBound"/>, <paramref name="upperBound"/>).
/// </summary>
/// <param name="lowerBound">The lower bound of the range.</param>
/// <param name="upperBound">The upper bound of the range.</param>
/// <returns>The random value.</returns>
public int Next(int lowerBound, int upperBound) => (int)(lowerBound + NextDouble() * (upperBound - lowerBound));
/// <summary>
/// Generates a random double value within the range [0, 1).
/// </summary>
/// <returns>The random value.</returns>
public double NextDouble() => int_to_real * Next();
private uint bitBuffer;
private int bitIndex = 32;
/// <summary>
/// Generates a reandom boolean value. Cached such that a random value is only generated once in every 32 calls.
/// </summary>
/// <returns>The random value.</returns>
public bool NextBool()
{
if (bitIndex == 32)
{
bitBuffer = NextUInt();
bitIndex = 1;
return (bitBuffer & 1) == 1;
}
bitIndex++;
return ((bitBuffer >>= 1) & 1) == 1;
}
}
}
| mit | C# | |
1b08f3b9c2354da352339cd86af833dabad2b7b1 | Add csharp 5.x snippets rest/taskrouter/events | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets | rest/taskrouter/events/example-1/example-1.5.x.cs | rest/taskrouter/events/example-1/example-1.5.x.cs | // Download the twilio-csharp library from https://www.twilio.com/docs/libraries/csharp#installation
using System;
using Twilio;
using Twilio.Rest.Taskrouter.V1.Workspace;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var events = EventResource.Read(workspaceSid);
foreach(EventResource trEvent in events) {
Console.WriteLine(trEvent.EventType);
}
}
}
| mit | C# | |
cadf2e6cf3167f86372843622d5220ce5e96fbbe | Create a class that is used to process the restQL queries. | nohros/must,nohros/must,nohros/must | src/platform/toolkit/restQL/QueryProcessor.cs | src/platform/toolkit/restQL/QueryProcessor.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Nohros.Toolkit.RestQL
{
/// <summary>
/// A class used to process a restQL query.
/// </summary>
public class QueryProcessor
{
QueryInfo query_;
string query_key_;
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="QueryProcessor"/> class
/// by using the specified query string.
/// </summary>
/// <param name="query_key">A string that uniquely identifies a query
/// within the main data store.</param>
/// <param name="query_string">A <see cref="IDictionary"/> object
/// containing the parameters that will be used by the query associated
/// with the given <paramref name="query_key"/>.</param>
public QueryProcessor(QueryInfo query) {
}
#endregion
/// <summary>
/// Retrieve the query information from the main datastore and execute it,
/// using the supplied parameters.
/// </summary>
/// <returns></returns>
public string Process() {
}
}
}
| mit | C# | |
d6536f81d44004214debf969994bed3148df6853 | Create angryProfessor.cs | shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms | angryProfessor.cs | angryProfessor.cs | /*
# File : diagonalDifference.cs
# Author : Shree Harsha Sridharamurthy
# Author email : s.shreeharsha@gmail.com
# Disclaimer : For use by concerned personnel only. Released under MIT License - permitted to use this but need to quote the source origin.
# Program : Solution for hackerrank question posted here:https://www.hackerrank.com/challenges/angry-professor
# Description : A Discrete Mathematics professor has a class of N students. Frustrated with their lack of discipline, he decides to cancel class if fewer than K students are present when class starts.
Given the arrival time of each student, determine if the class is canceled.
Input Format
The first line of input contains T, the number of test cases.
Each test case consists of two lines. The first line has two space-separated integers, N (students in the class) and K (the cancelation threshold).
The second line contains NN space-separated integers (a1,a2,…,aN) describing the arrival times for each student.
Note: Non-positive arrival times (ai≤0) indicate the student arrived early or on time; positive arrival times (ai>0) indicate the student arrived aiai minutes late.
Output Format
For each test case, print the word YES if the class is canceled or NO if it is not.
Constraints
1≤T≤10
1≤N≤1000
1≤K≤N
−100≤ai≤100,where i∈[1,N]−
Note
If a student arrives exactly on time (ai=0), the student is considered to have entered before the class started.
Sample Input
2
4 3
-1 -3 4 2
4 2
0 -1 2 1
Sample Output
YES
NO
Explanation:
For the first test case, K=3. The professor wants at least 33 students in attendance, but only 2 have arrived on time (−3 and −1). Thus, the class is canceled.
For the second test case, K=2. The professor wants at least 22 students in attendance, and there are 2 who have arrived on time (0 and −1). Thus, the class is not canceled.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int t = Convert.ToInt32(Console.ReadLine());
for(int testCount = 0; testCount < t; testCount++){
string[] nAndk = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nAndk[0]);
int k = Convert.ToInt32(nAndk[1]);
string[] studentsStr = Console.ReadLine().Split(' ');
int[] students = Array.ConvertAll(studentsStr,Int32.Parse);
if(k>n){
Console.WriteLine("YES");
}
else{
int goodCount = 0;
for(int i=0;i<n;i++){
if(students[i] <= 0){
goodCount++;
}
}
//Console.WriteLine(goodCount+","+k);
if(goodCount >= k){
Console.WriteLine("NO");
}
else{
Console.WriteLine("YES");
}
}
}
}
}
| mit | C# | |
144b182e8cae9cf94f54126b47b1f241eaf2cecc | Add LevelModel.cs | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.Contract/Models/LevelModel.cs | NinjaHive.Contract/Models/LevelModel.cs | using System;
using System.ComponentModel.DataAnnotations;
using NinjaHive.Core.Helpers;
using NinjaHive.Core.Validations;
namespace NinjaHive.Contract.Models
{
public class LevelModel : IModel
{
public Guid Id { get; set; }
}
}
| apache-2.0 | C# | |
64eea4249341f5d062434f04a18ffe32f9298363 | make Null.Default readonly | rmboggs/boo,KidFashion/boo,hmah/boo,wbardzinski/boo,BitPuffin/boo,BillHally/boo,rmartinho/boo,rmartinho/boo,BillHally/boo,wbardzinski/boo,BITechnologies/boo,drslump/boo,Unity-Technologies/boo,wbardzinski/boo,bamboo/boo,BITechnologies/boo,bamboo/boo,hmah/boo,rmartinho/boo,KingJiangNet/boo,bamboo/boo,BitPuffin/boo,boo-lang/boo,boo-lang/boo,Unity-Technologies/boo,KidFashion/boo,wbardzinski/boo,hmah/boo,drslump/boo,scottstephens/boo,bamboo/boo,rmboggs/boo,rmboggs/boo,Unity-Technologies/boo,BITechnologies/boo,scottstephens/boo,rmartinho/boo,bamboo/boo,KidFashion/boo,rmboggs/boo,wbardzinski/boo,BitPuffin/boo,BillHally/boo,Unity-Technologies/boo,BitPuffin/boo,BITechnologies/boo,KidFashion/boo,BitPuffin/boo,BITechnologies/boo,BillHally/boo,wbardzinski/boo,boo-lang/boo,boo-lang/boo,hmah/boo,rmboggs/boo,KidFashion/boo,BITechnologies/boo,hmah/boo,drslump/boo,KingJiangNet/boo,KidFashion/boo,KingJiangNet/boo,drslump/boo,Unity-Technologies/boo,scottstephens/boo,BitPuffin/boo,bamboo/boo,hmah/boo,hmah/boo,KingJiangNet/boo,KingJiangNet/boo,BillHally/boo,scottstephens/boo,BillHally/boo,boo-lang/boo,rmboggs/boo,rmartinho/boo,BITechnologies/boo,rmartinho/boo,KidFashion/boo,rmboggs/boo,drslump/boo,boo-lang/boo,rmartinho/boo,wbardzinski/boo,BITechnologies/boo,hmah/boo,drslump/boo,BitPuffin/boo,Unity-Technologies/boo,BitPuffin/boo,scottstephens/boo,bamboo/boo,KingJiangNet/boo,scottstephens/boo,drslump/boo,scottstephens/boo,hmah/boo,rmboggs/boo,scottstephens/boo,wbardzinski/boo,Unity-Technologies/boo,KingJiangNet/boo,Unity-Technologies/boo,BillHally/boo,KingJiangNet/boo,boo-lang/boo,boo-lang/boo,rmartinho/boo | src/Boo.Lang.Compiler/TypeSystem/Null.cs | src/Boo.Lang.Compiler/TypeSystem/Null.cs | #region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Boo.Lang.Compiler.TypeSystem.Core;
namespace Boo.Lang.Compiler.TypeSystem
{
public class Null : AbstractType
{
public static readonly Null Default = new Null();
private Null()
{
}
override public string Name
{
get { return "null"; }
}
override public EntityType EntityType
{
get { return EntityType.Null; }
}
public override IArrayType MakeArrayType(int rank)
{
return My<TypeSystemServices>.Instance.ObjectType.MakeArrayType(rank);
}
}
}
| #region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Boo.Lang.Compiler.TypeSystem.Core;
namespace Boo.Lang.Compiler.TypeSystem
{
public class Null : AbstractType
{
public static Null Default = new Null();
private Null()
{
}
override public string Name
{
get { return "null"; }
}
override public EntityType EntityType
{
get { return EntityType.Null; }
}
public override IArrayType MakeArrayType(int rank)
{
return My<TypeSystemServices>.Instance.ObjectType.MakeArrayType(rank);
}
}
}
| bsd-3-clause | C# |
69da4dffd55124881caabbaafaebf69de16b62b5 | Add sql base class | xin9le/DeclarativeSql | src/DeclarativeSql/Sql/Sql.cs | src/DeclarativeSql/Sql/Sql.cs | using System;
using System.Text;
namespace DeclarativeSql.Sql
{
/// <summary>
/// Represents SQL for specified mapping table.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISql<T>
{
/// <summary>
/// Gets database provider.
/// </summary>
DbProvider DbProvider { get; }
/// <summary>
/// Builds query.
/// </summary>
/// <returns></returns>
Query Build();
}
/// <summary>
/// Represents SQL for specified mapping table.
/// </summary>
/// <typeparam name="T"></typeparam>
internal abstract class Sql<T> : ISql<T>
{
#region Constructors
/// <summary>
/// Creates instance.
/// </summary>
/// <param name="provider"></param>
protected Sql(DbProvider provider)
=> this.DbProvider = provider ?? throw new ArgumentNullException(nameof(provider));
#endregion
#region ISql implementations
/// <summary>
/// Gets database provider.
/// </summary>
public DbProvider DbProvider { get; }
/// <summary>
/// Builds query.
/// </summary>
/// <returns></returns>
public Query Build()
{
var builder = new StringBuilder();
var bindParameter = new BindParameter();
this.Build(builder, bindParameter);
return new Query(builder.ToString(), bindParameter);
}
#endregion
#region abstract
/// <summary>
/// Builds query.
/// </summary>
/// <param name="builder"></param>
/// <param name="bindParameter"></param>
internal abstract void Build(StringBuilder builder, BindParameter bindParameter);
#endregion
#region override
/// <summary>
/// Converts to string.
/// </summary>
/// <returns></returns>
public sealed override string ToString()
=> this.Build().Statement;
#endregion
}
}
| mit | C# | |
e6fb7880440e7d2655d1d19c2a7d67304a766be4 | Fix d'un bug qui faisait en sorte que le showDialog ne fonctionnait pas | Lan-Manager/lama,Tri125/lama | Lama/UI/Win/AjouterVolontaire.xaml.cs | Lama/UI/Win/AjouterVolontaire.xaml.cs | using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Lama.UI.Win
{
/// <summary>
/// Logique d'interaction pour AjouterVolontaire.xaml
/// </summary>
public partial class AjouterVolontaire
{
public AjouterVolontaire()
{
InitializeComponent();
}
}
}
| using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Lama.UI.Win
{
/// <summary>
/// Logique d'interaction pour AjouterVolontaire.xaml
/// </summary>
public partial class AjouterVolontaire : MetroWindow
{
public AjouterVolontaire()
{
InitializeComponent();
}
}
}
| mit | C# |
18617d9d7c3834a341dcc239ddbeea3646d850e6 | Call GL.GetShaderInfoLog | haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,a9upam/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,sakthivelnagarajan/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples,robinlaide/monotouch-samples,labdogg1003/monotouch-samples,a9upam/monotouch-samples,a9upam/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,albertoms/monotouch-samples,kingyond/monotouch-samples,robinlaide/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,peteryule/monotouch-samples,nelzomal/monotouch-samples,iFreedive/monotouch-samples,nervevau2/monotouch-samples,nelzomal/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,davidrynn/monotouch-samples,albertoms/monotouch-samples,albertoms/monotouch-samples,markradacz/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,hongnguyenpro/monotouch-samples,xamarin/monotouch-samples,sakthivelnagarajan/monotouch-samples,W3SS/monotouch-samples,robinlaide/monotouch-samples,kingyond/monotouch-samples,labdogg1003/monotouch-samples,markradacz/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,xamarin/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,YOTOV-LIMITED/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,hongnguyenpro/monotouch-samples,a9upam/monotouch-samples,W3SS/monotouch-samples,markradacz/monotouch-samples,sakthivelnagarajan/monotouch-samples | OpenGL/OpenGLES20Example/GLProgram.cs | OpenGL/OpenGLES20Example/GLProgram.cs | using System;
using OpenTK.Graphics.ES20;
using MonoTouch.Foundation;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace OpenGLES20Example
{
public class GLProgram
{
int program,
vertShader,
fragShader;
List<string> attributes;
public GLProgram (string vShaderFilename, string fShaderFilename)
{
attributes = new List<string> ();
program = GL.CreateProgram ();
string vertShaderPathName = NSBundle.MainBundle.PathForResource (vShaderFilename, "vsh");
if (!compileShader (ref vertShader, ShaderType.VertexShader, vertShaderPathName))
Console.WriteLine ("Failed to compile the vertex shader");
string fragShaderPathName = NSBundle.MainBundle.PathForResource (fShaderFilename, "fsh");
if (!compileShader (ref fragShader, ShaderType.FragmentShader, fragShaderPathName))
Console.WriteLine ("Failed to compile the fragment shader");
GL.AttachShader (program, vertShader);
GL.AttachShader (program, fragShader);
}
bool compileShader (ref int shader, ShaderType type, string file)
{
int status;
string source;
using (StreamReader sr = new StreamReader(file))
source = sr.ReadToEnd();
shader = GL.CreateShader (type);
GL.ShaderSource (shader, source);
GL.CompileShader (shader);
GL.GetShader (shader, ShaderParameter.CompileStatus, out status);
return status == (int) All.True;
}
public void AddAttribute (string attributeName)
{
if (!attributes.Contains (attributeName)) {
attributes.Add (attributeName);
GL.BindAttribLocation (program, attributes.IndexOf (attributeName), attributeName);
}
}
public int GetAttributeIndex (string attributeName)
{
return attributes.IndexOf (attributeName);
}
public int GetUniformIndex (string uniformName)
{
return GL.GetUniformLocation (program, uniformName);
}
public bool Link ()
{
int status = 0;
GL.LinkProgram (program);
GL.ValidateProgram (program);
GL.GetProgram (program, ProgramParameter.LinkStatus, out status);
if (status == (int) All.False)
return false;
GL.DeleteShader (vertShader);
GL.DeleteShader (fragShader);
return true;
}
public void Use ()
{
GL.UseProgram (program);
}
string GetLog (int obj) {
string log;
if (GL.IsShader (obj)) {
log = GL.GetShaderInfoLog (obj);
} else {
log = GL.GetProgramInfoLog (obj);
}
return log;
}
public string VertexShaderLog ()
{
return GetLog (vertShader);
}
public string FragmentShaderLog ()
{
return GetLog (fragShader);
}
public string ProgramLog ()
{
return GetLog (program);
}
}
}
| using System;
using OpenTK.Graphics.ES20;
using MonoTouch.Foundation;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace OpenGLES20Example
{
public class GLProgram
{
int program,
vertShader,
fragShader;
List<string> attributes;
public GLProgram (string vShaderFilename, string fShaderFilename)
{
attributes = new List<string> ();
program = GL.CreateProgram ();
string vertShaderPathName = NSBundle.MainBundle.PathForResource (vShaderFilename, "vsh");
if (!compileShader (ref vertShader, ShaderType.VertexShader, vertShaderPathName))
Console.WriteLine ("Failed to compile the vertex shader");
string fragShaderPathName = NSBundle.MainBundle.PathForResource (fShaderFilename, "fsh");
if (!compileShader (ref fragShader, ShaderType.FragmentShader, fragShaderPathName))
Console.WriteLine ("Failed to compile the fragment shader");
GL.AttachShader (program, vertShader);
GL.AttachShader (program, fragShader);
}
bool compileShader (ref int shader, ShaderType type, string file)
{
int status;
string source;
using (StreamReader sr = new StreamReader(file))
source = sr.ReadToEnd();
shader = GL.CreateShader (type);
GL.ShaderSource (shader, source);
GL.CompileShader (shader);
GL.GetShader (shader, ShaderParameter.CompileStatus, out status);
return status == (int) All.True;
}
public void AddAttribute (string attributeName)
{
if (!attributes.Contains (attributeName)) {
attributes.Add (attributeName);
GL.BindAttribLocation (program, attributes.IndexOf (attributeName), attributeName);
}
}
public int GetAttributeIndex (string attributeName)
{
return attributes.IndexOf (attributeName);
}
public int GetUniformIndex (string uniformName)
{
return GL.GetUniformLocation (program, uniformName);
}
public bool Link ()
{
int status = 0;
GL.LinkProgram (program);
GL.ValidateProgram (program);
GL.GetProgram (program, ProgramParameter.LinkStatus, out status);
if (status == (int) All.False)
return false;
GL.DeleteShader (vertShader);
GL.DeleteShader (fragShader);
return true;
}
public void Use ()
{
GL.UseProgram (program);
}
string getLog (int obj)
{
int logLength = 0;
GL.GetProgram (obj, ProgramParameter.InfoLogLength, out logLength);
if (logLength < 1)
return null;
string log = GL.GetProgramInfoLog (program);
return log;
}
public string VertexShaderLog ()
{
return getLog (vertShader);
}
public string FragmentShaderLog ()
{
return getLog (fragShader);
}
public string ProgramLog ()
{
return getLog (program);
}
}
}
| mit | C# |
3a13637eeaea916b7b80d7b5e34cdfac09638ba7 | Create GpsHelper.cs | Pharap/SpengyUtils | Classes/GpsHelper.cs | Classes/GpsHelper.cs | static class GpsHelper
{
public static string ToGpsString(string name, Vector3 vector)
{
return string.Format("GPS:{0}:{1}:{2}:{3}:", name, vector.X, vector.Y, vector.Z);
}
public static string ToGpsString(string name, Vector3D vector)
{
return string.Format("GPS:{0}:{1}:{2}:{3}:", name, vector.X, vector.Y, vector.Z);
}
public static string ToGpsString(string name, float x, float y, float z)
{
return string.Format("GPS:{0}:{1}:{2}:{3}:", name, x, y, z);
}
public static string ToGpsString(string name, double x, double y, double z)
{
return string.Format("GPS:{0}:{1}:{2}:{3}:", name, x, y, z);
}
public static bool TryParse(string gpsString, out string name, out Vector3 vector)
{
var parts = gpsString.Trim().Split(':');
name = null;
vector = new Vector3();
if (parts.Length != 6)
return false;
name = parts[1];
return
parts[0] == "GPS" &&
float.TryParse(parts[2], out vector.X) &&
float.TryParse(parts[3], out vector.Y) &&
float.TryParse(parts[4], out vector.Z) &&
parts[5] == "";
}
public static bool TryParse(string gpsString, out string name, out Vector3D vector)
{
var parts = gpsString.Trim().Split(':');
name = null;
vector = new Vector3();
if (parts.Length != 6)
return false;
name = parts[1];
return
parts[0] == "GPS" &&
double.TryParse(parts[2], out vector.X) &&
double.TryParse(parts[3], out vector.Y) &&
double.TryParse(parts[4], out vector.Z) &&
parts[5] == "";
}
public static bool TryParse(string gpsString, out string name, out float x, out float y, out float z)
{
var parts = gpsString.Trim().Split(':');
name = null;
x = 0;
y = 0;
z = 0;
if (parts.Length != 6)
return false;
name = parts[1];
return
parts[0] == "GPS" &&
float.TryParse(parts[2], out x) &&
float.TryParse(parts[3], out y) &&
float.TryParse(parts[4], out z) &&
parts[5] == "";
}
public static bool TryParse(string gpsString, out string name, out double x, out double y, out double z)
{
var parts = gpsString.Trim().Split(':');
name = null;
x = 0;
y = 0;
z = 0;
if (parts.Length != 6)
return false;
name = parts[1];
return
parts[0] == "GPS" &&
double.TryParse(parts[2], out x) &&
double.TryParse(parts[3], out y) &&
double.TryParse(parts[4], out z) &&
parts[5] == "";
}
}
| apache-2.0 | C# | |
5e14cc4b7d4d15996421ac283d0eff7b23463c91 | Change how constants are defined | ZocDoc/ZocMon,modulexcite/ZocMon,modulexcite/ZocMon,modulexcite/ZocMon,ZocDoc/ZocMon,ZocDoc/ZocMon | source/ZocMonLib/Framework/Constant.cs | source/ZocMonLib/Framework/Constant.cs | using System;
using System.Data.SqlTypes;
namespace ZocMonLib
{
public class Constant
{
public static readonly DateTime MinDbDateTime = SqlDateTime.MinValue.Value;
public const long TicksInMillisecond = TimeSpan.TicksPerMillisecond;
public const long MinResolutionForDbWrites = 60 * 1000;
public const long MsPerDay = TimeSpan.TicksPerDay / TimeSpan.TicksPerMillisecond;
public const int MaxConfigNameLength = 116;
public const int MaxDataPointsPerLine = 2000; // roughly 3 months of hourly data
}
} | using System;
namespace ZocMonLib
{
public class Constant
{
public static readonly DateTime MinDbDateTime = new DateTime(1753, 1, 1);
public const long TicksInMillisecond = 10000;
public const long MinResolutionForDbWrites = 60 * 1000;
public const long MsPerDay = 24 * 60 * 60 * 1000;
public const int MaxConfigNameLength = 116;
public const int MaxDataPointsPerLine = 2000; // roughly 3 months of hourly data
}
} | apache-2.0 | C# |
6104f1949a2dd74458842fa00323a808ca04a5c2 | Comment use | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Core2D.Avalonia/App.xaml.cs | src/Core2D.Avalonia/App.xaml.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using Avalonia.Markup.Xaml;
using Core2D.Avalonia.Renderers;
using Core2D.ViewModels;
namespace Core2D.Avalonia
{
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
static object BuildDataContext()
{
var bootstrapper = new Bootstrapper();
var vm = bootstrapper.CreateDemoViewModel();
bootstrapper.CreateDemoContainer(vm);
vm.Renderer = new AvaloniaShapeRenderer();
vm.Selected = vm.Renderer.Selected;
return vm;
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
//.UseDirect2D1()
//.UseSkia()
.LogToDebug();
static void Print(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
if (ex.InnerException != null)
{
Print(ex.InnerException);
}
}
static void Main(string[] args)
{
try
{
BuildAvaloniaApp().Start<MainWindow>(() => BuildDataContext());
}
catch (Exception ex)
{
Print(ex);
}
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using Avalonia.Markup.Xaml;
using Core2D.Avalonia.Renderers;
using Core2D.ViewModels;
namespace Core2D.Avalonia
{
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
static object BuildDataContext()
{
var bootstrapper = new Bootstrapper();
var vm = bootstrapper.CreateDemoViewModel();
bootstrapper.CreateDemoContainer(vm);
vm.Renderer = new AvaloniaShapeRenderer();
vm.Selected = vm.Renderer.Selected;
return vm;
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.UseDirect2D1()
//.UseSkia()
.LogToDebug();
static void Print(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
if (ex.InnerException != null)
{
Print(ex.InnerException);
}
}
static void Main(string[] args)
{
try
{
BuildAvaloniaApp().Start<MainWindow>(() => BuildDataContext());
}
catch (Exception ex)
{
Print(ex);
}
}
}
}
| mit | C# |
3c739c04ef9fab4adfc49cb3f4bca1a6e0291139 | add tests for Similar class | icarus-consulting/Yaapii.Atoms | tests/Yaapii.Atoms.Tests/Number/SimilarTest.cs | tests/Yaapii.Atoms.Tests/Number/SimilarTest.cs | using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Yaapii.Atoms.Number;
namespace Yaapii.Atoms.Number.Tests
{
public sealed class SimilarTest
{
[Fact]
public void IsSimilarSame()
{
INumber first =
new NumberOf(13.37);
INumber second =
new NumberOf(13.37);
Assert.True(
new Similar(first, second).Value()
);
}
[Fact]
public void IsSimilarNoDecimal()
{
INumber first =
new NumberOf(13);
INumber second =
new NumberOf(13);
Assert.True(
new Similar(first, second, 10).Value()
);
}
[Fact]
public void IsSimilarOneDecimal()
{
INumber first =
new NumberOf(13.37);
INumber second =
new NumberOf(13.3);
Assert.True(
new Similar(first, second, 1).Value()
);
}
[Fact]
public void IsSimilarOnlyOneDecimal()
{
INumber first =
new NumberOf(13.37777);
INumber second =
new NumberOf(13.33333);
Assert.True(
new Similar(first, second, 1).Value()
);
}
[Fact]
public void IsSimilarFiveDecimal()
{
INumber first =
new NumberOf(13.333337);
INumber second =
new NumberOf(13.333339);
Assert.True(
new Similar(first, second, 5).Value()
);
}
[Fact]
public void IsSimilar10Decimal()
{
INumber first =
new NumberOf(13.33333333337);
INumber second =
new NumberOf(13.33333333339);
Assert.True(
new Similar(first, second, 10).Value()
);
}
[Fact]
public void IsNotSimilar()
{
INumber first =
new NumberOf(13.37);
INumber second =
new NumberOf(13.39);
Assert.False(
new Similar(first, second, 2).Value()
);
}
}
} | mit | C# | |
7ede2917e4542bd0b36410769ab985f062b75575 | Add ShutdownAwaiterAppLifecycleBehavior to initialize the awaiter before features are called. | quartz-software/kephas,quartz-software/kephas | src/Kephas.Application/ShutdownAwaiterAppLifecycleBehavior.cs | src/Kephas.Application/ShutdownAwaiterAppLifecycleBehavior.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ShutdownAwaiterAppLifecycleBehavior.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Implements the shutdown awaiter application lifecycle behavior class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Application
{
using System.Threading;
using System.Threading.Tasks;
using Kephas.Services;
using Kephas.Threading.Tasks;
/// <summary>
/// A shutdown awaiter application lifecycle behavior.
/// </summary>
/// <remarks>
/// Makes sure that the shutdown awaiter has a chance to initialize before the application manager starts initializing the features.
/// Sometimes the features and the behaviors order a shutdown (like a setup routine).
/// </remarks>
[ProcessingPriority(Priority.Highest)]
public class ShutdownAwaiterAppLifecycleBehavior : AppLifecycleBehaviorBase
{
private readonly IAppShutdownAwaiter awaiter;
/// <summary>
/// Initializes a new instance of the <see cref="ShutdownAwaiterAppLifecycleBehavior"/> class.
/// </summary>
/// <param name="awaiter">The awaiter.</param>
public ShutdownAwaiterAppLifecycleBehavior(IAppShutdownAwaiter awaiter)
{
this.awaiter = awaiter;
}
/// <summary>
/// Interceptor called before the application starts its asynchronous initialization.
/// </summary>
/// <param name="appContext">Context for the application.</param>
/// <param name="cancellationToken">Optional. The cancellation token.</param>
/// <returns>
/// A Task.
/// </returns>
public override async Task BeforeAppInitializeAsync(IAppContext appContext, CancellationToken cancellationToken = default)
{
if (this.awaiter is IAsyncInitializable asyncAwaiter)
{
await asyncAwaiter.InitializeAsync(appContext).PreserveThreadContext();
}
else if (this.awaiter is IInitializable syncAwaiter)
{
syncAwaiter.Initialize(appContext);
}
}
}
}
| mit | C# | |
8eb557781b36838a65f983588c03d01004da3449 | Add Q222 | txchen/localleet | csharp/Q222_CountCompleteTreeNodes.cs | csharp/Q222_CountCompleteTreeNodes.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Given a complete binary tree, count the number of nodes.
//
// Definition of a complete binary tree from Wikipedia:
// In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
// https://leetcode.com/problems/count-complete-tree-nodes/
namespace LocalLeet
{
public class Q222
{
public int CountNodes(BinaryTree root)
{
if (root == null)
{
return 0;
}
int leftDepth = 0;
BinaryTree tmp = root;
while (tmp != null)
{
leftDepth++;
tmp = tmp.Left;
}
int rightDepth = 0;
tmp = root;
while (tmp != null)
{
rightDepth++;
tmp = tmp.Right;
}
if (leftDepth == rightDepth)
{
return (int)Math.Pow(2, leftDepth) - 1;
}
return 1 + CountNodes(root.Left) + CountNodes(root.Right);
}
[Fact]
public void Q222_CountCompleteTreeNodes()
{
TestHelper.Run(input => CountNodes(input.EntireInput.ToBinaryTree2()).ToString());
}
}
}
| mit | C# | |
426ca6150a8d79d6e76a0915e41a524679f6f227 | Create StartTest.cs | Si-143/Application-and-Web-Development | StartTest.cs | StartTest.cs | protected void Page_Load(object sender, EventArgs e)
{
Testid.DataSource = DB.ListTest(); Testid.DataTextField = "TestName";
Testid.DataValueField = "TestID";
Testid.DataBind();
Session["TestID"] = Testid.SelectedValue;
string TId = Session["TestID"].ToString();
}
protected void Submit_Click(object sender, EventArgs e)
{
string connString = @"Provider=Microsoft.JET.OLEDB.4.0;Data
Source=I:\AWD\WebApplication1\cwDBExample.mdb"; // pathing of the database
OleDbConnection myConnection = new OleDbConnection(connString);
string myQuery = "SELECT * FROM test WHERE password = '" +
Pass.Text + "'";// select all from the test table where the password match with
each other,
OleDbCommand myCommand = new OleDbCommand(myQuery,
myConnection);
try
{
myConnection.Open();
OleDbDataReader reader = myCommand.ExecuteReader();
if (reader.HasRows == true)// check if it is true
{
int T = Int32.Parse(Testid.SelectedValue.ToString());
List<Questions> question = DB.LoadQuestion(T);// set
question to the value that is returned from loadQuestion method.
Random r = new Random();// randomiser
List<Questions> RandomQuestion = new List<Questions>();
while (RandomQuestion.Count < 5)// check the
randomquestion count is less then 5
{
int num = r.Next(question.Count);
bool containsQuestion = false;
foreach (var Q in RandomQuestion)
{
if (question[num] == Q)
{
containsQuestion = true;
}
}
if (!containsQuestion)
{
RandomQuestion.Add(question[num]);
}
}
Session["RandomQuestion"] = RandomQuestion;
Response.Redirect("TestPage");
| mit | C# | |
709d0be257f90907181a913360590086ff643cd9 | Support for IDN command. | tparviainen/oscilloscope | SCPI/IDN.cs | SCPI/IDN.cs | using System;
using System.Linq;
using System.Text;
namespace SCPI
{
public class IDN : ICommand
{
public string Description => "Query the ID string of the instrument";
public string Manufacturer { get; private set; }
public string Model { get; private set; }
public string SerialNumber { get; private set; }
public string SoftwareVersion { get; private set; }
public string Command(params object[] parameters)
{
return "*IDN?";
}
public bool Parse(byte[] data)
{
// RIGOL TECHNOLOGIES,<model>,<serial number>,<software version>
var id = Encoding.ASCII.GetString(data).Split(',').Select(f => f.Trim());
// According to IEEE 488.2 there are four fields in the response
if (id.Count() == 4)
{
Manufacturer = id.ElementAt(0);
Model = id.ElementAt(1);
SerialNumber = id.ElementAt(2);
SoftwareVersion = id.ElementAt(3);
return true;
}
return false;
}
}
}
| mit | C# | |
5e396ec68e5ad7cb8c023f803368b80594a979c7 | Add a new Paused mode. | dipeshc/BTDeploy | src/MonoTorrent/MonoTorrent.Client/Modes/PausedMode.cs | src/MonoTorrent/MonoTorrent.Client/Modes/PausedMode.cs | using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Common;
namespace MonoTorrent.Client
{
class PausedMode : Mode
{
public override TorrentState State
{
get { return TorrentState.Paused; }
}
public PausedMode(TorrentManager manager)
: base(manager)
{
// When in the Paused mode, a special RateLimiter will
// activate and disable transfers. PauseMode itself
// does not need to do anything special.
}
public override void Tick(int counter)
{
// TODO: In future maybe this can be made smarter by refactoring
// so that in Pause mode we set the Interested status of all peers
// to false, so no data is requested. This way connections can be
// kept open by sending/receiving KeepAlive messages. Currently
// we 'Pause' by not sending/receiving data from the socket.
}
}
}
| mit | C# | |
c25fb26ffe04f1ed057583d5fea629f8c7d8dcc9 | move IExternalReport interface to Serenity.Services | volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity | src/Serenity.Net.Services/Reporting/IExternalReport.cs | src/Serenity.Net.Services/Reporting/IExternalReport.cs | namespace Serenity.Reporting
{
/// <summary>
/// This interface marks a report class as a report that should open an external URL, e.g. an SSRS report url, or any arbitrary site
/// The URL should be returned from GetData() method of report class.
/// </summary>
public interface IExternalReport
{
}
} | mit | C# | |
2eb688d11f6d2066476462665368544b64af6d16 | Create ApprovedResponse.cs | marketvision/ShipStation4Net | ShipStation4Net/Responses/ApprovedResponse.cs | ShipStation4Net/Responses/ApprovedResponse.cs | #region License
/*
* Copyright 2017 Brandon James
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using Newtonsoft.Json;
namespace ShipStation4Net.Responses
{
public class ApprovedResponse
{
[JsonProperty("approved")]
public bool Approved { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
}
| apache-2.0 | C# | |
444e27ec497766be96798ddcc5510ffb3de255a0 | Create HowOldAreYou.cs | TheCanterlonian/Learning,TheCanterlonian/Learning | HowOldAreYou.cs | HowOldAreYou.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowOldAreYou
{
class Program
{
static void Main(string[] args)
{
DateTime nowTime = DateTime.Now;
Console.WriteLine("The current date and time is: " + nowTime);
Console.WriteLine();
Console.WriteLine("When were you born?");
DateTime birthDate = DateTime.Parse(Console.ReadLine());
TimeSpan elapsedTime = DateTime.Now.Subtract(birthDate);
Console.WriteLine();
Console.WriteLine("You are " + elapsedTime.Days + " days old.");
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
Console.WriteLine();
}
}
}
| agpl-3.0 | C# | |
2eb1f9e0943589c5c07687398e66a3cec96e0ed5 | add Upgrade_20220822_StartAfter | signumsoftware/framework,signumsoftware/framework | Signum.Upgrade/Upgrades/Upgrade_20220822_StartAfter.cs | Signum.Upgrade/Upgrades/Upgrade_20220822_StartAfter.cs | using System;
using System.IO;
using System.Net;
using System.Net.Http;
namespace Signum.Upgrade.Upgrades;
class Upgrade_20220822_StartAfter : CodeUpgradeBase
{
public override string Description => "Rename StartXXAfter methods";
public override void Execute(UpgradeContext uctx)
{
uctx.ChangeCodeFile($@"Southwind.React\Startup.cs", file =>
{
file.Replace(
"ProcessRunnerLogic.StartRunningProcesses(",
"ProcessRunner.StartRunningProcessesAfter(");
file.Replace(
"SchedulerLogic.StartScheduledTasks(",
"ScheduleTaskRunner.StartScheduledTaskAfter(");
file.Replace(
"AsyncEmailSenderLogic.StartRunningEmailSenderAsync(",
"AsyncEmailSender.StartAsyncEmailSenderAfter(");
file.Replace(
"ProcessRunnerLogic.StartRunningProcesses(",
"ProcessRunner.StartRunningProcessesAfter(");
});
}
}
| mit | C# | |
db87c10949908d1b6fdc5b45d61751d5e7732ab0 | Change the MSI version to 1.8 | jtlibing/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,makhdumi/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,samtoubia/azure-sdk-for-net,btasdoven/azure-sdk-for-net,yoreddy/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,relmer/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,atpham256/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,shuainie/azure-sdk-for-net,enavro/azure-sdk-for-net,bgold09/azure-sdk-for-net,mihymel/azure-sdk-for-net,peshen/azure-sdk-for-net,jamestao/azure-sdk-for-net,djoelz/azure-sdk-for-net,Nilambari/azure-sdk-for-net,scottrille/azure-sdk-for-net,atpham256/azure-sdk-for-net,btasdoven/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,xindzhan/azure-sdk-for-net,AzCiS/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,AuxMon/azure-sdk-for-net,dasha91/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,makhdumi/azure-sdk-for-net,r22016/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,oaastest/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,smithab/azure-sdk-for-net,vhamine/azure-sdk-for-net,gubookgu/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,hyonholee/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,peshen/azure-sdk-for-net,robertla/azure-sdk-for-net,hovsepm/azure-sdk-for-net,AzCiS/azure-sdk-for-net,tpeplow/azure-sdk-for-net,jianghaolu/azure-sdk-for-net,yoreddy/azure-sdk-for-net,djyou/azure-sdk-for-net,hyonholee/azure-sdk-for-net,shipram/azure-sdk-for-net,robertla/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,mumou/azure-sdk-for-net,abhing/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,pomortaz/azure-sdk-for-net,shuagarw/azure-sdk-for-net,djyou/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,pomortaz/azure-sdk-for-net,mumou/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,jtlibing/azure-sdk-for-net,btasdoven/azure-sdk-for-net,marcoippel/azure-sdk-for-net,juvchan/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,oaastest/azure-sdk-for-net,nemanja88/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,amarzavery/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,bgold09/azure-sdk-for-net,oburlacu/azure-sdk-for-net,nacaspi/azure-sdk-for-net,pinwang81/azure-sdk-for-net,djoelz/azure-sdk-for-net,arijitt/azure-sdk-for-net,rohmano/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,nemanja88/azure-sdk-for-net,cwickham3/azure-sdk-for-net,pattipaka/azure-sdk-for-net,dasha91/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,makhdumi/azure-sdk-for-net,ailn/azure-sdk-for-net,xindzhan/azure-sdk-for-net,AuxMon/azure-sdk-for-net,jamestao/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,hovsepm/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,nathannfan/azure-sdk-for-net,ogail/azure-sdk-for-net,pankajsn/azure-sdk-for-net,samtoubia/azure-sdk-for-net,pomortaz/azure-sdk-for-net,lygasch/azure-sdk-for-net,hallihan/azure-sdk-for-net,namratab/azure-sdk-for-net,tpeplow/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,juvchan/azure-sdk-for-net,dominiqa/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,olydis/azure-sdk-for-net,r22016/azure-sdk-for-net,samtoubia/azure-sdk-for-net,ailn/azure-sdk-for-net,shipram/azure-sdk-for-net,shuagarw/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,mihymel/azure-sdk-for-net,hyonholee/azure-sdk-for-net,gubookgu/azure-sdk-for-net,robertla/azure-sdk-for-net,pilor/azure-sdk-for-net,djyou/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,cwickham3/azure-sdk-for-net,juvchan/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,bgold09/azure-sdk-for-net,lygasch/azure-sdk-for-net,mabsimms/azure-sdk-for-net,begoldsm/azure-sdk-for-net,guiling/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,akromm/azure-sdk-for-net,herveyw/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,enavro/azure-sdk-for-net,mabsimms/azure-sdk-for-net,kagamsft/azure-sdk-for-net,shutchings/azure-sdk-for-net,pattipaka/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,ogail/azure-sdk-for-net,Nilambari/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shutchings/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,relmer/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,gubookgu/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,nemanja88/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,namratab/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,r22016/azure-sdk-for-net,rohmano/azure-sdk-for-net,nathannfan/azure-sdk-for-net,huangpf/azure-sdk-for-net,hallihan/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,shutchings/azure-sdk-for-net,dasha91/azure-sdk-for-net,pattipaka/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,herveyw/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,lygasch/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,hyonholee/azure-sdk-for-net,rohmano/azure-sdk-for-net,abhing/azure-sdk-for-net,shuainie/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,hovsepm/azure-sdk-for-net,marcoippel/azure-sdk-for-net,naveedaz/azure-sdk-for-net,pinwang81/azure-sdk-for-net,abhing/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,pilor/azure-sdk-for-net,marcoippel/azure-sdk-for-net,olydis/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,dominiqa/azure-sdk-for-net,vladca/azure-sdk-for-net,scottrille/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,peshen/azure-sdk-for-net,ogail/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,alextolp/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,dominiqa/azure-sdk-for-net,naveedaz/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,akromm/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,guiling/azure-sdk-for-net,travismc1/azure-sdk-for-net,shipram/azure-sdk-for-net,Nilambari/azure-sdk-for-net,xindzhan/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,jtlibing/azure-sdk-for-net,shuagarw/azure-sdk-for-net,naveedaz/azure-sdk-for-net,pankajsn/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,oburlacu/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,begoldsm/azure-sdk-for-net,kagamsft/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,pankajsn/azure-sdk-for-net,atpham256/azure-sdk-for-net,nathannfan/azure-sdk-for-net,begoldsm/azure-sdk-for-net,amarzavery/azure-sdk-for-net,namratab/azure-sdk-for-net,AuxMon/azure-sdk-for-net,tpeplow/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,vladca/azure-sdk-for-net,pilor/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,relmer/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,zaevans/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,alextolp/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,mabsimms/azure-sdk-for-net,cwickham3/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,mihymel/azure-sdk-for-net,jamestao/azure-sdk-for-net,arijitt/azure-sdk-for-net,amarzavery/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ailn/azure-sdk-for-net,samtoubia/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,herveyw/azure-sdk-for-net,stankovski/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,vhamine/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,pinwang81/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,akromm/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,oaastest/azure-sdk-for-net,guiling/azure-sdk-for-net,markcowl/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,scottrille/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,smithab/azure-sdk-for-net,oburlacu/azure-sdk-for-net,olydis/azure-sdk-for-net,zaevans/azure-sdk-for-net,kagamsft/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,hyonholee/azure-sdk-for-net,zaevans/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,AzCiS/azure-sdk-for-net,alextolp/azure-sdk-for-net,smithab/azure-sdk-for-net,stankovski/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,nacaspi/azure-sdk-for-net,vladca/azure-sdk-for-net,yoreddy/azure-sdk-for-net,jamestao/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,enavro/azure-sdk-for-net | microsoft-azure-api/Configuration/Microsoft.WindowsAzure.Configuration/Properties/AssemblyInfo.cs | microsoft-azure-api/Configuration/Microsoft.WindowsAzure.Configuration/Properties/AssemblyInfo.cs | //
// Copyright 2012 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("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyDescription("Configuration API for Windows Azure services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a4d8eda-db18-4c6f-9f84-4576bb255f30")]
[assembly: AssemblyVersion("1.8.0.0")]
[assembly: AssemblyFileVersion("1.8.0.0")]
| //
// Copyright 2012 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("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyDescription("Configuration API for Windows Azure services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a4d8eda-db18-4c6f-9f84-4576bb255f30")]
[assembly: AssemblyVersion("1.7.0.0")]
[assembly: AssemblyFileVersion("1.7.0.0")]
| mit | C# |
3e2b766ee373ca25854a43b98cbe32ad143fc53e | Use axes | Procrat/orpheus | Assets/PlayerController.cs | Assets/PlayerController.cs |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private Rigidbody2D body;
void Start ()
{
body = GetComponent<Rigidbody2D> ();
}
void FixedUpdate ()
{
HandleInput ();
}
private void HandleInput ()
{
if (Input.GetButtonDown ("Cancel")) {
Debug.Log ("Quitting.");
Application.Quit ();
}
Move (Input.GetAxis ("Horizontal"));
// Temporary shortcut to win/die
if (Input.GetKeyDown ("space")) {
Win ();
}
}
private void Move (float horizontalTranslation)
{
var translationVector = new Vector2 (horizontalTranslation, 0);
transform.Translate (moveSpeed * translationVector);
}
public void Win ()
{
Debug.Log ("Hooray! You won!");
SceneManager.LoadScene ("End");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private Rigidbody2D body;
void Start ()
{
body = GetComponent<Rigidbody2D> ();
}
void FixedUpdate ()
{
HandleInput ();
}
private void HandleInput ()
{
if (Input.GetKeyDown (KeyCode.Escape) || Input.GetKeyDown (KeyCode.Q)) {
Debug.Log ("Quitting.");
Application.Quit ();
}
if (Input.GetKey (KeyCode.RightArrow)) {
MoveRight ();
} else if (Input.GetKey (KeyCode.LeftArrow)) {
MoveLeft ();
}
// Temporary shortcut to win/die
if (Input.GetKeyDown ("space")) {
Win ();
}
}
private void MoveLeft ()
{
Move (Vector2.left);
}
private void MoveRight ()
{
Move (Vector2.right);
}
private void Move (Vector2 translationVector)
{
transform.Translate (moveSpeed * translationVector);
}
public void Win ()
{
Debug.Log ("Hooray! You won!");
SceneManager.LoadScene ("End");
}
}
| mit | C# |
ffb059e6e4719be7b1b2916ed83d7aea69ba82d8 | Add MemoryStreamCache | yufeih/Common | src/MemoryStreamCache.cs | src/MemoryStreamCache.cs | using System.Threading;
using System.Text;
namespace System.IO
{
internal static class MemoryStreamCache
{
private const int MAX_BUILDER_SIZE = 1024;
private const int DEFAULT_CAPACITY = 256;
[ThreadStatic]
private static MemoryStream t_cachedInstance;
public static MemoryStream Acquire(int capacity = DEFAULT_CAPACITY)
{
if (capacity <= MAX_BUILDER_SIZE)
{
MemoryStream ms = MemoryStreamCache.t_cachedInstance;
if (ms != null)
{
// Avoid MemoryStream block fragmentation by getting a new MemoryStream
// when the requested size is larger than the current capacity
if (capacity <= ms.Capacity)
{
MemoryStreamCache.t_cachedInstance = null;
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
}
}
return new MemoryStream(capacity);
}
public static void Release(MemoryStream ms)
{
if (ms.Capacity <= MAX_BUILDER_SIZE)
{
MemoryStreamCache.t_cachedInstance = ms;
}
}
public static byte[] GetBytesAndRelease(MemoryStream ms)
{
byte[] result = ms.ToArray();
Release(ms);
return result;
}
}
}
| mit | C# | |
5b8f0933b771d7d924684027b6aa455b32ff9a80 | Define 'I{ReadOnly,}Collection' | jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm | stdlib/corlib/Collections.Generic/ICollection.cs | stdlib/corlib/Collections.Generic/ICollection.cs | namespace System.Collections.Generic
{
/// <summary>
/// A read-only view of a collection of elements.
/// </summary>
public interface IReadOnlyCollection<out T> : IEnumerable<T>
{
/// <summary>
/// Gets the number of elements in the collection.
/// </summary>
/// <returns>The number of elements in the collection.</returns>
int Count { get; }
}
/// <summary>
/// A mutable view of a collection of elements.
/// </summary>
public interface ICollection<T> : IReadOnlyCollection<T>
{
/// <summary>
/// Tells if the collection is read-only.
/// </summary>
/// <returns>
/// <c>true</c> if the collection is read-only; otherwise, <c>false</c>.
/// </returns>
bool IsReadOnly { get; }
/// <summary>
/// Adds an element to the collection.
/// </summary>
/// <param name="value">The value to add.</param>
void Add(T value);
/// <summary>
/// Removes all elements from the collection.
/// </summary>
void Clear();
/// <summary>
/// Checks if the collection contains a value.
/// </summary>
/// <param name="value">A value.</param>
/// <returns>
/// <c>true</c> if the collection contains the value; otherwise, <c>false</c>.
/// </returns>
bool Contains(T value);
/// <summary>
/// Copies the contents of the collection to an array, starting
/// at an offset in the array.
/// </summary>
/// <param name="destination">The destination array.</param>
/// <param name="offset">
/// The offset where the first element of this collection is placed.
/// </param>
void CopyTo(T[] destination, int offset);
/// <summary>
/// Removes the first occurrence of an element from the collection.
/// </summary>
/// <param name="value">The value to remove.</param>
/// <returns>
/// <c>true</c> an element was removed; otherwise, <c>false</c>.
/// </returns>
bool Remove(T value);
}
} | mit | C# | |
9fd380f8b5eb6fc53a7d752dda4f061780ada735 | Create Loadbutton.cs | jon-lad/Battlefleet-Gothic | MainMenu/Loadbutton.cs | MainMenu/Loadbutton.cs | using UnityEngine;
using System.Collections;
public class LoadButton : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseOver(){
renderer.material.color = new Color32(212,11,57, 255);
}
void OnMouseExit(){
renderer.material.color = new Color(1 -(214 / 255),1 - (185 / 255),1 -(167 / 255));
}
void OnMouseDown(){
GameData.instance.Load ("save");
}
}
| mit | C# | |
6fee09a105af581ee90a5d22373f2cb3c572dbe6 | Add Track class | goshippo/shippo-csharp-client | Shippo/Track.cs | Shippo/Track.cs | using System;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Track : ShippoId {
[JsonProperty (PropertyName = "carrier")]
public object Carrier { get; set; }
[JsonProperty (PropertyName = "tracking_number")]
public object TrackingNumber { get; set; }
[JsonProperty (PropertyName = "address_from")]
public object AddressFrom { get; set; }
[JsonProperty (PropertyName = "address_to")]
public object AddressTo { get; set; }
[JsonProperty (PropertyName = "eta")]
public object Eta { get; set; }
[JsonProperty (PropertyName = "servicelevel")]
public object Servicelevel { get; set; }
[JsonProperty (PropertyName = "tracking_status")]
public object TrackingStatus { get; set; }
[JsonProperty (PropertyName = "tracking_history")]
public object TrackingHistory { get; set; }
[JsonProperty (PropertyName = "metadata")]
public object Metadata { get; set; }
}
}
| apache-2.0 | C# | |
7909f6b0d516b23bd0bf21a5411916ce22e1204e | Create Gothic.cs | jon-lad/Battlefleet-Gothic | Ships/Imperial/Cruiser/Gothic.cs | Ships/Imperial/Cruiser/Gothic.cs | using UnityEngine;
using System.Collections;
public class Gothic : Ship {
// Use this for initialization
public override void Start () {
base.Start ();
stand = (GameObject)Instantiate(GameData.instance.SmallStandPrefab, transform.position, Quaternion.Euler(new Vector3()));
hits = 8;
speed = 20;
minMove = speed / 2;
turns = 45;
shields = 2;
armour = 5;
turrets = 2;
minTurnDistance = 10;
maxMove = speed;
baseMinTurnDistance = 10;
stand.transform.parent = transform;
remainingHits = hits;
activeShields = shields;
shipType = 1;
Weapon portLanceBattery = new Weapon();
weapons.Add (portLanceBattery);
Weapon starboardLanceBattery = new Weapon();
weapons.Add (starboardLanceBattery);
portLanceBattery.type = 0;
portLanceBattery.range = 30;
portLanceBattery.strength = 4;
portLanceBattery.maxFireArc = -45;
portLanceBattery.minFireArc = -135;
portLanceBattery.weaponName = "Port Lance Batt.";
starboardLanceBattery.type = 0;
starboardLanceBattery.range = 30;
starboardLanceBattery.strength = 4;
starboardLanceBattery.maxFireArc = 135;
starboardLanceBattery.minFireArc = 45;
starboardLanceBattery.weaponName = "Strbd Lance Batt.";
}
public override void Update () {
base.Update ();
}
}
| mit | C# | |
e64e5b76b3da71844f026c882ba91d938187fc42 | add Product.cs (#24) | tbauer516/Mobilize.net,tbauer516/Mobilize.net,tbauer516/Mobilize.net | SalmonKingSeafood/SalmonKingSeafood/products/Product.cs | SalmonKingSeafood/SalmonKingSeafood/products/Product.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
namespace SalmonKingSeafood
{
public class Product
{
public static string ProductSQL(HttpContext Context, String[] data, String[] info)
{
using (System.Data.SqlClient.SqlConnection dbconnect = new SqlConnection(ConfigurationManager.ConnectionStrings["SKSData"].ToString()))
{
var results = new List<Dictionary<string, object>>();
string cmdString = "exec usp" + data[0] + "Product @" + info[0] + " = '" + data[1] + "'";
for (var i = 1; i < info.Length; i++)
{
cmdString += ", @" + info[i] + " = '" + data[i + 1] + "'";
}
Console.WriteLine(cmdString);
SqlCommand addProductCmd = new SqlCommand(cmdString, dbconnect);
dbconnect.Open();
using (SqlDataReader reader = addProductCmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var item = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
item.Add(reader.GetName(i), reader.IsDBNull(i) ? null : reader.GetValue(i));
}
results.Add(item);
}
}
}
dbconnect.Close();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
return new JavaScriptSerializer().Serialize(results);
}
}
public static string SQLViewProduct(HttpContext Context)
{
using (System.Data.SqlClient.SqlConnection dbconnect = new SqlConnection(ConfigurationManager.ConnectionStrings["SKSData"].ToString()))
{
var results = new List<Dictionary<string, object>>();
string cmdString = "SELECT * FROM tblPRODUCT";
SqlCommand FindProductCmd = new SqlCommand(cmdString, dbconnect);
dbconnect.Open();
using (SqlDataReader reader = FindProductCmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var item = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
item.Add(reader.GetName(i), reader.IsDBNull(i) ? null : reader.GetValue(i));
}
results.Add(item);
}
}
}
dbconnect.Close();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
return new JavaScriptSerializer().Serialize(results);
}
}
}
} | mit | C# | |
7a1d6581e5932ebbe6b34b2ce3f2e5a166b948cb | Create StringAccumulator.cs | Zephyr-Koo/sololearn-challenge | StringAccumulator.cs | StringAccumulator.cs | using System;
using System.Collections.Generic;
using System.Linq;
// https://www.sololearn.com/Discuss/687819/?ref=app
namespace SoloLearn
{
class Program
{
static void Main(string[] zephyr_koo)
{
foreach (var str in new string[]
{
"abc", "ECxa", "XmkkucH", "SoloLearN", "QpYWffvYGGyaX"
})
{
Console.WriteLine(str);
Console.WriteLine(GetAccumulatedString(str) + Environment.NewLine);
}
}
static string GetAccumulatedString(string str)
{
str = str.ToLower(); // optimize for repetitive usage of char.ToLower(c) in Enumerable.Repeat
return string.Join("-", str.Select(
(c, i) => c.ToString().ToUpper() +
new string(Enumerable.Repeat(c, i).ToArray())
));
}
}
}
| apache-2.0 | C# | |
ec5c967e71343396224e9769ef21126b91d581fa | Add test coverage of `SettingsCheckbox` | NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu | osu.Game.Tests/Visual/UserInterface/TestSceneSettingsCheckbox.cs | osu.Game.Tests/Visual/UserInterface/TestSceneSettingsCheckbox.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osuTK;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneSettingsCheckbox : OsuTestScene
{
[TestCase]
public void TestCheckbox()
{
AddStep("create component", () =>
{
FillFlowContainer flow;
Child = flow = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 500,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(5),
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "a sample component",
},
},
};
foreach (var colour1 in Enum.GetValues(typeof(OverlayColourScheme)).OfType<OverlayColourScheme>())
{
flow.Add(new OverlayColourContainer(colour1)
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Child = new SettingsCheckbox
{
LabelText = "a sample component",
}
});
}
});
}
private class OverlayColourContainer : Container
{
[Cached]
private OverlayColourProvider colourProvider;
public OverlayColourContainer(OverlayColourScheme scheme)
{
colourProvider = new OverlayColourProvider(scheme);
}
}
}
}
| mit | C# | |
65d3347a74615a89dc56724cf4c77954c5d05467 | Add type extension method | xin9le/DeclarativeSql | src/DeclarativeSql/Internals/TypeExtensions.cs | src/DeclarativeSql/Internals/TypeExtensions.cs | using System;
namespace DeclarativeSql.Internals
{
/// <summary>
/// Provides <see cref="Type"/> extension methods.
/// </summary>
internal static class TypeExtensions
{
/// <summary>
/// Gets whether specified type is <see cref="Nullable{T}"/>.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsNullable(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
}
}
| mit | C# | |
be83d17dcf1ffb7316df47e77099c34984fb2b83 | Add unit tests for Users API controller | meutley/ISTS | src/Api.Test/Controllers/UsersControllerTests.cs | src/Api.Test/Controllers/UsersControllerTests.cs | using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
using ISTS.Api.Controllers;
using ISTS.Api.Helpers;
using ISTS.Application.Users;
namespace ISTS.Api.Test.Controllers
{
public class UsersControllerTests
{
private Mock<IOptions<ApplicationSettings>> _options;
private Mock<IUserService> _userService;
private UsersController _usersController;
public UsersControllerTests()
{
_options = new Mock<IOptions<ApplicationSettings>>();
_userService = new Mock<IUserService>();
_usersController = new UsersController(_options.Object, _userService.Object);
}
[Fact]
public async void Register_Returns_OkObjectResult_With_UserDto()
{
var dto = new UserPasswordDto
{
Email = "my@email.com",
DisplayName = "My User",
PostalCode = "11111"
};
var expectedModel = new UserDto
{
Id = Guid.NewGuid(),
Email = dto.Email,
DisplayName = dto.DisplayName,
PostalCode = dto.PostalCode
};
_userService
.Setup(s => s.CreateAsync(It.IsAny<UserPasswordDto>()))
.Returns(Task.FromResult(expectedModel));
var result = await _usersController.Register(dto);
Assert.IsType<OkObjectResult>(result);
var okResult = result as OkObjectResult;
Assert.IsType<UserDto>(okResult.Value);
var model = okResult.Value as UserDto;
Assert.Equal(expectedModel.Id, model.Id);
Assert.Equal(expectedModel.Email, model.Email);
Assert.Equal(expectedModel.DisplayName, model.DisplayName);
Assert.Equal(expectedModel.PostalCode, model.PostalCode);
}
[Fact]
public async void Authenticate_Returns_UnauthorizedResult()
{
var dto = new UserPasswordDto
{
Email = "my@email.com",
Password = "BadP@ssw0rd"
};
_userService
.Setup(s => s.AuthenticateAsync(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult<UserDto>(null));
var result = await _usersController.Authenticate(dto);
Assert.IsType<UnauthorizedResult>(result);
}
}
} | mit | C# | |
d22d13ef49ac7fcc7878a519c1d19d334f65cf40 | Create XMLParse.cs | ellivr/PersonalSnippets | CSharp/XMLParse.cs | CSharp/XMLParse.cs | public static void ParseSave(string filename)
{
byte[] Data = new byte[SteamRemoteStorage.GetFileSize(filename)];
int ret = SteamRemoteStorage.FileRead(filename, Data, Data.Length);
string m_Message = System.Text.Encoding.UTF8.GetString(Data, 0, ret);
PSTTool.Log(m_Message);
using (XmlReader reader = XmlReader.Create(new StringReader(m_Message)))
{
while (reader.Read())
{
// Only detect start elements.
if (reader.IsStartElement())
{
// Get element name and switch on it.
switch (reader.Name)
{
case "validity":
if (reader.Read())
{
PSTTool.Log("Validity: " + reader.Value.Trim());
}
break;
case "steamid":
if (reader.Read())
{
PSTTool.Log("SteamID: " + reader.Value.Trim());
}
break;
case "data_type":
if (reader.Read())
{
PSTTool.Log("Data Type: " + reader.Value.Trim());
}
break;
case "data_version":
if (reader.Read())
{
PSTTool.Log("Data Version: " + reader.Value.Trim());
}
break;
case "loginname":
if (reader.Read())
{
PSTTool.Log("Login Name: " + reader.Value.Trim());
}
break;
}
}
}
}
}
| mit | C# | |
e52d76e3d84d26f0f50302f20522197b1ec9906f | Refactor exporter - step 1 (#1078) | open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet | src/OpenTelemetry/Trace/ActivityExporterSync.cs | src/OpenTelemetry/Trace/ActivityExporterSync.cs | // <copyright file="ActivityExporterSync.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace OpenTelemetry.Trace
{
/// <summary>
/// Enumeration used to define the result of an export operation.
/// </summary>
public enum ExportResultSync
{
/// <summary>
/// Batch export succeeded.
/// </summary>
Success = 0,
/// <summary>
/// Batch export failed.
/// </summary>
Failure = 1,
}
/// <summary>
/// ActivityExporterSync base class.
/// </summary>
public abstract class ActivityExporterSync : IDisposable
{
/// <summary>
/// Exports batch of activities.
/// </summary>
/// <param name="batch">Batch of activities to export.</param>
/// <returns>Result of export.</returns>
public abstract ExportResult Export(IEnumerable<Activity> batch);
/// <summary>
/// Shuts down the exporter.
/// </summary>
public virtual void Shutdown()
{
}
/// <inheritdoc/>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by this class and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
}
}
}
| apache-2.0 | C# | |
ad3985dbfa6771ed5c3008c21612c53d223b14d4 | Create Movable.cs | xxmon/unity | Movable/Movable.cs | Movable/Movable.cs | using UnityEngine;
[System.Serializable]
public class Movable : MonoBehaviour
{
public GameObject target;
public bool isMovable = true;
public GameObject GetTarget ()
{
if (target == null) {
return gameObject;
} else {
return target;
}
}
}
| mit | C# | |
43e4637cccff93162305dba4641bf53a7a4cab24 | Create an Environment class to store variable definitions | escamilla/squirrel | squirrel/Environment.cs | squirrel/Environment.cs | using System.Collections.Generic;
namespace squirrel
{
public class Environment
{
private readonly Environment _parent;
private readonly Dictionary<string, AstNode> _definitions = new Dictionary<string, AstNode>();
public Environment(Environment parent)
{
_parent = parent;
}
public Environment() : this(null)
{
}
public void Add(string name, AstNode value)
{
_definitions.Add(name, value);
}
public AstNode? Get(string name)
{
return GetShallow(name) ?? _parent.Get(name);
}
private AstNode? GetShallow(string name)
{
if (_definitions.ContainsKey(name))
{
return _definitions[name];
}
return null;
}
}
}
| mit | C# | |
b06f59ffdcf99454bb4447b7e4efb936ebb0f399 | Split out test for combo counter specifically | ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu | osu.Game.Tests/Visual/Gameplay/TestSceneComboCounter.cs | osu.Game.Tests/Visual/Gameplay/TestSceneComboCounter.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneComboCounter : SkinnableTestScene
{
private IEnumerable<SkinnableComboCounter> comboCounters => CreatedDrawables.OfType<SkinnableComboCounter>();
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
[SetUpSteps]
public void SetUpSteps()
{
AddStep("Create combo counters", () => SetContents(() =>
{
var comboCounter = new SkinnableComboCounter();
comboCounter.Current.Value = 1;
return comboCounter;
}));
}
[Test]
public void TestComboCounterIncrementing()
{
AddRepeatStep("increase combo", () =>
{
foreach (var counter in comboCounters)
counter.Current.Value++;
}, 10);
AddStep("reset combo", () =>
{
foreach (var counter in comboCounters)
counter.Current.Value = 0;
});
}
}
}
| mit | C# | |
4468b0596f785404debb8fec7e053f9cfd71804f | Add InterpolationTest for C#. | msteinbeck/tinyspline,msteinbeck/tinyspline,msteinbeck/tinyspline,msteinbeck/tinyspline,msteinbeck/tinyspline,msteinbeck/tinyspline,msteinbeck/tinyspline,msteinbeck/tinyspline | test/csharp/InterpolationTest.cs | test/csharp/InterpolationTest.cs | using NUnit.Framework;
using System.Collections.Generic;
using TinySpline;
namespace csharp;
public class InterpolationTest
{
class Vec2EqualityComparer : IEqualityComparer<Vec2>
{
public bool Equals(Vec2 v1, Vec2 v2)
{
if (v1 == null && v2 == null) return true;
if (v1 == null || v2 == null) return false;
return v1.Distance(v2) <= tinysplinecsharp.TS_POINT_EPSILON;
}
public int GetHashCode(Vec2 vec)
{
double hCode = vec.X * vec.Y;
return hCode.GetHashCode();
}
}
[Test]
public void TestOpened()
{
// Given
List<double> points = new List<double> {
1.0, -1.0, // P1
-1.0, 2.0, // P2
1.0, 4.0, // P3
4.0, 3.0, // P4
7.0, 5.0 // P5
};
Vec2EqualityComparer comparer = new Vec2EqualityComparer();
// When
BSpline spline = BSpline.InterpolateCubicNatural(points, 2);
// Then
Assert.That(spline.NumControlPoints, Is.EqualTo(16));
// First bezier segment
Assert.That(spline.ControlPointVec2At(0),
Is.EqualTo(new Vec2(1, -1))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(1),
Is.EqualTo(new Vec2(0, 0))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(2),
Is.EqualTo(new Vec2(-1, 1))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(3),
Is.EqualTo(new Vec2(-1, 2))
.Using(comparer));
// Second bezier segment
Assert.That(spline.ControlPointVec2At(4),
Is.EqualTo(new Vec2(-1, 2))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(5),
Is.EqualTo(new Vec2(-1, 3))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(6),
Is.EqualTo(new Vec2(0, 4))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(7),
Is.EqualTo(new Vec2(1, 4))
.Using(comparer));
// Third bezier segment
Assert.That(spline.ControlPointVec2At(8),
Is.EqualTo(new Vec2(1, 4))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(9),
Is.EqualTo(new Vec2(2, 4))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(10),
Is.EqualTo(new Vec2(3, 3))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(11),
Is.EqualTo(new Vec2(4, 3))
.Using(comparer));
// Forth bezier segment
Assert.That(spline.ControlPointVec2At(12),
Is.EqualTo(new Vec2(4, 3))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(13),
Is.EqualTo(new Vec2(5, 3))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(14),
Is.EqualTo(new Vec2(6, 4))
.Using(comparer));
Assert.That(spline.ControlPointVec2At(15),
Is.EqualTo(new Vec2(7, 5))
.Using(comparer));
}
}
| mit | C# | |
de6a8ae01f32ae6827d05272f2eb48ad17d785d7 | Add test for racecondition issue | MrHant/tiver-fowl.Drivers,MrHant/tiver-fowl.Drivers | Tiver.Fowl.Drivers.Tests/DownloadersParallel.cs | Tiver.Fowl.Drivers.Tests/DownloadersParallel.cs | using System.IO;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
using Tiver.Fowl.Drivers.Configuration;
using Tiver.Fowl.Drivers.DriverBinaries;
using Tiver.Fowl.Drivers.DriverDownloaders;
namespace Tiver.Fowl.Drivers.Tests
{
[TestFixture]
public class DownloadersParallel
{
private static DriversConfiguration Config
{
get
{
var driversConfiguration = new DriversConfiguration();
var config = new ConfigurationBuilder()
.AddJsonFile("Tiver_config.json", optional: true)
.Build();
config.GetSection("Tiver.Fowl.Drivers").Bind(driversConfiguration);
return driversConfiguration;
}
}
private static string[] Platforms = {"win32", "linux64"};
private static string BinaryName(string platform)
{
return platform switch
{
"win32" => "chromedriver.exe",
_ => "chromedriver"
};
}
private static string DriverFilepath(string platform)
{
return Path.Combine(Config.DownloadLocation, BinaryName(platform));
}
private void DeleteDriverAndVersionFilesIfExist()
{
foreach (var platform in Platforms)
{
if (File.Exists(DriverFilepath(platform)))
{
File.Delete(DriverFilepath(platform));
}
var versionFilepath = Path.Combine(Config.DownloadLocation, $"{BinaryName(platform)}.version");
if (File.Exists(versionFilepath))
{
File.Delete(versionFilepath);
}
}
}
[OneTimeSetUp]
public void SetUp()
{
DeleteDriverAndVersionFilesIfExist();
}
[Test, Parallelizable(ParallelScope.All)]
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
public void Download_ParallelTests(int threadNumber)
{
var downloader = new ChromeDriverDownloader();
const string versionNumber = "76.0.3809.25";
var result = downloader.DownloadBinary(versionNumber, "win32");
Assert.IsTrue(result.Successful, $"Reported error message:{result.ErrorMessage}");
Assert.AreEqual(DownloaderAction.BinaryDownloaded, result.PerformedAction);
Assert.IsNull(result.ErrorMessage);
var exists = File.Exists(DriverFilepath("win32"));
Assert.IsTrue(exists);
exists = downloader.Binary.CheckBinaryExists();
Assert.IsTrue(exists);
Assert.AreEqual(versionNumber, downloader.Binary.GetExistingBinaryVersion());
}
}
}
| mit | C# | |
6b61b74db1c85b2bd2865be1a7e4dfd56d367bad | Add TimeControl model | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/Models/Variant960/TimeControl.cs | src/ChessVariantsTraining/Models/Variant960/TimeControl.cs | using MongoDB.Bson.Serialization.Attributes;
namespace ChessVariantsTraining.Models.Variant960
{
public class TimeControl
{
[BsonElement("initial")]
public int InitialSeconds
{
get;
set;
}
[BsonElement("increment")]
public int Increment
{
get;
set;
}
public TimeControl() { }
public TimeControl(int secondsInitial, int secondsIncrement)
{
InitialSeconds = secondsInitial;
Increment = secondsIncrement;
}
public override string ToString()
{
string minutes;
switch (InitialSeconds)
{
case 30:
minutes = "½";
break;
case 45:
minutes = "¾";
break;
case 90:
minutes = "1.5";
break;
default:
minutes = (InitialSeconds / 60).ToString();
break;
}
return string.Format("{0}+{1}", minutes, Increment);
}
}
}
| agpl-3.0 | C# | |
624bc7273dd6960a3e0a7dc881e86878f0acf14f | Add helper. | Grabacr07/MetroTrilithon | src/MetroTrilithon.Desktop/UI/Controls/NavigationHelper.cs | src/MetroTrilithon.Desktop/UI/Controls/NavigationHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Xaml.Behaviors;
using WPFUI.Controls;
namespace MetroTrilithon.UI.Controls;
public class NavigationHelper
{
#region PropagationContext attached property
private static readonly HashSet<Navigation> _knownItems = new();
public static readonly DependencyProperty PropagationContextProperty
= DependencyProperty.RegisterAttached(
nameof(PropagationContextProperty).GetPropertyName(),
typeof(object),
typeof(NavigationHelper),
new PropertyMetadata(null, HandlePropagationContextChanged));
public static void SetPropagationContext(DependencyObject element, object value)
=> element.SetValue(PropagationContextProperty, value);
public static object GetPropagationContext(DependencyObject element)
=> element.GetValue(PropagationContextProperty);
private static void HandlePropagationContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not NavigationItem item) throw new NotSupportedException($"The '{nameof(PropagationContextProperty).GetPropertyName()}' attached property is only supported for the '{nameof(NavigationItem)}' type.");
var navigation = item.GetSelfAndAncestors()
.OfType<Navigation>()
.FirstOrDefault();
if (navigation == null || _knownItems.Add(navigation) == false) return;
navigation.Navigated += HandleNavigated;
}
private static void HandleNavigated(object sender, RoutedEventArgs e)
{
if (sender is Navigation { Current: NavigationItem { Instance: FrameworkElement { DataContext: null } element } item })
{
element.DataContext = GetPropagationContext(item);
}
}
#endregion
}
| mit | C# | |
250b79c069225ad15f2f22755aca9145a13710d9 | add whocalls.cs | smoothdeveloper/SimpleScene,Namone/SimpleScene,RealRui/SimpleScene,jeske/SimpleScene | WavefrontOBJViewer/SimpleScene/Util/WhoCalls.cs | WavefrontOBJViewer/SimpleScene/Util/WhoCalls.cs | // Copyright(C) David W. Jeske, 2012
// Released to the public domain. Use, modify and relicense at will.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
// no-inlining seems to be broken on x64
// https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=162364&wa=wsignin1.0
namespace Bend {
public class WhoCalls
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static string WhatsMyName()
{
StackFrame stackFrame = new StackFrame();
MethodBase methodBase = stackFrame.GetMethod();
return methodBase.Name;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string WhoCalledMe()
{
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(2);
MethodBase methodBase = stackFrame.GetMethod();
return String.Format("{0}:{1}:{2}",
stackFrame.GetFileName(),
stackFrame.GetFileLineNumber(),
methodBase.Name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string StackTrace() {
string ss = "";
StackTrace stackTrace = new StackTrace();
for(int x=0;x<stackTrace.FrameCount;x++) {
StackFrame stackFrame = stackTrace.GetFrame(x);
ss = ss + stackFrame.GetMethod().Name + ":" + stackFrame.GetFileName() + ":" + stackFrame.GetFileLineNumber() + " ";
}
return ss;
}
}
}
#if BUILD_TESTS
namespace BendTests
{
using Bend;
using NUnit.Framework;
[TestFixture]
public class ZZ_TODO_WhoCalls
{
[MethodImpl(MethodImplOptions.NoInlining)]
public string TestWhatsMyName() {
return WhoCalls.WhatsMyName();
}
//[MethodImpl(MethodImplOptions.NoInlining)]
//public string TestWhoCalledMe() {
// return WhoCalls.WhoCalledMe();
//}
[Test]
[MethodImpl(MethodImplOptions.NoInlining)]
public void T00_WhoCalls()
{
Assert.AreEqual("TestWhatsMyName", TestWhatsMyName(), "1");
//Assert.AreEqual("T00_WhoCalls", TestWhoCalledMe(), "2");
}
}
}
#endif | apache-2.0 | C# | |
4d46b581c3095ceaa2bb698c569ca20e0ddc0a0b | Add some initial examples. | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | csharp/ql/test/utils/model-generator/Summaries.cs | csharp/ql/test/utils/model-generator/Summaries.cs | using System;
namespace Summaries;
public class BasicFlow
{
public BasicFlow ReturnThis(object input)
{
return this;
}
public string ReturnParam0(string input0, object input1)
{
return input0;
}
public object ReturnParam1(string input0, object input1)
{
return input1;
}
public object ReturnParamMultiple(object input0, object input1)
{
return (System.DateTime.Now.DayOfWeek == System.DayOfWeek.Monday) ? input0 : input1;
}
public int ReturnArrayElement(int[] input)
{
return input[0];
}
public void AssignToArray(int data, int[] target)
{
target[0] = data;
}
}
| mit | C# | |
228c5edaa84e293cb056dbc74cb2053c86207a56 | Add Profile Ewerton Jordao | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/EwertonJordao.cs | src/Firehose.Web/Authors/EwertonJordao.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 EwertonJordao : IAmAMicrosoftMVP
{
public string FirstName => "Ewerton";
public string LastName => "Jordão";
public string ShortBioOrTagLine => "Automation lover, Speaker at .NetSP, DevOps Professionals , Azure Talks, SampaDevs. Technical Author, MVP Azure";
public string StateOrRegion => "São Paulo, Brazil";
public string EmailAddress => "";
public string GravatarHash => "70ac0c6fd63afc54ddf5e3c927f51d02";
public string TwitterHandle => "EwertonJordao";
public string GitHubHandle => "EwertonJordao";
public GeoPosition Position => new GeoPosition(-23.536729, -46.635690);
public Uri WebSite => new Uri("https://medium.com/@ewertonjordao");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@ewertonjordao"); } }
public string FeedLanguageCode => "en";
}
}
| mit | C# | |
e8b29dd284c9622e9585cb9ff321372a101a7c4f | Create IProtocolResponse.cs | poostwoud/discovery | src/Library/Protocol/IProtocolResponse.cs | src/Library/Protocol/IProtocolResponse.cs | namespace Discovery.Library.Protocol
{
public interface IProtocolResponse
{
string Result { get; }
}
}
| mit | C# | |
dfe21461bfdc281dae49ff6cb0cf62696bacb3e9 | Create MongoRepositoryTests.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/Data/Mongo/MongoRepositoryTests.cs | TIKSN.Framework.IntegrationTests/Data/Mongo/MongoRepositoryTests.cs | using System;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace TIKSN.Framework.IntegrationTests.Data.Mongo
{
[Collection("ServiceProviderCollection")]
public class MongoRepositoryTests
{
private readonly ServiceProviderFixture _serviceProviderFixture;
public MongoRepositoryTests(ServiceProviderFixture serviceProviderFixture)
{
_serviceProviderFixture = serviceProviderFixture;
}
[Fact]
public async Task TestCreationAndRetrieval()
{
var testRepository = _serviceProviderFixture.Services.GetRequiredService<ITestMongoRepository>();
var testEntityId = Guid.NewGuid();
var testEntity = new TestMongoEntity
{
ID = testEntityId,
Value = Guid.NewGuid()
};
await testRepository.AddAsync(testEntity, default);
var retrievedEntity = await testRepository.GetAsync(testEntityId, default);
retrievedEntity.Value.Should().Be(testEntity.Value);
}
}
} | mit | C# | |
b163b7d8b2fadf33747ed0aacd8ae4a40007c57e | Set Horizontal And Vertical Image Resolution | asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET,asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET,asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET,asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET | Examples/CSharp/Rendering-Printing/SetHorizontalAndVerticalImageResolution.cs | Examples/CSharp/Rendering-Printing/SetHorizontalAndVerticalImageResolution.cs | using Aspose.Words.Saving;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aspose.Words.Examples.CSharp.Rendering_Printing
{
class SetHorizontalAndVerticalImageResolution
{
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_RenderingAndPrinting();
// Load the documents
Document doc = new Document(dataDir + "TestFile.doc");
//Renders a page of a Word document into a PNG image at a specific horizontal and vertical resolution.
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png);
options.HorizontalResolution = 300;
options.VerticalResolution = 300;
options.PageCount = 1;
doc.Save(dataDir + "Rendering.SaveToImageResolution Out.png", options);
}
}
}
| mit | C# | |
100f1b9d4c35de13064e3e85589f4b1a2ac27617 | add MigrationResult.cs | commonsensesoftware/Its.Cqrs,commonsensesoftware/Its.Cqrs,commonsensesoftware/Its.Cqrs | Domain.Sql/Migrations/MigrationResult.cs | Domain.Sql/Migrations/MigrationResult.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Its.Domain.Sql.Migrations
{
public class MigrationResult
{
public string Log { get; set; }
public bool MigrationWasApplied { get; set; }
}
} | mit | C# | |
684d88ba7586eb361091f8e235b35c9dc3af54c5 | Add full OsuGame tests | ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu | osu.Game.Tests/Visual/Navigation/TestSceneButtonSystemNavigation.cs | osu.Game.Tests/Visual/Navigation/TestSceneButtonSystemNavigation.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.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Select;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestSceneButtonSystemNavigation : OsuGameTestScene
{
private ButtonSystem buttons => ((MainMenu)Game.ScreenStack.CurrentScreen).ChildrenOfType<ButtonSystem>().Single();
[Test]
public void TestGlobalActionHasPriority()
{
AddAssert("state is initial", () => buttons.State == ButtonSystemState.Initial);
// triggering the cookie in the initial state with any key should only happen if no other action is bound to that key.
// here, F10 is bound to GlobalAction.ToggleGameplayMouseButtons.
AddStep("press F10", () => InputManager.Key(Key.F10));
AddAssert("state is initial", () => buttons.State == ButtonSystemState.Initial);
AddStep("press P", () => InputManager.Key(Key.P));
AddAssert("state is top level", () => buttons.State == ButtonSystemState.TopLevel);
}
[Test]
public void TestShortcutKeys()
{
AddAssert("state is initial", () => buttons.State == ButtonSystemState.Initial);
AddStep("press P", () => InputManager.Key(Key.P));
AddAssert("state is top level", () => buttons.State == ButtonSystemState.TopLevel);
AddStep("press P", () => InputManager.Key(Key.P));
AddAssert("state is play", () => buttons.State == ButtonSystemState.Play);
AddStep("press P", () => InputManager.Key(Key.P));
AddAssert("entered song select", () => Game.ScreenStack.CurrentScreen is PlaySongSelect);
}
}
}
| mit | C# | |
accf9c1c72162ad3a65edac75dbc8558f9d26eab | Add KeyCombination Test | ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework | osu.Framework.Tests/Input/KeyCombinationTest.cs | osu.Framework.Tests/Input/KeyCombinationTest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.States;
using osuTK.Input;
using KeyboardState = osu.Framework.Input.States.KeyboardState;
namespace osu.Framework.Tests.Input
{
[TestFixture]
public class KeyCombinationTest
{
[Test]
public void TestKeyCombinationSortKeysWithTrueOrder()
{
var keyCombination = new KeyCombination(InputKey.R, InputKey.Shift, InputKey.Control);
Assert.AreEqual(keyCombination.Keys[0], InputKey.Control);
Assert.AreEqual(keyCombination.Keys[1], InputKey.Shift);
Assert.AreEqual(keyCombination.Keys[2], InputKey.R);
}
[Test]
public void TestKeyCombinationReadableStringDisplayTrueOrder()
{
var keyCombination1 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
var keyCombination2 = new KeyCombination(InputKey.R, InputKey.Shift, InputKey.Control);
Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
}
[Test]
public void TestKeyCombinationFromKeyboardStateReadableStringDisplayTrueOrder()
{
var keyboardState = new KeyboardState();
keyboardState.Keys.Add(Key.R);
keyboardState.Keys.Add(Key.LShift);
keyboardState.Keys.Add(Key.LControl);
var keyCombination1 = KeyCombination.FromInputState(new InputState(keyboard: keyboardState));
var keyCombination2 = new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.R);
Assert.AreEqual(keyCombination1.ReadableString(), keyCombination2.ReadableString());
}
}
}
| mit | C# | |
51489547a476015f9909909c26fb738b4eea28ec | Allow extending translations | bussemac/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,n2cms/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,bussemac/n2cms,DejanMilicic/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,nimore/n2cms,SntsDev/n2cms,DejanMilicic/n2cms,nicklv/n2cms,nimore/n2cms,nicklv/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,bussemac/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,nicklv/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,nimore/n2cms,nicklv/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,n2cms/n2cms,n2cms/n2cms | src/Mvc/MvcTemplates/N2/Web/AngularLocalizationHandler.cs | src/Mvc/MvcTemplates/N2/Web/AngularLocalizationHandler.cs | using N2.Web;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
namespace N2.Management.Web
{
public class AngularLocalizationHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
if (!context.IsDebuggingEnabled)
context.Response.SetOutputCache(DateTime.Now.AddHours(1));
context.Response.Write("(function (module) {");
context.Response.Write(@"
module.factory('Translate', function () {
return function (key, fallback) {
var t = translations;
var k = key.split('.');
for (var i in k) {
t = t[k[i]];
if (!t) return fallback;
}
return t;
}
});
");
context.Response.Write("var translations = ");
var jsPath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(0, context.Request.AppRelativeCurrentExecutionFilePath.Length - 5);
var file = HostingEnvironment.VirtualPathProvider.GetFile(jsPath);
using (var s = file.Open())
{
TransferBetweenStreams(s, context.Response.OutputStream);
}
context.Response.Write(";" + Environment.NewLine);
context.Response.Write("module.value('n2translations', translations);");
context.Response.Write("})(angular.module('n2.localization', []));");
}
long TransferBetweenStreams(Stream inputStream, Stream outputStream)
{
long inputStreamLength = 0;
byte[] buffer = new byte[32768];
while (true)
{
int bytesRead = inputStream.Read(buffer, 0, buffer.Length);
if (bytesRead <= 0)
break;
outputStream.Write(buffer, 0, bytesRead);
inputStreamLength += bytesRead;
}
return inputStreamLength;
}
}
} | using N2.Web;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
namespace N2.Management.Web
{
public class AngularLocalizationHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
if (!context.IsDebuggingEnabled)
context.Response.SetOutputCache(DateTime.Now.AddHours(1));
context.Response.Write("(function (module) {");
context.Response.Write(@"
module.factory('Translate', function () {
return function (key, fallback) {
var t = translations;
var k = key.split('.');
for (var i in k) {
t = t[k[i]];
if (!t) return fallback;
}
return t;
}
});
");
context.Response.Write("var translations = ");
var jsPath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(0, context.Request.AppRelativeCurrentExecutionFilePath.Length - 5);
var file = HostingEnvironment.VirtualPathProvider.GetFile(jsPath);
using (var s = file.Open())
{
TransferBetweenStreams(s, context.Response.OutputStream);
}
context.Response.Write("})(angular.module('n2.localization', []));");
}
long TransferBetweenStreams(Stream inputStream, Stream outputStream)
{
long inputStreamLength = 0;
byte[] buffer = new byte[32768];
while (true)
{
int bytesRead = inputStream.Read(buffer, 0, buffer.Length);
if (bytesRead <= 0)
break;
outputStream.Write(buffer, 0, bytesRead);
inputStreamLength += bytesRead;
}
return inputStreamLength;
}
}
} | lgpl-2.1 | C# |
14ddf6e7ec8df8ef3ead81f90890d05751dfb67c | Add interface for content validation | NicatorBa/Porthor | src/Porthor/ContentValidation/IContentValidator.cs | src/Porthor/ContentValidation/IContentValidator.cs | using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace Porthor.ContentValidation
{
public interface IContentValidator
{
Task<bool> Validate(HttpRequest request);
}
}
| apache-2.0 | C# | |
06e2455a867a99be12c4c22e58ce0b2670b0627b | Create HowToUse.cs | invalidred/Cross-platform-AES-encryption,Pakhee/Cross-platform-AES-encryption,Pakhee/Cross-platform-AES-encryption,invalidred/Cross-platform-AES-encryption,invalidred/Cross-platform-AES-encryption,Pakhee/Cross-platform-AES-encryption,MudassarMumtaz/Cross-platform-AES-encryption,MudassarMumtaz/Cross-platform-AES-encryption,MudassarMumtaz/Cross-platform-AES-encryption | C-Sharp/HowToUse.cs | C-Sharp/HowToUse.cs | public class test {
public static void Main (String []args)
{
CryptLib _crypt = new CryptLib ();
string plainText = "This is the text to be encrypted";
String iv = CryptLib.GenerateRandomIV (15); //do not exceed 15
string key = CryptLib.getHashSha256("my secret key", 31); //do not exceed 31
String cypherText = _crypt.encrypt (plainText, key, iv);
Console.WriteLine ("iv="+iv);
Console.WriteLine ("key=" + key);
Console.WriteLine("Cypher text=" + cypherText);
Console.WriteLine ("Plain text =" + _crypt.decrypt (cypherText, key, iv));
}
}
| apache-2.0 | C# | |
a425cafec4970f5279041753564d506f2cd383bd | Add Ambient transaction register | rpaschoal/DynamicRepository | DynamicRepository.MongoDB/TransactionRegister.cs | DynamicRepository.MongoDB/TransactionRegister.cs | using DynamicRepository.Transaction;
using System.Collections.Concurrent;
namespace DynamicRepository.MongoDB
{
internal static class TransactionRegister
{
internal static ConcurrentDictionary<string, ITransaction> AmbientTransactions = new ConcurrentDictionary<string, ITransaction>();
}
}
| mit | C# | |
8ec7d44113b21ac720b6e712aea06f9c264c3315 | format specialists list | petebryant/freelunch.uk,petebryant/freelunch.uk,petebryant/freelunch.uk | freelunch.uk/Views/Home/Specialists.cshtml | freelunch.uk/Views/Home/Specialists.cshtml | @model freelunch.uk.Models.SpecialistsViewModel
@{
ViewBag.Title = "Specialists";
string locations = "";
}
<div class="well well-lg">
<h2><i class="fa fa-users" aria-hidden="true"></i> @ViewBag.Title.</h2>
<br />
<div>
Find an specialist or register your skills etc...
</div>
</div>
@foreach (var specialist in Model.Specialists)
{
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">@Html.Encode(specialist.Name)</h3>
</div>
<div class="panel-body">
<div class="col-md-6">
<dl class="dl-horizontal">
<dt>@Html.DisplayNameFor(s => s.DummySpecialist.Description)</dt>
<dd>@Html.Encode(specialist.Description)</dd>
@foreach (var location in specialist.Locations)
{
if (!string.IsNullOrEmpty(locations))
{
locations += ", ";
}
locations += location.Name;
}
<dt>@Html.DisplayNameFor(s => s.DummyLocation.Name)</dt>
<dd>@Html.Encode(locations)</dd>
@foreach (var link in specialist.Links)
{
string iClass = "";
switch (link.LinkType)
{
case freelunch.uk.Models.LinkType.Facebook:
iClass = "fa fa-facebook";
break;
case freelunch.uk.Models.LinkType.LinkedIn:
iClass = "fa fa-linkedin";
break;
case freelunch.uk.Models.LinkType.Twitter:
iClass = "fa fa-twitter";
break;
default:
iClass = "fa fa-book";
break;
}
<dd>
<br />
<i class="fa @iClass" aria-hidden="true"></i>
<a href="@Html.Encode(link.URL)" style="text-decoration: none" title="@Html.Encode(link.Text)" target="_blank"> @Html.Encode(link.Text)</a>
</dd>
}
</dl>
</div>
<div class="col-md-6 bg-primary">
@foreach (var specialism in specialist.Specialisms)
{
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">@Html.Encode(specialism.Subject)</h3>
</div>
<div class="panel-body">
@Html.Encode(specialism.Description)
</div>
</div>
}
</div>
</div>
</div>
}
| mit | C# | |
9e9735fdfc6caad2c70f5cd715b62b1aa8c8d721 | Fix formatting in IDragHandler | dga711/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,battewr/CefSharp,joshvera/CefSharp,joshvera/CefSharp,gregmartinhtc/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,wangzheng888520/CefSharp,NumbersInternational/CefSharp,zhangjingpu/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,twxstar/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,zhangjingpu/CefSharp,jamespearce2006/CefSharp,illfang/CefSharp,joshvera/CefSharp,battewr/CefSharp,battewr/CefSharp,twxstar/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,haozhouxu/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,VioletLife/CefSharp,ITGlobal/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,Haraguroicha/CefSharp,haozhouxu/CefSharp,dga711/CefSharp,battewr/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,AJDev77/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,AJDev77/CefSharp,yoder/CefSharp,NumbersInternational/CefSharp,yoder/CefSharp,illfang/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,twxstar/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp | CefSharp/IDragHandler.cs | CefSharp/IDragHandler.cs | // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp
{
public interface IDragHandler
{
bool OnDragEnter(IWebBrowser browserControl, IBrowser browser, IDragData dragData, DragOperationsMask mask);
}
}
| // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp
{
public interface IDragHandler
{
bool OnDragEnter(IWebBrowser browserControl, IBrowser browser, IDragData dragData, DragOperationsMask mask);
}
}
| bsd-3-clause | C# |
68e061650dd7451fcd2fda50dd68fd3e4c0dde6d | Add ShipmentsController.cs | iwelina-popova/EShipmentSystem,iwelina-popova/EShipmentSystem,iwelina-popova/EShipmentSystem,iwelina-popova/EShipmentSystem | EShipmentSystem/EShipmentSystem.Web/Controllers/ShipmentsController.cs | EShipmentSystem/EShipmentSystem.Web/Controllers/ShipmentsController.cs | namespace EShipmentSystem.Web.Controllers
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using EShipmentSystem.Services.Contracts;
using Models.Shipment;
[Route("api/[controller]")]
public class ShipmentsController : Controller
{
private readonly IMapper mapper;
private IShipmentDataService shipments;
public ShipmentsController(
IMapper mapper,
IShipmentDataService shipments)
{
this.mapper = mapper;
this.shipments = shipments;
}
[HttpGet]
public async Task<IActionResult> All()
{
var shipmentDatas = await this.shipments
.GetAll()
.ProjectTo<ShipmentViewModel>()
.ToListAsync();
return this.Ok(shipmentDatas);
}
}
} | mit | C# | |
309e81f0b2da875fa9c2d3420d44fdbf6bba8a07 | Add ConstValues.cs for donet | StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals | rocketmq-client-donet/src/ConstValues.cs | rocketmq-client-donet/src/ConstValues.cs | namespace RocketMQ.Interop
{
public static class ConstValues
{
public const string RocketMQDriverDllName = "rocketmq-client-cpp.dll";
}
}
| apache-2.0 | C# | |
5033cfa13b8f9649cf2fc6c46e2b7125dbbf77d9 | add Unit Test to verify multiple blackboard key changes don’t result in wrong subbranch being activated | meniku/NPBehave | Editor/Tests/GeneralTest.cs | Editor/Tests/GeneralTest.cs | using NUnit.Framework;
namespace NPBehave
{
public class GeneralTest : Test
{
[Test]
public void ShouldNotActivateLowerPriorityBranchInCaseMultipleBranchesGetValid()
{
this.Timer = new Clock();
this.Blackboard = new Blackboard(Timer);
// our mock nodes we want to query for status
MockNode firstChild = new MockNode(false); // false -> fail when aborted
MockNode secondChild = new MockNode(false);
MockNode thirdChild = new MockNode(false);
// coniditions for each subtree that listen the BB for events
BlackboardCondition firstSelector = new BlackboardCondition( "branch1", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART, firstChild );
BlackboardCondition secondSelector = new BlackboardCondition( "branch2", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART, secondChild );
BlackboardCondition thirdSelector = new BlackboardCondition( "branch3", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART, thirdChild );
// set up the tree
Selector selector = new Selector(firstSelector, secondSelector, thirdSelector);
TestRoot behaviorTree = new TestRoot(Blackboard, Timer, selector);
// intially we want to activate branch3
Blackboard.Set("branch3", true);
// start the tree
behaviorTree.Start();
// verify the third child is running
Assert.AreEqual(Node.State.INACTIVE, firstChild.CurrentState);
Assert.AreEqual(Node.State.INACTIVE, secondChild.CurrentState);
Assert.AreEqual(Node.State.ACTIVE, thirdChild.CurrentState);
Assert.AreEqual(0, firstChild.DebugNumStartCalls);
Assert.AreEqual(0, secondChild.DebugNumStartCalls);
Assert.AreEqual(1, thirdChild.DebugNumStartCalls);
// change keys so the first & second conditions get true, too
Blackboard.Set("branch1", true);
Blackboard.Set("branch2", true);
// still the third child should be active, as the blackboard didn't yet notifiy the nodes
Assert.AreEqual(Node.State.INACTIVE, firstChild.CurrentState);
Assert.AreEqual(Node.State.INACTIVE, secondChild.CurrentState);
Assert.AreEqual(Node.State.ACTIVE, thirdChild.CurrentState);
Assert.AreEqual(0, firstChild.DebugNumStartCalls);
Assert.AreEqual(0, secondChild.DebugNumStartCalls);
Assert.AreEqual(1, thirdChild.DebugNumStartCalls);
// tick the timer to ensure the blackboard notifies the nodes
Timer.Update(0.1f);
// now we should be in branch1
Assert.AreEqual(Node.State.ACTIVE, firstChild.CurrentState);
Assert.AreEqual(Node.State.INACTIVE, secondChild.CurrentState);
Assert.AreEqual(Node.State.INACTIVE, thirdChild.CurrentState);
Assert.AreEqual(1, firstChild.DebugNumStartCalls);
Assert.AreEqual(0, secondChild.DebugNumStartCalls);
Assert.AreEqual(1, thirdChild.DebugNumStartCalls);
// disable first branch
Blackboard.Set("branch1", false);
Timer.Update(0.1f);
// and now the second branch should be active
Assert.AreEqual(Node.State.INACTIVE, firstChild.CurrentState);
Assert.AreEqual(Node.State.ACTIVE, secondChild.CurrentState);
Assert.AreEqual(Node.State.INACTIVE, thirdChild.CurrentState);
Assert.AreEqual(1, firstChild.DebugNumStartCalls);
Assert.AreEqual(1, secondChild.DebugNumStartCalls);
Assert.AreEqual(1, thirdChild.DebugNumStartCalls);
}
}
} | mit | C# | |
35d591334caa270bc6ab01ad942fea6bbf70a24e | Add WinUserNativeMethods.cs for encrypt/decrypt in Launcher | hpsa/hpe-application-automation-tools-plugin,hpsa/hp-application-automation-tools-plugin,bamh/hpe-application-automation-tools-plugin,bamh/hpe-application-automation-tools-plugin,bamh/hpe-application-automation-tools-plugin,HPSoftware/hpaa-octane-dev,HPSoftware/hpaa-octane-dev,hpsa/hp-application-automation-tools-plugin,HPSoftware/hpaa-octane-dev,hpsa/hp-application-automation-tools-plugin,hpsa/hp-application-automation-tools-plugin,hpsa/hpe-application-automation-tools-plugin,hpsa/hpe-application-automation-tools-plugin,bamh/hpe-application-automation-tools-plugin,hpsa/hpe-application-automation-tools-plugin,HPSoftware/hpaa-octane-dev,bamh/hpe-application-automation-tools-plugin,hpsa/hpe-application-automation-tools-plugin,hpsa/hp-application-automation-tools-plugin,HPSoftware/hpaa-octane-dev | HpToolsLauncher/WinUserNativeMethods.cs | HpToolsLauncher/WinUserNativeMethods.cs | using System;
using System.Runtime.InteropServices;
namespace HpToolsLauncher
{
public static class WinUserNativeMethods
{
private static class EncodeUtilsWrap
{
[DllImport("EncodeUtilsWrap", CallingConvention = CallingConvention.Cdecl)]
public static extern void UnprotectBSTRFromBase64([MarshalAs(UnmanagedType.BStr)] string input, [MarshalAs(UnmanagedType.BStr)] out string result);
[DllImport("EncodeUtilsWrap", CallingConvention = CallingConvention.Cdecl)]
public static extern void ProtectBSTRToBase64([MarshalAs(UnmanagedType.BStr)] string input, [MarshalAs(UnmanagedType.BStr)] out string result);
}
private static class EncodeUtilsWrapD
{
[DllImport("EncodeUtilsWrapD", CallingConvention = CallingConvention.Cdecl)]
public static extern void UnprotectBSTRFromBase64([MarshalAs(UnmanagedType.BStr)] string input, [MarshalAs(UnmanagedType.BStr)] out string result);
[DllImport("EncodeUtilsWrapD", CallingConvention = CallingConvention.Cdecl)]
public static extern void ProtectBSTRToBase64([MarshalAs(UnmanagedType.BStr)] string input, [MarshalAs(UnmanagedType.BStr)] out string result);
}
public static string ProtectBSTRToBase64(string clearData)
{
string result = null;
try
{
EncodeUtilsWrap.ProtectBSTRToBase64(clearData, out result);
}
catch (DllNotFoundException)
{
try
{
EncodeUtilsWrapD.ProtectBSTRToBase64(clearData, out result);
}
catch (DllNotFoundException)
{
}
}
return result;
}
public static string UnprotectBSTRFromBase64(string protectedData)
{
if (string.IsNullOrEmpty(protectedData))
return string.Empty;
string result = null;
try
{
EncodeUtilsWrap.UnprotectBSTRFromBase64(protectedData, out result);
}
catch (DllNotFoundException)
{
EncodeUtilsWrapD.UnprotectBSTRFromBase64(protectedData, out result);
}
return result;
}
}
}
| mit | C# | |
40c8c3f2497005b6d6f41abef6daa947bab73499 | Create ValueVrapper.cs | SMihand/Cache-GlobalsProxy-Framework | MetaEditor/helpclass/ValueVrapper.cs | MetaEditor/helpclass/ValueVrapper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetaCache_v3
{
class ValueVrapper
{
//"workers","list",0,100,"string",0,255,0)
String _Caption;
String _datatyp;
double _min, _max;
string _Def;
public ValueVrapper(String Caption, String datatyp, double min, double max, string Def)
{
_Caption = Caption;
_datatyp = datatyp;
_min = min;
_max = max;
_Def = Def;
}
public String toValueString()
{
return "\"" + _datatyp + "\"," + _min + "," + _max + "," + _Def;
}
public String toValuevsCaptionString()
{
return "\"" + _Caption + "\"," + "\"" + _datatyp + "\"," + _min + "," + _max + "," + _Def;
}
}
}
| mit | C# | |
9eae275c3683945c6d433d1e15835c8480d3f33b | Create LoadResources.cs | Gianxs/CitiesSkylineFavoriteCimsMod | LoadResources.cs | LoadResources.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace FavoriteCims
{
public class ResourceLoader
{
public static Assembly ResourceAssembly
{
get {
return Assembly.GetAssembly(typeof(ResourceLoader));
}
}
public static string BaseDir {
get {
return Path.GetDirectoryName(ResourceAssembly.Location) + Path.PathSeparator;
}
}
public static byte[] loadResourceData(string name)
{
name = "FavoriteCims.resources." + name;
UnmanagedMemoryStream stream = (UnmanagedMemoryStream)ResourceAssembly.GetManifestResourceStream(name);
if (stream == null)
{
return null;
}
BinaryReader read = new BinaryReader(stream);
return read.ReadBytes((int)stream.Length);
}
public static string loadResourceString(string name)
{
name = "FavoriteCims.resources." + name;
UnmanagedMemoryStream stream = (UnmanagedMemoryStream)ResourceAssembly.GetManifestResourceStream(name);
if (stream == null)
{
return null;
}
StreamReader read = new StreamReader(stream);
return read.ReadToEnd();
}
public static Texture2D loadTexture(int x, int y, string filename)
{
try
{
Texture2D texture = new Texture2D(x,y,TextureFormat.ARGB32,false);
texture.LoadImage(loadResourceData(filename));
return FixTransparency(texture);
}
catch (Exception e)
{
Debug.Log("Exception Error " + e);
}
return null;
}
//=========================================================================
// Copy the values of adjacent pixels to transparent pixels color info, to
// remove the white border artifact when importing transparent .PNGs.
//Thx to petrucio for this -> http://answers.unity3d.com/questions/238922/png-transparency-has-white-borderhalo.html
internal static Texture2D FixTransparency(Texture2D texture)
{
Color32[] pixels = texture.GetPixels32();
int w = texture.width;
int h = texture.height;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int idx = y * w + x;
Color32 pixel = pixels[idx];
if (pixel.a == 0) {
bool done = false;
if (!done && x > 0) done = TryAdjacent(ref pixel, pixels[idx - 1]); // Left pixel
if (!done && x < w-1) done = TryAdjacent(ref pixel, pixels[idx + 1]); // Right pixel
if (!done && y > 0) done = TryAdjacent(ref pixel, pixels[idx - w]); // Top pixel
if (!done && y < h-1) done = TryAdjacent(ref pixel, pixels[idx + w]); // Bottom pixel
pixels[idx] = pixel;
}
}
}
texture.SetPixels32(pixels);
texture.Apply();
return texture;
}
private static bool TryAdjacent(ref Color32 pixel, Color32 adjacent)
{
if (adjacent.a == 0) return false;
pixel.r = adjacent.r;
pixel.g = adjacent.g;
pixel.b = adjacent.b;
return true;
}
//=========================================================================
}
}
| mit | C# | |
3556a0cd70d3dc18c5d4cd4c631afc4c67766d4c | Add CryptographicException class | ektrah/nsec | src/Cryptography/CryptographicException.cs | src/Cryptography/CryptographicException.cs | using System;
namespace NSec.Cryptography
{
public class CryptographicException : Exception
{
public CryptographicException() { }
public CryptographicException(string message) : base(message) { }
public CryptographicException(string message, Exception innerException) : base(message, innerException) { }
}
}
| mit | C# | |
f75ea261fe1cbd4ad5ccb5651877c68bf40a8b83 | Create DeserializerException.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/DeserializerException.cs | TIKSN.Core/Serialization/DeserializerException.cs | using System;
namespace TIKSN.Serialization
{
[Serializable]
public class DeserializerException : Exception
{
public DeserializerException()
{
}
public DeserializerException(string message) : base(message)
{
}
public DeserializerException(string message, Exception inner) : base(message, inner)
{
}
protected DeserializerException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
} | mit | C# | |
f4135ffce75cfe097a99612179b17fc94e256726 | Disable test parallelization for OmniSharp.Cake.Tests | DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn | tests/OmniSharp.Cake.Tests/AssemblyInfo.cs | tests/OmniSharp.Cake.Tests/AssemblyInfo.cs | [assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)]
| mit | C# | |
e37a04e24b6b96f8f2f82624a31b03a81675adda | Create Sample.cs | Levaneng/Resharper-Themes | Sample.cs | Sample.cs | using ExternalNamespace;
namespace MyNamespace
{
internal delegate string Delegate();
public enum MyEnum { Value1, Value2 }
public struct MyStruct { }
/// <summary>
/// This is a XML comment
/// </summary>
/// <typeparam name="TGeneric"></typeparam>
internal class MyClass<TGeneric> : IAmInterface
{
public bool Property { get; set; }
public string NormalMethod(double param)
{
var localVariable = param.ExtensionMethod() / StaticClass.Constant;
return $"The result {localVariable} is awesome";
}
public static void StaticMethod()
{
// This a comment...
new MyClass<TGeneric>().NormalMethod(1234.5);
}
public string InterfaceMethod()
{
// TODO
throw new System.NotImplementedException();
}
}
}
namespace ExternalNamespace
{
public interface IAmInterface
{
string InterfaceMethod();
}
public static class StaticClass
{
public const int Constant = 111;
public static double ExtensionMethod(this double param)
{
return param;
}
}
}
| mit | C# | |
4b818f103b4c4218b9fbdfac405014743088dfc0 | Add IterationDataAttribute for easy test looping | heejaechang/roslyn,tmat/roslyn,davkean/roslyn,dotnet/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,nguerrera/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,mavasani/roslyn,agocke/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,VSadov/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,reaction1989/roslyn,dotnet/roslyn,tmat/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,aelij/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,eriawan/roslyn,jmarolf/roslyn,physhi/roslyn,AmadeusW/roslyn,abock/roslyn,physhi/roslyn,physhi/roslyn,MichalStrehovsky/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,genlu/roslyn,sharwell/roslyn,bartdesmet/roslyn,agocke/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,VSadov/roslyn,mavasani/roslyn,abock/roslyn,stephentoub/roslyn,weltkante/roslyn,tannergooding/roslyn,KevinRansom/roslyn,tmat/roslyn,aelij/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,gafter/roslyn,jmarolf/roslyn,eriawan/roslyn,tannergooding/roslyn,VSadov/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,genlu/roslyn,davkean/roslyn,brettfo/roslyn,stephentoub/roslyn,sharwell/roslyn,aelij/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,agocke/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,nguerrera/roslyn,AmadeusW/roslyn,brettfo/roslyn,swaroop-sridhar/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,reaction1989/roslyn,eriawan/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,swaroop-sridhar/roslyn,wvdd007/roslyn,abock/roslyn,KirillOsenkov/roslyn,gafter/roslyn,gafter/roslyn,nguerrera/roslyn,mavasani/roslyn,sharwell/roslyn,AmadeusW/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn | src/VisualStudio/IntegrationTest/TestUtilities/IterationDataAttribute.cs | src/VisualStudio/IntegrationTest/TestUtilities/IterationDataAttribute.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Reflection;
using Xunit.Sdk;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
/// <summary>
/// xUnit data attribute that allows looping tests. The following example shows a test which will run 50 times.
/// <code>
/// [WpfTheory, IterationData(50)]
/// public void IteratingTest(int iteration)
/// {
/// }
/// </code>
/// </summary>
public sealed class IterationDataAttribute : DataAttribute
{
public IterationDataAttribute(int iterations = 100)
{
Iterations = 100;
}
public int Iterations { get; }
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
for (var i = 0; i < Iterations; i++)
{
yield return new object[] { i };
}
}
}
}
| mit | C# | |
4468674a94c838935cc57ad7e54aaefbc6192eba | Fix possible null ref issue. | JasonBock/csla,MarimerLLC/csla,jonnybee/csla,MarimerLLC/csla,rockfordlhotka/csla,JasonBock/csla,MarimerLLC/csla,ronnymgm/csla-light,ronnymgm/csla-light,BrettJaner/csla,jonnybee/csla,BrettJaner/csla,ronnymgm/csla-light,rockfordlhotka/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,BrettJaner/csla | cslacs/Csla/Server/Hosts/Silverlight/WcfErrorInfo.cs | cslacs/Csla/Server/Hosts/Silverlight/WcfErrorInfo.cs | using System;
using System.Runtime.Serialization;
namespace Csla.Server.Hosts.Silverlight
{
/// <summary>
/// Message containing details about any
/// server-side exception.
/// </summary>
[DataContract]
public class WcfErrorInfo
{
/// <summary>
/// Type name of the exception object.
/// </summary>
[DataMember]
public string ExceptionTypeName { get; set; }
/// <summary>
/// Message from the exception object.
/// </summary>
[DataMember]
public string Message { get; set; }
/// <summary>
/// Stack trace from the exception object.
/// </summary>
[DataMember]
public string StackTrace { get; set; }
/// <summary>
/// Source of the exception object.
/// </summary>
[DataMember]
public string Source { get; set; }
/// <summary>
/// Target site name from the exception object.
/// </summary>
[DataMember]
public string TargetSiteName { get; set; }
/// <summary>
/// WcfErrorInfo object containing information
/// about any inner exception of the original
/// exception.
/// </summary>
[DataMember]
public WcfErrorInfo InnerError { get; private set; }
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="ex">
/// The Exception to encapusulate.
/// </param>
public WcfErrorInfo(Exception ex)
{
this.ExceptionTypeName = ex.GetType().FullName;
this.Message = ex.Message;
this.StackTrace = ex.StackTrace;
this.Source = ex.Source;
if (ex.TargetSite != null)
this.TargetSiteName = ex.TargetSite.Name;
if (ex.InnerException != null)
this.InnerError = new WcfErrorInfo(ex.InnerException);
}
}
}
| using System;
using System.Runtime.Serialization;
namespace Csla.Server.Hosts.Silverlight
{
/// <summary>
/// Message containing details about any
/// server-side exception.
/// </summary>
[DataContract]
public class WcfErrorInfo
{
/// <summary>
/// Type name of the exception object.
/// </summary>
[DataMember]
public string ExceptionTypeName { get; set; }
/// <summary>
/// Message from the exception object.
/// </summary>
[DataMember]
public string Message { get; set; }
/// <summary>
/// Stack trace from the exception object.
/// </summary>
[DataMember]
public string StackTrace { get; set; }
/// <summary>
/// Source of the exception object.
/// </summary>
[DataMember]
public string Source { get; set; }
/// <summary>
/// Target site name from the exception object.
/// </summary>
[DataMember]
public string TargetSiteName { get; set; }
/// <summary>
/// WcfErrorInfo object containing information
/// about any inner exception of the original
/// exception.
/// </summary>
[DataMember]
public WcfErrorInfo InnerError { get; private set; }
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="ex">
/// The Exception to encapusulate.
/// </param>
public WcfErrorInfo(Exception ex)
{
this.ExceptionTypeName = ex.GetType().FullName;
this.Message = ex.Message;
this.StackTrace = ex.StackTrace;
this.Source = ex.Source;
this.TargetSiteName = ex.TargetSite.Name;
if (ex.InnerException != null)
this.InnerError = new WcfErrorInfo(ex.InnerException);
}
}
}
| mit | C# |
1d3f5515e8ba9321ca091f25f442efd1897cb3e4 | Add MockCoreClrSanity test | crummel/dotnet_core-setup,crummel/dotnet_core-setup,wtgodbe/core-setup,wtgodbe/core-setup,MichaelSimons/core-setup,crummel/dotnet_core-setup,crummel/dotnet_core-setup,MichaelSimons/core-setup,MichaelSimons/core-setup,wtgodbe/core-setup,crummel/dotnet_core-setup,wtgodbe/core-setup,MichaelSimons/core-setup,MichaelSimons/core-setup,crummel/dotnet_core-setup,MichaelSimons/core-setup,wtgodbe/core-setup,wtgodbe/core-setup | src/test/HostActivationTests/MockCoreClrSanity.cs | src/test/HostActivationTests/MockCoreClrSanity.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 Microsoft.DotNet.Cli.Build;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Xunit;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation
{
public class MockCoreClrSanity : IDisposable
{
private readonly DotNetCli DotNet;
private readonly string _dotnetDir;
public MockCoreClrSanity()
{
_dotnetDir = Path.Combine(TestArtifact.TestArtifactsPath, "mockCoreclrSanity");
DotNet = new DotNetBuilder(_dotnetDir, Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"), "exe")
.AddMicrosoftNETCoreAppFrameworkMockCoreClr("9999.0.0")
.Build();
}
public void Dispose()
{
if (!TestArtifact.PreserveTestRuns())
{
Directory.Delete(_dotnetDir, true);
}
}
[Fact]
public void Muxer_ListRuntimes()
{
DotNet.Exec("--list-runtimes")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should().Pass()
.And.HaveStdOutContaining("Microsoft.NETCore.App 9999.0.0");
}
[Fact]
public void Muxer_ExecAppSequence()
{
var appDll = typeof(MockCoreClrSanity).Assembly.Location;
char sep = Path.DirectorySeparatorChar;
DotNet.Exec("--roll-forward-on-no-candidate-fx", "2", appDll, "argumentOne", "arg2")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should().Pass()
.And.HaveStdOutContaining("mock coreclr_initialize() called")
.And.HaveStdOutContaining("mock property[TRUSTED_PLATFORM_ASSEMBLIES]")
.And.HaveStdOutContaining($"Microsoft.NETCore.App{sep}9999.0.0{sep}Microsoft.NETCore.App.deps.json")
.And.HaveStdOutContaining("mock coreclr_execute_assembly() called")
.And.HaveStdOutContaining("mock argc:2")
.And.HaveStdOutContaining($"mock managedAssemblyPath:{appDll}")
.And.HaveStdOutContaining("mock argv[0] = argumentOne")
.And.HaveStdOutContaining("mock argv[1] = arg2")
.And.HaveStdOutContaining("mock coreclr_shutdown_2() called");
}
}
}
| mit | C# | |
08de81004adda619d84d0a5b18c9f91905b4cc5e | Create view model for user | grantcolley/authorisationmanager,grantcolley/authorisationmanager,grantcolley/authorisationmanager,grantcolley/authorisationmanager | UI/ASPNetCore/ViewModels/UserViewModel.cs | UI/ASPNetCore/ViewModels/UserViewModel.cs | namespace DevelopmentInProgress.AuthorisationManager.ASP.Net.Core.ViewModels
{
public class UserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
}
}
| apache-2.0 | C# | |
e62b1c1f8c062c0c7f6890b8099e1cc5e8e95aee | Create Chemin.cs | HartmanDev/WimP | Chemin.cs | Chemin.cs | using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
namespace PathFinder
{
class Chemin
{
#region Attributs
private int iNbMoveSinceLastNode;
public int NbBloquage;
public DateTime dtPATH;
// contient le chemin possible (n'est pas définitif)
public byte[] PathX;
public byte[] PathY;
public int PathLenght;
public bool PathValid;
/// <summary>
/// Correspond au nombre de mouvement effectué depuis le début du chemin en cours
/// </summary>
public int nbMovementPath;
public int NbMoveSinceLastNode
{
get { return iNbMoveSinceLastNode; }
set
{
iNbMoveSinceLastNode = value;
}
}
public List<Carrefour> Crosses;
#endregion
#region Méthodes
public void BuildPath(int[,] ArrayPath)
{
byte loop = 0;
byte nbmove = 1;
while (PathX[loop] < byte.MaxValue || PathY[loop] < byte.MaxValue)
{
ArrayPath[PathX[loop], PathY[loop]] = nbmove;
nbmove++;
loop++;
}
}
/// <summary>
/// Permet d'effacer du contenu dans PathX et PathY en partant d'un point donné, pour une certaine limite.
/// </summary>
/// <param name="Vassigner">Définit le point de départ</param>
/// <param name="Vlimite">Définit le nombre de cellules qui devront être effacées</param>
public void PurgePathXY(int Vassigner, int Vlimite)
{
for (int i = Vassigner; i < Vlimite; i++)
{
PathX[i] = byte.MaxValue;
PathY[i] = byte.MaxValue;
}
}
/// <summary>
/// Permet d'effacer toutes les cellules dans PathX et PathY depuis l'index donné.
/// </summary>
/// <param name="Vassigner">Définit le point de départ</param>
public void PurgePathXY(int Vassigner)
{
for (int i = Vassigner; PathX[i] != 255; i++)
{
PathX[i] = byte.MaxValue;
PathY[i] = byte.MaxValue;
}
}
public void AddCross(int CrossX, int CrossY, int CrossLenght, int iNbBloquage, int Possibilites)
{
Crosses.Add(new Carrefour(CrossX, CrossY, CrossLenght, iNbBloquage, Possibilites));
}
public void RemoveCross(int Indice)
{
Crosses.RemoveAt(Indice);
}
#endregion
#region Constructeur
/// <summary>
/// Initialise un chemin
/// </summary>
/// <param name="SizeX">Largeur de la Map</param>
/// <param name="SizeY">Hauteur de la map</param>
public Chemin(int SizeX, int SizeY)
{
Crosses = new List<Carrefour>();
PathX = new byte[SizeX];
PathY = new byte[SizeY];
for (int i = PathX.GetLength(0) - 1; i > 0; i--)
PathX[i] = byte.MaxValue;
for (int i = PathY.GetLength(0) - 1; i > 0; i--)
PathY[i] = byte.MaxValue;
nbMovementPath = 1;
PathLenght = 0;
NbBloquage = 0;
PathValid = false;
dtPATH = DateTime.Now;
}
#endregion
}
}
| mit | C# | |
9a4edaf55c5ade30643d9b59437bcc5a42cec45a | Clean up | viciousviper/mediafire-csharp-open-sdk,MediaFire/mediafire-csharp-open-sdk | Source/Samples/ConsoleApplication/Program.cs | Source/Samples/ConsoleApplication/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaFireSDK;
using MediaFireSDK.Model;
using MediaFireSDK.Model.Responses;
namespace ConsoleApplication
{
class Program
{
private const string AppId = "";
private const string AppKey = "";
private const string Email = "";
private const string Password = "";
static void Main(string[] args)
{
var config = new MediaFireApiConfiguration
(
appId: AppId,
apiKey: AppKey,
apiVersion: "1.4",
automaticallyRenewToken: true,
chunkTransferBufferSize:1024
);
var agent = new MediaFireAgent(config);
Console.WriteLine("Signing in {0}...", Email);
agent.User.GetSessionToken(Email, Password).Wait();
Console.WriteLine("Getting root folder files and folders...", Email);
var folderContent = agent.GetAsync<MediaFireGetContentResponse>(MediaFireApiFolderMethods.GetContent,
new Dictionary<string, object>
{
{MediaFireApiParameters.FolderKey, ""},
{MediaFireApiParameters.ContentType, MediaFireFolderContentType.Folders.ToApiParameter()}
}).Result.FolderContent;
var fileContent = agent.GetAsync<MediaFireGetContentResponse>(MediaFireApiFolderMethods.GetContent,
new Dictionary<string, object>
{
{MediaFireApiParameters.FolderKey, ""},
{MediaFireApiParameters.ContentType, MediaFireFolderContentType.Files.ToApiParameter()}
}).Result.FolderContent;
Console.WriteLine("Key | Name");
foreach (var item in folderContent.Folders.Union<MediaFireItem>(fileContent.Files))
{
Console.WriteLine("{0} | {1}", item.Key, item.Name);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaFireSDK;
using MediaFireSDK.Model;
using MediaFireSDK.Model.Responses;
namespace ConsoleApplication
{
class Program
{
private const string AppId = "";
private const string AppKey = "";
private const string Email = "";
private const string Password = "";
static void Main(string[] args)
{
var config = new MediaFireApiConfiguration
(
appId: AppId,
apiKey: AppKey,
apiVersion: "1.4",
automaticallyRenewToken: true,
chunkTransferBufferSize:1024
);
var agent = new MediaFireAgent(config);
Console.WriteLine("Signing in {0}...", Email);
agent.User.GetSessionToken(Email, Password).Wait();
Console.WriteLine("Getting root folder files and folders...", Email);
var folderContent = agent.GetAsync<MediaFireGetContentResponse>(MediaFireApiFolderMethods.GetContent,
new Dictionary<string, object>
{
{MediaFireApiParameters.FolderKey, ""},
{MediaFireApiParameters.ContentType, MediaFireFolderContentType.Folders.ToApiParameter()}
}).Result.FolderContent;
var fileContent = agent.GetAsync<MediaFireGetContentResponse>(MediaFireApiFolderMethods.GetContent,
new Dictionary<string, object>
{
{MediaFireApiParameters.FolderKey, ""},
{MediaFireApiParameters.ContentType, MediaFireFolderContentType.Files.ToApiParameter()}
}).Result.FolderContent;
Console.WriteLine("Key | Name");
foreach (var item in folderContent.Folders.Union<MediaFireItem>(fileContent.Files))
{
Console.WriteLine("{0} | {1}", item.Key, item.Name);
}
}
}
}
| apache-2.0 | C# |
d633a694a0938c5ee4836785b3f4036c0d51133e | Create getControllers.cs | stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff | example_code/getControllers.cs | example_code/getControllers.cs | // lists controllers when added to a web application
// returns result as a string
public String getControllers()
{
var asms = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name != "System.Web.Mvc");
String output = "";
foreach (Assembly asm in asms)
{
String s = "";
try
{
var controllers = asm.GetExportedTypes().Where(t => typeof(ControllerBase).IsAssignableFrom(t));
if (controllers.Count() > 0)
{
s += string.Format("\r\n{0}\r\nAssembly: {1}\r\n{2}\r\n", new String('=',32), asm.GetName().Name, new String('=', 32));
}
foreach (Type controller in controllers)
{
s += string.Format("{0}\r\nController: {1}\r\n{2}\r\n", new String('-', 32), controller.Name, new String('-', 32));
List<string> bannedDeclaringTypes = new List<string> { "System.Object", "System.Web.Mvc.ControllerBase", "System.Web.Mvc.Controller" };
//List<string> bannedDeclaringTypes = new List<string> { };
String cattribs = "Controller Attributes: ";
var cattributes = controller.GetCustomAttributes(false);
foreach (var attribute in cattributes)
{
cattribs += string.Format("{0},", attribute);
}
s += string.Format("{0}\r\n", cattribs);
var methods = controller.GetMethods().Where(m => m.IsPublic && !bannedDeclaringTypes.Contains(m.DeclaringType.FullName));
foreach (var method in methods)
{
s += string.Format("Method: {0}\r\n", method.Name);
String attribs = "Method Attributes: ";
var attributes = method.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
attribs += string.Format("{0},", attribute);
}
s += string.Format("{0}\r\n", attribs);
var parameters = method.GetParameters();
String pdata = "Method Parameters: ";
foreach (var param in parameters)
{
pdata += string.Format("(Name: {0}, Type: {1}),", param.Name, param.ParameterType.Name);
}
s += string.Format("{0}\r\n", pdata);
s += string.Format("Method Return Type: {0}\r\n\r\n", method.ReturnType.Name);
}
}
}
catch
{
s += string.Format("\r\nAssembly {0} failed parsing\r\n", asm.GetName().Name);
}
output += s;
}
return output;
}
| bsd-3-clause | C# | |
b37ef8a3a0c9c0758f0a9e04524bd069b54fe756 | Add UserInspector | peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype | src/Glimpse.Agent.Web/Inspectors/UserInspector.cs | src/Glimpse.Agent.Web/Inspectors/UserInspector.cs | using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.Web.Inspectors
{
public class UserInspector : IInspector
{
public Task Before(HttpContext context)
{
throw new NotImplementedException();
}
public Task After(HttpContext context)
{
throw new NotImplementedException();
}
}
}
| mit | C# | |
02b967f805527348e03d8e66f94d523d7de976ee | Create CharismaE.cs | Keripo/fgo-data | webservice/src/Models/Data/ActiveSkills/CharismaE.cs | webservice/src/Models/Data/ActiveSkills/CharismaE.cs | using FGOData.Models.Serialization;
using System.Collections.Generic;
namespace FGOData.Models.Data
{
public class CharismaE : ActiveSkill
{
public CharismaB()
{
Name_EN = "Charisma E";
Name_JP = "カリスマ E";
Cooldown = 7;
Effects = new List<Effect> {
new Effect()
{
EffectType = EffectType.Attack,
Target = TargetType.Team,
Duration = 3,
EffectValuesType = EffectValueType.Percent,
EffectValues = new List<float>
{
6.0f,
6.6f,
7.2f,
7.8f,
8.4f,
9.0f,
9.6f,
10.2f,
10.8f,
12.0f
}
}
};
}
}
}
| apache-2.0 | C# | |
e1a831505785abd8f9d6c0e9f58708e73e56bd7f | Add basic IRepository implementation | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.DataLayer/RepositoryBase.cs | src/Diploms.DataLayer/RepositoryBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class RepositoryBase<T> : IRepository<T> where T : class, IEntity
{
protected readonly DiplomContext _context;
public RepositoryBase(DiplomContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
_context = context;
}
/// <summary>
/// Получение всех объектов
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<T>> Get()
{
return await _context.Set<T>().AsNoTracking().ToListAsync();
}
/// <summary>
/// Получение объекта по Id
/// </summary>
/// <param name="id">Идентификатор объекта</param>
/// <param name="includes"></param>
/// <returns></returns>
public async Task<T> Get(int id)
{
var query = _context.Set<T>().AsNoTracking();
return await query.FirstOrDefaultAsync(entity => entity.Id == id);
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="item">Объект для добавления</param>
public void Add(T item)
{
_context.Set<T>().AddAsync(item);
}
/// <summary>
/// Обновление объекта
/// </summary>
/// <param name="item">Объект для обновления</param>
public void Update(T item)
{
_context.Set<T>().Update(item);
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="item">Объект для удаления</param>
public void Delete(T item)
{
_context.Set<T>().Remove(item);
}
/// <summary>
/// Сохранение изменений в репозитории
/// </summary>
/// <returns></returns>
public async Task SaveChanges()
{
await _context.SaveChangesAsync();
}
}
} | mit | C# | |
a7685a7725dca5d7a2e282c4bb2c3bf626588d0f | Add WaterQualityEntityComparer | HatfieldConsultants/Hatfield.EnviroData.WQDataProfile | Source/Hatfield.EnviroData.DataProfile.WQ.Data/WaterQualityEntityComparer.cs | Source/Hatfield.EnviroData.DataProfile.WQ.Data/WaterQualityEntityComparer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hatfield.EnviroData.DataProfile.WQ
{
public class WaterQualityEntityComparer
{
public static bool AreValueEqual(Hatfield.EnviroData.DataProfile.WQ.Models.Site model, Hatfield.EnviroData.Core.Site domain)
{
if(model == null || domain == null)
{
return false;
}
var dataAreTheSame = (domain.Latitude == model.Latitude) &&
(domain.Longitude == model.Longitude) &&
(domain.SamplingFeature != null) &&
(domain.SamplingFeature.SamplingFeatureName == model.Name);
return dataAreTheSame;
}
public static bool AreValueEqual(Hatfield.EnviroData.DataProfile.WQ.Models.Unit model, Hatfield.EnviroData.Core.Unit domain)
{
if (model == null || domain == null)
{
return false;
}
return model.Name == domain.UnitsName;
}
public static bool AreValueEqual(Hatfield.EnviroData.DataProfile.WQ.Models.Person model, Hatfield.EnviroData.Core.Person domain)
{
if (model == null || domain == null)
{
return false;
}
return string.Equals(model.FirstName, domain.PersonFirstName, StringComparison.InvariantCulture) &&
string.Equals(model.MiddleName, domain.PersonMiddleName, StringComparison.InvariantCulture) &&
string.Equals(model.LastName, domain.PersonLastName, StringComparison.InvariantCulture);
}
public static bool AreValueEqual(Hatfield.EnviroData.DataProfile.WQ.Models.Lab model, Hatfield.EnviroData.Core.Organization domain)
{
if (model == null || domain == null)
{
return false;
}
return string.Equals(model.Name, domain.OrganizationName, StringComparison.InvariantCulture);
}
public static bool AreValueEqual(Hatfield.EnviroData.DataProfile.WQ.Models.Analyte model, Hatfield.EnviroData.Core.Variable domain)
{
if (model == null || domain == null)
{
return false;
}
return string.Equals(model.Name, domain.VariableCode, StringComparison.InvariantCulture);
}
}
}
| mpl-2.0 | C# | |
a016c2be5fee8d5f0bcb719de79cc512a72b257c | Create AddDefineSymbols.cs | UnityCommunity/UnityLibrary | Assets/Scripts/Editor/AddDefineSymbols.cs | Assets/Scripts/Editor/AddDefineSymbols.cs | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
/// <summary>
/// Adds the given define symbols to PlayerSettings define symbols.
/// Just add your own define symbols to the Symbols property at the below.
/// </summary>
[InitializeOnLoad]
public class AddDefineSymbols : Editor
{
/// <summary>
/// Symbols that will be added to the editor
/// </summary>
public static readonly string [] Symbols = new string[] {
"MYCOMPANY",
"MYCOMPANY_MYPACKAGE"
};
/// <summary>
/// Add define symbols as soon as Unity gets done compiling.
/// </summary>
static AddDefineSymbols ()
{
string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup ( EditorUserBuildSettings.selectedBuildTargetGroup );
List<string> allDefines = definesString.Split ( ';' ).ToList ();
allDefines.AddRange ( Symbols.Except ( allDefines ) );
PlayerSettings.SetScriptingDefineSymbolsForGroup (
EditorUserBuildSettings.selectedBuildTargetGroup,
string.Join ( ";", allDefines.ToArray () ) );
}
}
| mit | C# | |
5abad7dbfb9f6880f642323989c16f3be4ec95bc | Test fix | bluemner/FormsGenerator,bluemner/FormsGenerator,bluemner/FormsGenerator | FormsGeneratorWebApplication/Views/Shared/_FormsLayout.cshtml | FormsGeneratorWebApplication/Views/Shared/_FormsLayout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Froms Generator</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Form:", "Index", "Home", null, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Forms")</li>
<li>@Html.ActionLink("About", "About", "Forms")</li>
<li>@Html.ActionLink("Contact", "Contact", "Forms")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - Forms Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# | |
5263f8e64625f4efe14ab4ffc02253db9ed66436 | add stub sample for later | aritchie/bluetoothle,aritchie/bluetoothle | Samples/Samples/Tasks/NotificationTask.cs | Samples/Samples/Tasks/NotificationTask.cs | //using System;
//using System.Reactive.Linq;
//using Autofac;
//using Plugin.BluetoothLE;
//namespace Samples.Tasks
//{
// public class NotificationTask : IStartable
// {
// readonly IAdapter adapter;
// readonly INotification notifications;
// public NotificationTask(IAdapter adapter, INotifications notifications)
// {
// this.adapter = adapter;
// this.notifications = notifications;
// }
// public void Start()
// {
// this.adapter
// .WhenStatusChanged()
// .Skip(1)
// .Where(x => x == AdapterStatus.PoweredOff)
// .Subscribe(_ =>
// {
// this.notifications.Send("Turn your bluetooth back on!")
// });
// }
// }
//}
| mit | C# | |
e8e947ad16d601e313807521bca42c251d6a6a29 | Create SmoothMouseLookAveraged.cs | UnityCommunity/UnityLibrary | Scripts/Camera/SmoothMouseLookAveraged.cs | Scripts/Camera/SmoothMouseLookAveraged.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// source: https://forum.unity3d.com/threads/a-free-simple-smooth-mouselook.73117/#post-3101292
// added: lockCursor
namespace UnityLibrary
{
public class SmoothMouseLookAveraged : MonoBehaviour
{
[Header("Info")]
private List<float> _rotArrayX = new List<float>(); // TODO: could use fixed array, or queue
private List<float> _rotArrayY = new List<float>();
private float rotAverageX;
private float rotAverageY;
private float mouseDeltaX;
private float mouseDeltaY;
[Header("Settings")]
public float _sensitivityX = 1.5f;
public float _sensitivityY = 1.5f;
[Tooltip("The more steps, the smoother it will be.")]
public int _averageFromThisManySteps = 3;
public bool lockCursor = false;
[Header("References")]
[Tooltip("Object to be rotated when mouse moves left/right.")]
public Transform _playerRootT;
[Tooltip("Object to be rotated when mouse moves up/down.")]
public Transform _cameraT;
//============================================
// FUNCTIONS (UNITY)
//============================================
void Start()
{
Cursor.visible = !lockCursor;
}
void Update()
{
HandleCursorLock();
MouseLookAveraged();
}
//============================================
// FUNCTIONS (CUSTOM)
//============================================
void HandleCursorLock()
{
// pressing esc toggles between hide/show and lock/unlock cursor
if (Input.GetKeyDown(KeyCode.Escape))
{
lockCursor = !lockCursor;
}
// Ensure the cursor is always locked when set
Cursor.lockState = lockCursor ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !lockCursor;
}
void MouseLookAveraged()
{
rotAverageX = 0f;
rotAverageY = 0f;
mouseDeltaX = 0f;
mouseDeltaY = 0f;
mouseDeltaX += Input.GetAxis("Mouse X") * _sensitivityX;
mouseDeltaY += Input.GetAxis("Mouse Y") * _sensitivityY;
// Add current rot to list, at end
_rotArrayX.Add(mouseDeltaX);
_rotArrayY.Add(mouseDeltaY);
// Reached max number of steps? Remove oldest from list
if (_rotArrayX.Count >= _averageFromThisManySteps)
_rotArrayX.RemoveAt(0);
if (_rotArrayY.Count >= _averageFromThisManySteps)
_rotArrayY.RemoveAt(0);
// Add all of these rotations together
for (int i_counterX = 0; i_counterX < _rotArrayX.Count; i_counterX++)
rotAverageX += _rotArrayX[i_counterX];
for (int i_counterY = 0; i_counterY < _rotArrayY.Count; i_counterY++)
rotAverageY += _rotArrayY[i_counterY];
// Get average
rotAverageX /= _rotArrayX.Count;
rotAverageY /= _rotArrayY.Count;
// Apply
_playerRootT.Rotate(0f, rotAverageX, 0f, Space.World);
_cameraT.Rotate(-rotAverageY, 0f, 0f, Space.Self);
}
}
}
| mit | C# | |
e574aa0e94ee16366a7c4086f2eb80042edb494f | Add toggle menu item test | 2yangk23/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,smoogipooo/osu,johnneijzen/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu | osu.Game.Tests/Visual/UserInterface/TestSceneToggleMenuItem.cs | osu.Game.Tests/Visual/UserInterface/TestSceneToggleMenuItem.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneToggleMenuItem : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(OsuMenu),
typeof(ToggleMenuItem),
typeof(DrawableStatefulMenuItem)
};
public TestSceneToggleMenuItem()
{
Add(new OsuMenu(Direction.Vertical, true)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Items = new[]
{
new ToggleMenuItem("First"),
new ToggleMenuItem("Second") { State = { Value = true } }
}
});
}
}
}
| mit | C# | |
6ce82cfc1b2ce948a1f3be94473bec6845dfca48 | Create server.cs | neervfx/server,neervfx/server | server.cs | server.cs | using UnityEngine;
using System.Collections;
using System.Net;
public class server : MonoBehaviour {
private string privateKey = "sdfgsdhsdhrhdf"; //same secret key as php
private string saveDataUrl = "https://www.example.com/savedata.php?"; //your php server url
private string loadDataUrl = "https://www.example.com/loaddata.php?"; //your php server url
private string data1;
private string data2;
private string data3;
private string data4;
// Use this for initialization
void Start () {
data1 = "fgdfgfgh";
data2 = "eeeeeee";
data3 = "ggggg";
data4 = "fdghncv";
StartCoroutine(SaveData(data1, data2, data3, data4)); // save to server data first
//StartCoroutine(LoadData(data1)); //then load data from server
}
IEnumerator SaveData(string data1, string data2, string data3, string data4)
{
string hash = Md5Sum(data1 + privateKey);
WWW ScorePost = new WWW(saveDataUrl + "data1=" + data1 + "&data2=" + data2 + "&data3=" + data3 + "&data4=" + data4 + "&hash=" + hash);
yield return ScorePost;
if (ScorePost.error == null)
{
Debug.Log (ScorePost.text);
}
else
{
Debug.Log ("unable to update data:"+ScorePost.error);
}
}
IEnumerator LoadData(string data1)
{
string hash = Md5Sum(data1 + privateKey);
WWW GetScoresAttempt = new WWW (loadDataUrl + "data1=" + data1 + "&hash=" + hash);
yield return GetScoresAttempt;
if (GetScoresAttempt.error != null) {
Debug.Log ("server is not reachable");
} else {
string[] textlist = GetScoresAttempt.text.Split (new string[]{"\n","\t"}, System.StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<textlist.Length; i++) Debug.Log (textlist[i]);
}
}
private string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
}
| mit | C# | |
b9f204bc8b31af73393be63d1aaa5cc3349f186e | break IEnumerable into sets of a particular size | handcraftsman/Scratch | src/Scratch/SplitIEnumerableIntoSets/IEnumerableTExtensions.cs | src/Scratch/SplitIEnumerableIntoSets/IEnumerableTExtensions.cs | // * **********************************************************************************
// * Copyright (c) Clinton Sheppard
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **********************************************************************************
using System.Collections.Generic;
using System.Linq;
namespace Scratch.SplitIEnumerableIntoSets
{
/// <summary>
/// http://stackoverflow.com/questions/1034429/how-to-prevent-memory-overflow-when-using-an-ienumerablet-and-linq-to-sql/1035039#1035039
/// </summary>
public static class IEnumerableExtensions
{
public static IEnumerable<List<T>> InSetsOf<T>(this IEnumerable<T> source, int max)
{
var toReturn = new List<T>(max);
foreach (var item in source)
{
toReturn.Add(item);
if (toReturn.Count == max)
{
yield return toReturn;
toReturn = new List<T>(max);
}
}
if (toReturn.Any())
{
yield return toReturn;
}
}
}
} | mit | C# | |
b906177ec947480f44c3b5857ae7b6567b2f081b | Create Problem38.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem38.cs | Problems/Problem38.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler.Problems
{
class Problem38
{
private bool IsPandigital(string numS)//int num)
{
//string numS = num.ToString();
if (numS.Length != 9)
{
return false;
}
List<char> numC = new List<char>();
for(int c = 0; c < numS.Length; c++)
{
numC.Add(numS[c]);
}
numC.Sort();
string numS2 = "";
foreach (char c in numC)
{
numS2 += c;
}
return (numS2 == "123456789");
}
public void Run()
{
List<int> pandigitals = new List<int>();
for (int num = 100; num <= 9999; num++)
{
int i = 1;
string conc = "";
while (conc.Length < 9)
{
conc += (num * i).ToString();
i++;
}
if(IsPandigital(conc)) {
pandigitals.Add(int.Parse(conc));
}
}
Console.WriteLine(pandigitals.Max().ToString());
}
}
}
| mit | C# | |
8a140b8d2867c0ec66b887dd637c4907997fdaee | Create Problem97.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem97.cs | Problems/Problem97.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem97
{
private BigInteger modpow(BigInteger bas, BigInteger exponent, BigInteger modulus)
{
BigInteger result = 1;
while (exponent > 0)
{
if ((exponent & 1) == 1)
{
// multiply in this bit's contribution while using modulus to keep result small
result = (result * bas) % modulus;
}
// move to the next bit of the exponent, square (and mod) the base accordingly
exponent >>= 1;
bas = (bas * bas) % modulus;
}
return result;
}
public void Run()
{
BigInteger lastTen = 0;
//for (int i = 0; i < 10; i++)
//{
// Math.Pow(10, i)
//}
lastTen = modpow(2, 7830457, (long)Math.Pow(10, 10));
//lastTen = BigInteger.Pow(2, 7830457);
BigInteger lastTen2 = (28433 * lastTen) + 1;
string strLastTen2 = lastTen2.ToString();
Console.WriteLine(strLastTen2.Substring(strLastTen2.Length-10));
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.