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 |
|---|---|---|---|---|---|---|---|---|
7cc1a666bf22b31a4b133a1529345c20d93c8f3e | Create NullMessageBus.cs | wgraham17/Foundatio,FoundatioFx/Foundatio,exceptionless/Foundatio | src/Foundatio/Messaging/NullMessageBus.cs | src/Foundatio/Messaging/NullMessageBus.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Foundatio.Utility;
namespace Foundatio.Messaging {
public class NullMessageBus : IMessageBus {
public static readonly NullMessageBus Instance = new NullMessageBus();
public Task PublishAsync(Type messageType, object message, TimeSpan? delay = null, CancellationToken cancellationToken = default(CancellationToken)) {
return TaskHelper.Completed;
}
public void Subscribe<T>(Func<T, CancellationToken, Task> handler, CancellationToken cancellationToken = default(CancellationToken)) where T : class {}
public void Dispose() {}
}
}
| apache-2.0 | C# | |
b935c5e4217995d885389171a96c97655b2cc285 | Create Course.cs | Si-143/Application-and-Web-Development | Course.cs | Course.cs | public class Course
{
int cID;
string cName;
public int CourID{
get {return cID;}
set {cID = value;}
}
public string CourseName{
get {return cName;}
set {cName = value;}
}
public Course(int id,string CName)
{
cID = id;
cName = CName;
| mit | C# | |
a299dc7ad66c961d7a64d52f531007793f37a240 | Create linq.cs | jreina/impractical-fizzbuzz-solutions,jreina/impractical-fizzbuzz-solutions,jreina/impractical-fizzbuzz-solutions,jreina/impractical-fizzbuzz-solutions,jreina/impractical-fizzbuzz-solutions,jreina/impractical-fizzbuzz-solutions,jreina/impractical-fizzbuzz-solutions | csharp/linq.cs | csharp/linq.cs | using System;
using System.Linq;
public class Program
{
public static void Main()
{
Enumerable
.Range(1,100)
.Select(FizzBuzz.FromNumber)
.ToList()
.ForEach(Console.WriteLine);
}
}
public class FizzBuzz
{
private readonly int _number;
private readonly string _fizzbuzz;
public FizzBuzz(int number)
{
_number = number;
_fizzbuzz = $"{(number % 3 == 0 ? "Fizz" : "")}{(number % 5 == 0 ? "Buzz" : "")}";
}
public override string ToString()
{
return string.IsNullOrEmpty(_fizzbuzz) ? _number.ToString() : _fizzbuzz;
}
public static FizzBuzz FromNumber(int number)
{
return new FizzBuzz(number);
}
}
| mit | C# | |
78ad540c2720834671d2b42b04c86342c578cf3e | Add formatting related types | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/Formatting.cs | src/PowerShellEditorServices.Protocol/LanguageServer/Formatting.cs | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class DocumentFormattingRequest
{
public static readonly
RequestType<DocumentFormattingParams, TextEdit[], object,TextDocumentRegistrationOptions> Type = RequestType<DocumentFormattingParams, TextEdit[], object,TextDocumentRegistrationOptions>.Create("textDocument/definition");
}
public class DocumentFormattingParams
{
public TextDocumentIdentifier TextDocument { get; set; }
public FormattingOptions options { get; set; }
}
public class FormattingOptions
{
int TabSize { get; set; }
bool InsertSpaces { get; set; }
}
}
| mit | C# | |
441a45726793a4f6120f21d2a6f57f4409bc506d | Create MeteorRing.cs | UnityCommunity/UnityLibrary | Scripts/Misc/MeteorRing.cs | Scripts/Misc/MeteorRing.cs | using UnityEngine;
using System.Collections;
// Usage: Attach to gameobject (enable gizmos to see Debug.DrawRay())
// reference: http://forum.unity3d.com/threads/procedural-generation-in-a-specific-shape-question.421659/
public class MeteorRing : MonoBehaviour
{
public int totalCount = 5000;
public float ringRadius = 10;
public float ringHeight = 1;
void Start()
{
for (int i = 0; i < totalCount; i++)
{
// outer ring
float angle = i * (Mathf.PI *2) / totalCount;
var x = Mathf.Sin(angle) * ringRadius;
var y = Mathf.Cos(angle) * ringRadius;
var pos = new Vector3(x, 0, y);
// spread within outer ring
pos += Random.insideUnitSphere * ringHeight;
// draw
Debug.DrawRay(pos, Vector3.up * 0.05f, Color.yellow, 100);
}
}
}
| mit | C# | |
7c7704588a2e7aa03d976f959c419c3c446a81b6 | Create ProbabilityStateModel.cs | efruchter/UnityUtilities | ProbabilityStateModel.cs | ProbabilityStateModel.cs | using System.Collections;
using System;
/**
* A 1st order probabalistic model that can be used to model complex behaviours for A.I. or other processes.
*
* Designed to use minimal space and perform fast lookups.
* Built for fast Transitions O(log2(states)). Preparing the probabilities is O(n).
*
* After setting the states, don't forget to Prepare().
* -Eric
*/
public class ProbabilityStateModel {
public int currentState;
readonly WeightedRegion[][] binarySearchPModel;
bool validated;
readonly int STATE_COUNT;
readonly System.Func<float> randomNumberSource;
/**
* Create a probability model
* UniqueStateCount: Total number of states.
* startState: The starting state.
* randomPositiveUnitNumberSource: Function that generates a random float in the range [0, ..., 1];
*/
public ProbabilityStateModel ( int uniqueStateCount, int startState, System.Func<float> randomPositiveUnitNumberSource) {
currentState = startState;
STATE_COUNT = uniqueStateCount;
randomNumberSource = randomPositiveUnitNumberSource;
validated = false;
binarySearchPModel = new WeightedRegion[ uniqueStateCount ][];
for ( int i = 0; i < STATE_COUNT; i++ ) {
binarySearchPModel[ i ] = new WeightedRegion[ uniqueStateCount ];
}
for ( int i = 0; i < STATE_COUNT; i++ ) {
for ( int j = 0; j < STATE_COUNT; j++ ) {
SetTransitionProbability( i, j, 0 );
}
}
}
public void Prepare() {
if ( validated ) {
throw new Exception ( "Model has already been prepared." );
}
for ( int i = 0; i < STATE_COUNT; i++ ) {
MakeRegionArraySearchable( binarySearchPModel[ i ] );
}
validated = true;
}
/**
* Perform a probabilistic transition.
* Return true if the state changed.
*/
public bool Transition() {
if ( !validated ) {
throw new Exception( "Please Prepare() model before using." );
}
var newState = BinarySearchRegionFromSample( binarySearchPModel[ currentState ], randomNumberSource() );
bool isNewState = ( newState != currentState );
currentState = newState;
return isNewState;
}
/**
* Transition and return the current state.
*/
public int TransitionReturnState() {
Transition();
return currentState;
}
public void SetTransitionProbability( int fromState, int toState, float prob ) {
if ( validated ) {
throw new Exception ( "Cannot set probabilityies after calling Prepare()." );
}
binarySearchPModel[ fromState ][ toState ] = new WeightedRegion () {
upperRegionValue = prob,
trueIndex = toState
};
}
/**
* Returns The region that a sample exists in. All regions are marked by their upper range.
*/
static int BinarySearchRegionFromSample( WeightedRegion[] sortedA, float sample ) {
int l = 0;
int h = sortedA.Length - 1;
int m = ( l + h ) / 2;
if ( l == h ) {
return m;
}
while ( l <= h ) {
if ( sample < sortedA[ m ].upperRegionValue ) {
if ( ( m == 0 ) || ( (sortedA[ m ].upperRegionValue - sample ) <= ( sortedA[ m ].upperRegionValue - sortedA[ m - 1 ].upperRegionValue) ) ) {
return sortedA[ m ].trueIndex;
}
h = m - 1;
} else {
if ( m == sortedA.Length - 1 ) {
return sortedA[ m ].trueIndex;
}
l = m + 1;
}
m = ( l + h ) / 2;
}
return -1;
}
static void MakeRegionArraySearchable( WeightedRegion[] a ) {
Normalize( a );
for ( int i = 1; i < a.Length; i++ ) {
a[ i ].upperRegionValue += a[ i - 1 ].upperRegionValue;
}
int lastValidIndex = 0;
for ( int i = a.Length - 1; i > 0; i-- ) {
if ( a[i].upperRegionValue != a [ i - 1 ].upperRegionValue ) {
lastValidIndex = i;
break;
}
}
for ( int i = lastValidIndex + 1; i < a.Length; i++ ) {
a[ i ].trueIndex = lastValidIndex;
}
for ( int i = lastValidIndex - 1; i > 0; i-- ) {
if ( ( a[ i ].upperRegionValue == a[ i - 1 ].upperRegionValue ) || ( a[ i ].upperRegionValue != a[ i + 1 ].upperRegionValue ) ) {
a[ i ].trueIndex = a[ i + 1 ].trueIndex;
}
}
}
static void Normalize( WeightedRegion[] A ) {
float total = 0;
for ( int i = 0; i < A.Length; i++ ) {
total += A[ i ].upperRegionValue;
}
if ( total <= 0 ) {
throw new Exception( "Probabilities out of a given state cannot sum to 0!" );
}
for ( int i = 0; i < A.Length; i++ ) {
A [ i ].upperRegionValue /= total;
}
}
public float GetTransitionProbability( int fromState, int toState ) {
if ( toState == 0 ) {
return binarySearchPModel[ fromState ][ toState ].upperRegionValue;
}
return binarySearchPModel[ fromState ] [ toState ].upperRegionValue - binarySearchPModel[ fromState ][ toState - 1 ].upperRegionValue;
}
struct WeightedRegion {
public int trueIndex;
public float upperRegionValue;
}
}
| mit | C# | |
5bf1c1ae77c510bfc16cd8d797c18b68b2bcbd2d | Add PipelineCache tests | discosultan/VulkanCore | Tests/PipelineCacheTest.cs | Tests/PipelineCacheTest.cs | using System.Linq;
using VulkanCore.Tests.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace VulkanCore.Tests
{
public class PipelineCacheTest : HandleTestBase
{
[Fact]
public void GetData()
{
var descriptorSetLayoutCreateInfo = new DescriptorSetLayoutCreateInfo(
new DescriptorSetLayoutBinding(0, DescriptorType.StorageBuffer, 1, ShaderStages.Compute),
new DescriptorSetLayoutBinding(1, DescriptorType.StorageBuffer, 1, ShaderStages.Compute));
using (DescriptorSetLayout descriptorSetLayout = Device.CreateDescriptorSetLayout(descriptorSetLayoutCreateInfo))
using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout(new PipelineLayoutCreateInfo(new[] { descriptorSetLayout })))
using (ShaderModule shader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.comp.spv"))))
{
var pipelineCreateInfo = new ComputePipelineCreateInfo(
new PipelineShaderStageCreateInfo(ShaderStages.Compute, shader, "main"),
pipelineLayout);
byte[] cacheBytes;
// Populate cache.
using (PipelineCache cache = Device.CreatePipelineCache())
{
using (Device.CreateComputePipeline(pipelineCreateInfo, cache)) { }
cacheBytes = cache.GetData();
}
Assert.False(cacheBytes.All(x => x == 0));
// Recreate pipeline from cache.
using (PipelineCache cache = Device.CreatePipelineCache(new PipelineCacheCreateInfo(cacheBytes)))
{
using (Device.CreateComputePipeline(pipelineCreateInfo, cache)) { }
}
}
}
[Fact]
public void MergePipelines()
{
using (PipelineCache dstCache = Device.CreatePipelineCache())
using (PipelineCache srcCache = Device.CreatePipelineCache())
{
dstCache.MergeCache(srcCache);
dstCache.MergeCaches(srcCache);
}
}
public PipelineCacheTest(DefaultHandles defaults, ITestOutputHelper output) : base(defaults, output) { }
}
}
| mit | C# | |
ab878c1797699fba99059ae427bda4200658a8ff | Add SpatialQueryInfoCarrierTest. | azabluda/InfoCarrier.Core | test/InfoCarrier.Core.FunctionalTests/InMemory/Query/SpatialQueryInfoCarrierTest.cs | test/InfoCarrier.Core.FunctionalTests/InMemory/Query/SpatialQueryInfoCarrierTest.cs | // Copyright (c) on/off it-solutions gmbh. All rights reserved.
// Licensed under the MIT license. See license.txt file in the project root for license information.
namespace InfoCarrier.Core.FunctionalTests.InMemory.Query
{
using InfoCarrier.Core.FunctionalTests.TestUtilities;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.TestUtilities;
public class SpatialQueryInfoCarrierTest : SpatialQueryTestBase<SpatialQueryInfoCarrierTest.TestFixture>
{
public SpatialQueryInfoCarrierTest(TestFixture fixture)
: base(fixture)
{
}
public class TestFixture : SpatialQueryFixtureBase
{
private ITestStoreFactory testStoreFactory;
protected override ITestStoreFactory TestStoreFactory =>
InfoCarrierTestStoreFactory.EnsureInitialized(
ref this.testStoreFactory,
InfoCarrierTestStoreFactory.InMemory,
this.ContextType,
this.OnModelCreating);
}
}
}
| mit | C# | |
7f84dd2dc1efe9d309f069d7a46d863e487d1c06 | add failing tests | Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/Relationships.cs | test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/Relationships.cs | using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using DotNetCoreDocs;
using DotNetCoreDocs.Models;
using DotNetCoreDocs.Writers;
using JsonApiDotNetCoreExample;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Xunit;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Models;
namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec
{
[Collection("WebHostCollection")]
public class Relationships
{
private DocsFixture<Startup, JsonDocWriter> _fixture;
public Relationships(DocsFixture<Startup, JsonDocWriter> fixture)
{
_fixture = fixture;
}
[Fact]
public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships()
{
// arrange
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/todo-items";
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(httpMethod, route);
// act
var response = await client.SendAsync(request);
var documents = JsonConvert.DeserializeObject<Documents>(await response.Content.ReadAsStringAsync());
var data = documents.Data[0];
var expectedOwnerSelfLink = $"http://localhost/api/v1/todo-items/{data.Id}/relationships/owner";
var expectedOwnerRelatedLink = $"http://localhost/api/v1/todo-items/{data.Id}/owner";
// assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedOwnerSelfLink, data.Relationships["owner"].Links.Self);
Assert.Equal(expectedOwnerRelatedLink, data.Relationships["owner"].Links.Related);
}
[Fact]
public async Task Correct_RelationshipObjects_For_OneToMany_Relationships()
{
// arrange
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var httpMethod = new HttpMethod("GET");
var route = $"/api/v1/people";
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(httpMethod, route);
// act
var response = await client.SendAsync(request);
var documents = JsonConvert.DeserializeObject<Documents>(await response.Content.ReadAsStringAsync());
var data = documents.Data[0];
var expectedOwnerSelfLink = $"http://localhost/api/v1/people/{data.Id}/relationships/todo-items";
var expectedOwnerRelatedLink = $"http://localhost/api/v1/people/{data.Id}/todo-items";
// assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedOwnerSelfLink, data.Relationships["todo-items"].Links.Self);
Assert.Equal(expectedOwnerRelatedLink, data.Relationships["todo-items"].Links.Related);
}
}
}
| mit | C# | |
ed7af4d11f71f4823f7477f855d21c034b05c75d | Add tests for #90 (#196) | hazzik/DelegateDecompiler | src/DelegateDecompiler.Tests/Issue90.cs | src/DelegateDecompiler.Tests/Issue90.cs | using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace DelegateDecompiler.Tests
{
public class Issue90 : DecompilerTestsBase
{
public class Test
{
public string A { get; set; }
}
public class Test2
{
public List<Test> Collection { get; } = new List<Test>();
[Computed]
public Test Last => Collection.LastOrDefault();
}
[Test]
public void ShouldBeAbleToDecompileLastOrDefault()
{
var query = Enumerable.Range(0, 3)
.Select(x => new Test2
{
Collection =
{
new Test { A = (x * 3 + 0).ToString() },
new Test { A = (x * 3 + 1).ToString() },
new Test { A = (x * 3 + 2).ToString() },
}
}).AsQueryable();
var expected = query.Select(x => x.Collection.LastOrDefault()).Select(x => x.A);
var actual = query.Select(x => x.Last).Select(x => x.A).Decompile();
AssertAreEqual(expected.Expression, actual.Expression);
Assert.That(actual.ToList(), Is.EqualTo(new[] { "2", "5", "8" }));
}
}
}
| mit | C# | |
46bdaded1c150781e3f72c0075439f71d68c3981 | Add missing file | shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg | trunk/src/bindings/ProtocolType.cs | trunk/src/bindings/ProtocolType.cs | /**
* tapcfg - A cross-platform configuration utility for TAP driver
* Copyright (C) 2008 Juho Vähä-Herttua
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
namespace TAP {
/* http://www.iana.org/assignments/protocol-numbers/ */
public enum ProtocolType : byte {
HOPOPT = 1,
ICMP = 2,
IGMP = 3,
GGP = 4,
IP = 5,
IPv6 = 41,
ICMPv6 = 58
}
}
| lgpl-2.1 | C# | |
f218e868e54bfc24f88a098902bc41013607ca5d | add CountingSort3.cs | regeldso/hrank | Algorithms/Sorting/CountingSort3.cs | Algorithms/Sorting/CountingSort3.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[] ar = new int[n];
int[] ar_count = new int[100];
int[] helper_ar = new int[100];
int current_value;
for (int i = 0; i < n; i++)
{
string[] split_elements = Console.ReadLine().Split(' ');
current_value = Convert.ToInt32(split_elements[0]);
ar[i] = current_value;
ar_count[current_value] = ar_count[current_value] + 1;
}
helper_ar[0] = ar_count[0];
for (int b = 1; b < 100; b++)
{
if(ar_count[b] == 0)
helper_ar[b] = helper_ar[b - 1];
else
helper_ar[b] = ar_count[b] + helper_ar[b - 1];
}
Console.WriteLine(string.Join(" ", helper_ar));
}
} | mit | C# | |
1814a265a6290cb01284db57a880f69ffa2e51e4 | Create Stack_ResizingStack.cs | amithegde/AlgorithmsAndDataStructures | src/Stack_ResizingStack.cs | src/Stack_ResizingStack.cs | void Main()
{
//Auto Resizing Stack
var stack = new ResizingStack();
stack.Push("1");
stack.Push("2");
stack.Push("3");
Console.WriteLine("\nsize: " + stack.Size + " Capacity: " + stack.StackCapacity);
stack.Push("4");
stack.Push("5");
stack.Push("6");
Console.WriteLine("\nsize: " + stack.Size + " Capacity: " + stack.StackCapacity);
Console.WriteLine("\nPop elements");
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine("\nsize: " + stack.Size + " Capacity: " + stack.StackCapacity);
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Pop());
Console.WriteLine("\nsize: " + stack.Size + " Capacity: " + stack.StackCapacity);
}
public class ResizingStack
{
private Object[] array = null;
private int top;
public ResizingStack()
{
array = new Object[2];
top = -1;
}
public bool ISEmpty { get { return top == -1; } }
public int Size { get {return top + 1;} }
public int StackCapacity { get {return array.Length; } }
public void Push(Object item)
{
if (array.Length == top + 1)
{
ResizeStack(array.Length * 2);
}
array[++top] = item;
}
public Object Pop()
{
if (top == -1)
{
return null;
}
var item = array[top];
array[top--] = null;
if (top > 0 && top <= array.Length / 4)
{
ResizeStack(array.Length / 2);
}
return item;
}
///<summary>
/// creates a new array of size `length`, copies over elements from the array which maintains stack,
/// and replaces the original array with resized array
///<summary>
private void ResizeStack(int length)
{
if (length <= 0)
{
length = 1;
}
var tempArray = new Object[length];
for (int i = 0; i <= top; i++)
{
tempArray[i] = array[i];
}
array = tempArray;
}
}
| mit | C# | |
b9173f085ddc95b5d599d68b7761de672e7c4bfa | Create EventVariant.cs | Moci1/ColorBox | EventVariant.cs | EventVariant.cs | using System;
namespace ColorBox
{
public class ValidEventArgs : EventArgs
{
public bool IsValid { get; set; }
}
}
| mit | C# | |
566d7a360cc3ad88a1dbde328863351e4972e492 | Set name for Avalonia thread to identify it more easily in debugger. | uoinfusion/Infusion | Infusion.Desktop/App.xaml.cs | Infusion.Desktop/App.xaml.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Avalonia;
using Avalonia.Logging.Serilog;
namespace Infusion.Desktop
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
private Avalonia.Application avaloniaApplication;
private CancellationTokenSource applicationClosedTokenSource = new CancellationTokenSource();
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length == 2)
{
if (e.Args[0] == "command")
{
InterProcessCommunication.SendCommand(e.Args[1]);
Shutdown(0);
}
}
CommandLine.Handler.Handle(e.Args);
Task.Run(() =>
{
Thread.CurrentThread.Name = "Avalonia";
avaloniaApplication = AppBuilder.Configure<AvaloniaApp>()
.UsePlatformDetect()
.UseReactiveUI()
.LogToDebug()
.SetupWithoutStarting()
.Instance;
avaloniaApplication.ExitMode = ExitMode.OnExplicitExit;
avaloniaApplication.Run(applicationClosedTokenSource.Token);
});
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
foreach (var window in avaloniaApplication.Windows)
{
window.Close();
}
avaloniaApplication.MainWindow?.Close();
applicationClosedTokenSource.Cancel();
base.OnExit(e);
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Avalonia;
using Avalonia.Logging.Serilog;
namespace Infusion.Desktop
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
private Avalonia.Application avaloniaApplication;
private CancellationTokenSource applicationClosedTokenSource = new CancellationTokenSource();
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length == 2)
{
if (e.Args[0] == "command")
{
InterProcessCommunication.SendCommand(e.Args[1]);
Shutdown(0);
}
}
CommandLine.Handler.Handle(e.Args);
Task.Run(() =>
{
avaloniaApplication = AppBuilder.Configure<AvaloniaApp>()
.UsePlatformDetect()
.UseReactiveUI()
.LogToDebug()
.SetupWithoutStarting()
.Instance;
avaloniaApplication.ExitMode = ExitMode.OnExplicitExit;
avaloniaApplication.Run(applicationClosedTokenSource.Token);
});
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
foreach (var window in avaloniaApplication.Windows)
{
window.Close();
}
avaloniaApplication.MainWindow?.Close();
applicationClosedTokenSource.Cancel();
base.OnExit(e);
}
}
}
| mit | C# |
92a4f30704e5e548cdca0e3291cc8e609db70060 | add missing file | bdb-opensource/whitelist-executer,bdb-opensource/whitelist-executer,bdb-opensource/whitelist-executer | WhitelistExecuter.Web/App_Start/ErrorHandler.cs | WhitelistExecuter.Web/App_Start/ErrorHandler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using log4net;
namespace WhitelistExecuter.Web.App_Start
{
public class ErrorHandler : HandleErrorAttribute
{
protected static readonly ILog _logger = log4net.LogManager.GetLogger("ErrorHandler");
public override void OnException(ExceptionContext filterContext)
{
_logger.Error("ErrorHandler handled error", filterContext.Exception);
base.OnException(filterContext);
}
}
}
| mit | C# | |
2d36062159d8b3e5e77740eed2ec3c1305c2b60f | Add ClickableText | ppy/osu,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu,johnneijzen/osu,ZLima12/osu,johnneijzen/osu,peppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,2yangk23/osu,smoogipoo/osu,smoogipooo/osu | osu.Game/Graphics/UserInterface/ClickableText.cs | osu.Game/Graphics/UserInterface/ClickableText.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 OpenTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input;
using System;
namespace osu.Game.Graphics.UserInterface
{
public class ClickableText : SpriteText, IHasTooltip
{
private bool isEnabled;
private SampleChannel sampleHover;
private SampleChannel sampleClick;
public Action Action;
public bool IsEnabled
{
get { return isEnabled; }
set
{
isEnabled = value;
Alpha = value ? 1 : 0.5f;
}
}
public ClickableText() => isEnabled = true;
public override bool HandleMouseInput => true;
protected override bool OnHover(InputState state)
{
if (isEnabled)
sampleHover?.Play();
return base.OnHover(state);
}
protected override bool OnClick(InputState state)
{
if (isEnabled)
{
sampleClick?.Play();
Action?.Invoke();
}
return base.OnClick(state);
}
public string TooltipText { get; set; }
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleHover = audio.Sample.Get(@"UI/generic-hover-soft");
}
}
}
| mit | C# | |
339d87d3af09d262d124683dc916e7f52258bc25 | Create GenteControlD__.cs | MesoamericaAppsHackatonPanama2013/SimulacionDesastres | GenteControlD__.cs | GenteControlD__.cs | using UnityEngine;
using System.Collections;
public class GenteControlD__ : MonoBehaviour {
void OnCollisionEnter(Collision col){
if(col.collider.tag == "Player"){
Debug.Log("toca");
Destroy(gameObject);}
}
}
| mit | C# | |
9130e2590cfcc7286a09a907bffc996ad6b6b51c | Create browser.cs | ATailsLLC/BlocklandChrome | browser.cs | browser.cs | package BChrome
{
}
activatePackage(BChrome);
| apache-2.0 | C# | |
6ca4a2c16dfbae78488cee30b007f2226f485736 | Create GuidExtensions.cs | drawcode/labs-csharp | extensions/GuidExtensions.cs | extensions/GuidExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public static class GuidExtensions {
public static bool IsNullOrEmpty(this Guid inst) {
if (inst != null && inst != new Guid()) {
return true;
}
return false;
}
public static Guid Zero() {
return new Guid("00000000-0000-0000-0000-000000000000");
}
public static Guid Generate() {
return System.Guid.NewGuid();
}
}
| mit | C# | |
e65a8709ce69ac12be985e08f1c53f869444c0df | Add class Axe.cs in Models/Gear/Weapons/Axe.cs | baretata/CSharpOOP-TeamRedCurrantGame | RibesTerra/Models/Gear/Weapons/Axe.cs | RibesTerra/Models/Gear/Weapons/Axe.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models.Gear.Items
{
class Axe
{
}
}
| mit | C# | |
9c4594b3f293da70132e9355fd5d6738a9ed7496 | add debug | yangyu19840716/Alpha | Assets/src/Debug.cs | Assets/src/Debug.cs | using UnityEngine;
using System.Collections.Generic;
class DebugModule
{
public static Material lineMaterial = null;
public static Material redlineMaterial = null;
public static Material greenlineMaterial = null;
public static GameObject circle = null;
public static void GLDrawLine(Vector3 start, Vector3 end)
{
GL.PushMatrix();
lineMaterial.SetPass(0);
GL.Begin(GL.LINES);
GL.Vertex3(start.x, start.y, start.z);
GL.Vertex3(end.x, end.y, end.z);
GL.End();
GL.PopMatrix();
}
public static void GLDrawRedLine(Vector3 start, Vector3 end)
{
GL.PushMatrix();
redlineMaterial.SetPass(0);
GL.Begin(GL.LINES);
GL.Vertex3(start.x, start.y, start.z);
GL.Vertex3(end.x, end.y, end.z);
GL.End();
GL.PopMatrix();
}
public static void GLDrawGreenLine(Vector3 start, Vector3 end)
{
GL.PushMatrix();
greenlineMaterial.SetPass(0);
GL.Begin(GL.LINES);
GL.Vertex3(start.x, start.y, start.z);
GL.Vertex3(end.x, end.y, end.z);
GL.End();
GL.PopMatrix();
}
public static void DrawEntityLine(Entity entity)
{
if (entity == null)
return;
for (int i = 0; i < entity.friendList.Count; i++)
{
Entity f = entity.friendList[i];
DebugModule.GLDrawGreenLine(entity.obj.transform.position, f.obj.transform.position);
}
for (int i = 0; i < entity.enemyList.Count; i++)
{
Entity e = entity.enemyList[i];
DebugModule.GLDrawRedLine(entity.obj.transform.position, e.obj.transform.position);
}
}
public static void DrawWorldGrid()
{
Vector3 pos1 = new Vector3();
Vector3 pos2 = new Vector3();
Vector3 pos3 = new Vector3();
Vector3 pos4 = new Vector3();
pos1.y = pos2.y = pos3.y = pos4.y = 0.5f;
float f = World.GetInstacne().worldSize * 0.5f;
float gridSize = World.GetInstacne().gridSize;
for (int i = 0; i <= GridPos.gridNum; i++)
{
pos1.x = pos3.z = -f + gridSize * i;
pos1.z = pos3.x = -f;
pos2.x = pos4.z = -f + gridSize * i;
pos2.z = pos4.x = f;
DebugModule.GLDrawLine(pos1, pos2);
DebugModule.GLDrawLine(pos3, pos4);
}
}
public static void DrawEntityGrid(Entity entity)
{
if (entity == null)
return;
Vector3 pos1 = new Vector3();
Vector3 pos2 = new Vector3();
Vector3 pos3 = new Vector3();
Vector3 pos4 = new Vector3();
pos1.y = pos2.y = pos3.y = pos4.y = 0.5f;
float gridSize = World.GetInstacne().gridSize;
List<GridPos> list = World.GetInstacne().GetGrids(entity.obj.transform.position.x, entity.obj.transform.position.z, entity.GetData().range);
for (int i = 0; i < list.Count; i++)
{
Vector2 pos = World.GetInstacne().GetGridCenter(list[i]);
pos1.x = pos4.x = pos.x - gridSize * 0.5f;
pos1.z = pos3.z = pos.y - gridSize * 0.5f;
pos2.x = pos3.x = pos.x + gridSize * 0.5f;
pos2.z = pos4.z = pos.y + gridSize * 0.5f;
GLDrawLine(pos1, pos2);
GLDrawLine(pos3, pos4);
}
}
public static void ShowCircle(Vector3 pos, float r)
{
if (circle == null)
return;
Renderer circleRenderer = circle.GetComponent<Renderer>();
circleRenderer.enabled = false;
circle.transform.position = pos;
circle.transform.localScale = new Vector3(r, 0.0f, r);
circleRenderer.enabled = true;
}
public static void hideCircle()
{
if (circle == null)
return;
Renderer circleRenderer = circle.GetComponent<Renderer>();
circleRenderer.enabled = false;
}
} | mit | C# | |
f4fdd0dbe19c27a06dd654b83e05570e4f957833 | Add methods to refresh desktop and file explorer. | Si13n7/SilDev.CSharpLib | src/SilDev/Desktop.cs | src/SilDev/Desktop.cs | #region auto-generated FILE INFORMATION
// ==============================================
// This file is distributed under the MIT License
// ==============================================
//
// Filename: Desktop.cs
// Version: 2017-10-31 08:39
//
// Copyright (c) 2017, Si13n7 Developments (r)
// All rights reserved.
// ______________________________________________
#endregion
namespace SilDev
{
using System.IO;
using SHDocVw;
/// <summary>
/// Provides the functionality to manage desktop functions.
/// </summary>
public static class Desktop
{
/// <summary>
/// Refreshes the desktop.
/// </summary>
/// <param name="explorer">
/// true to refresh all open explorer windows; otherwise, false
/// </param>
public static void Refresh(bool explorer = true)
{
var hWnd = WinApi.NativeHelper.FindWindow("Progman", "Program Manager");
var cNames = new[]
{
"SHELLDLL_DefView",
"SysListView32"
};
foreach (var cName in cNames)
WinApi.NativeHelper.FindNestedWindow(ref hWnd, cName);
KeyState.SendState(hWnd, KeyState.VKey.VK_F5);
if (explorer)
RefreshExplorer();
}
/// <summary>
/// Refreshes all open explorer windows.
/// </summary>
/// <param name="extended">
/// true to wait for a window to refresh, if there is no window available;
/// otherwise, false
/// </param>
public static void RefreshExplorer(bool extended = false)
{
var hasUpdated = extended;
var shellWindows = new ShellWindows();
do
{
foreach (InternetExplorer window in shellWindows)
{
var name = Path.GetFileName(window?.FullName);
if (name?.EqualsEx("explorer.exe") != true)
continue;
window.Refresh();
hasUpdated = true;
}
}
while (!hasUpdated);
}
}
}
| mit | C# | |
be3cf68c86bb143e27c4c79a5e4b7792809cb840 | use 'zlib' compression method instead of 'deflate'. | dsp2003/GARbro,morkt/GARbro,dsp2003/GARbro,dsp2003/GARbro,morkt/GARbro | deflate.cs | deflate.cs | //! \file deflate.cs
//! \date Tue Jul 08 15:01:34 2014
//! \brief deflate file into zlib stream.
//
using System;
using System.IO;
using ZLibNet;
class Inflate
{
public static void Main (string[] args)
{
if (args.Length != 2)
{
Console.WriteLine ("Usage: deflate INPUT-FILE OUTPUT-FILE");
return;
}
try
{
using (var input = File.Open (args[0], FileMode.Open, FileAccess.Read))
using (var output = File.Create (args[1]))
using (var stream = new ZLibStream (output, CompressionMode.Compress, CompressionLevel.Level9))
input.CopyTo (stream);
Console.WriteLine ("{0} => {1}", args[0], args[1]);
}
catch (Exception X)
{
Console.Error.WriteLine (X.Message);
}
}
}
| //! \file deflate.cs
//! \date Tue Jul 08 15:01:34 2014
//! \brief deflate file into zlib stream.
//
using System;
using System.IO;
using ZLibNet;
class Inflate
{
public static void Main (string[] args)
{
if (args.Length != 2)
return;
try
{
using (var input = File.Open (args[0], FileMode.Open, FileAccess.Read))
using (var output = File.Create (args[1]))
using (var stream = new DeflateStream (output, CompressionMode.Compress, CompressionLevel.Level5))
input.CopyTo (stream);
Console.WriteLine ("{0} => {1}", args[0], args[1]);
}
catch (Exception X)
{
Console.Error.WriteLine (X.Message);
}
}
}
| mit | C# |
2e48179d900e52ada9df98851bd6effae2ea5ff0 | Create TestMongoClientProvider.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/Data/Mongo/TestMongoClientProvider.cs | TIKSN.Framework.IntegrationTests/Data/Mongo/TestMongoClientProvider.cs | using Microsoft.Extensions.Configuration;
using TIKSN.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests.Data.Mongo
{
public class TestMongoClientProvider : MongoClientProviderBase
{
public TestMongoClientProvider(IConfiguration configuration) : base(configuration, "Mongo")
{
}
}
} | mit | C# | |
377c53be28b4a24e7bc109891512246105f234ab | create an interface to abstract the notion of set for some security related classes. | nohros/must,nohros/must,nohros/must | src/base/common/security/auth/sets/ISecureSet.cs | src/base/common/security/auth/sets/ISecureSet.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Nohros.Security.Auth
{
public interface ISecureSet<T>
{
/// <summary>
/// Adds the specified element to the set.
/// </summary>
/// <param name="element">The element to add to the set.</param>
/// <returns>true if the element is added to the <see cref="SecureSet"/> object; false if the
/// element is already present. Note that the value returned from the GetHashCode() method of the
/// element object is used when comparing values in the set.</returns>
/// <exception cref="ArgumentNullException"><paramref name="element"/> is a null reference.</exception>
bool Add(T element);
/// <summary>
/// Removes the specified element from a <see cref="ISecureSet<T>"/> object.
/// </summary>
/// <param name="element">The element to remove.</param>
/// <returns>true if the element is successfully found and removed; otherwise, false. This method
/// returns false if <paramref name="element"/> is not found in the <see cref="ISecureSet<T>"/>
/// object. Note that the value returned from the GetHashCode() method of the element object
/// is used when comparing values in the set. So, if two elements with the same value coexists
/// in the set, this method, depending if the <paramref name="element"/> object overrides the
/// <see cref="object.Equals(object)"/> method, could remove only one of them.</returns>
bool Remove(T element);
/// <summary>
/// Determines whether the <see cref="ISecureSet<T>"/> contains a specific value.
/// </summary>
/// <param name="element">The object to locate in the <see cref="ISecureSet<T>"/>.</param>
/// <returns>true if the item is found in the collection; otherwise, false.</returns>
bool Contains(T element);
/// <summary>
/// Gets the number of elements that are contained in the set.
/// </summary>
/// <value>The number of elements contained in the <see cref="ISecureSet<T>"/></value>
int Count { get; }
/// <summary>
/// Removes all items from the <see cref="ISecureSet<T>"/>
/// </summary>
/// <remarks>
/// <see cref="Count"/> must be set to zero, and references to other objects from elements of the
/// collection must be released.
/// </remarks>
void Clear();
}
}
| mit | C# | |
bbb7f71fa3a9056544a90ce54de688ef6e25e124 | Create rectangle.cs | HeyIamJames/Learning-C-,HeyIamJames/Learning-C- | rectangle.cs | rectangle.cs | //https://www.tutorialspoint.com/csharp/csharp_basic_syntax.htm
using System;
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
| mit | C# | |
4cad51b9d5fdcd080c097276e3f5113bd55fe5e9 | Add UpdateSitelink example (#237) | googleads/google-ads-dotnet,googleads/google-ads-dotnet,googleads/google-ads-dotnet,googleads/google-ads-dotnet | examples/Extensions/UpdateSitelink.cs | examples/Extensions/UpdateSitelink.cs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V5.Common;
using Google.Ads.GoogleAds.V5.Errors;
using Google.Ads.GoogleAds.V5.Resources;
using Google.Ads.GoogleAds.V5.Services;
namespace Google.Ads.GoogleAds.Examples.V5
{
/// <summary>
/// Updates the sitelink extension feed item with the specified link text and URL.
/// </summary>
public class UpdateSitelink : ExampleBase
{
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
UpdateSitelink codeExample = new UpdateSitelink();
Console.WriteLine(codeExample.Description);
// The Google Ads customer ID for which the call is made.
long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The feed item ID to update.
long feedItemId = long.Parse("INSERT_FEED_ITEM_ID_HERE");
// The new sitelink text.
string sitelinkText = "INSERT_SITELINK_TEXT_HERE";
codeExample.Run(new GoogleAdsClient(), customerId, feedItemId, sitelinkText);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"Updates the sitelink extension feed item with the specified link text and URL.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="feedItemId">The feed item ID to update.</param>
/// <param name="sitelinkText">The new sitelink text.</param>
public void Run(GoogleAdsClient client, long customerId, long feedItemId,
string sitelinkText)
{
// Get the ExtensionFeedItemService.
ExtensionFeedItemServiceClient extensionFeedItemService =
client.GetService(Services.V5.ExtensionFeedItemService);
// Create an extension feed item using the specified feed item ID and sitelink text.
ExtensionFeedItem extensionFeedItem = new ExtensionFeedItem
{
ResourceName = ResourceNames.ExtensionFeedItem(customerId, feedItemId),
SitelinkFeedItem = new SitelinkFeedItem
{
LinkText = sitelinkText
}
};
// Construct an operation that will update the extension feed item using the FieldMasks
// utilities to derive the update mask. This mask tells the Google Ads API which
// attributes of the extension feed item you want to change.
ExtensionFeedItemOperation extensionFeedItemOperation = new ExtensionFeedItemOperation
{
Update = extensionFeedItem,
UpdateMask = FieldMasks.AllSetFieldsOf(extensionFeedItem)
};
try
{
// Issue a mutate request to update the extension feed item.
MutateExtensionFeedItemsResponse response =
extensionFeedItemService.MutateExtensionFeedItems(
customerId.ToString(), new[] {extensionFeedItemOperation});
// Print the resource name of the updated extension feed item.
Console.WriteLine("Updated extension feed item with resource name " +
$"'{response.Results.First().ResourceName}'.");
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
}
}
| apache-2.0 | C# | |
b10c786752aa3a2212cbcb9656556452ba29b710 | Create ButtonColorChange.cs | MatrixNAN/Unity-Artist-Tools | ButtonColorChange.cs | ButtonColorChange.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonColorChange : MonoBehaviour
{
public bool isClicked = false;
void Start()
{
if (isClicked)
{
var colors = GetComponent<Button> ().colors;
// This code should work but it does not because of a bug in Unity UI Button
//colors.normalColor = colors.pressedColor;
//GetComponent<Button> ().colors = colors;
// So we have to do the line below instead
GetComponent<Image>().color = colors.pressedColor;
}
else
{
var colors = GetComponent<Button> ().colors;
// This code should work but it does not because of a bug in Unity UI Button
//colors.normalColor = Color.white;
//GetComponent<Button> ().colors = colors;
// So we have to do the line below instead
GetComponent<Image>().color = colors.normalColor;
}
}
public void ActivateButtonColor()
{
if (isClicked)
{
isClicked = false;
var colors = GetComponent<Button> ().colors;
// This code should work but it does not because of a bug in Unity UI Button
//colors.normalColor = Color.white;
//GetComponent<Button> ().colors = colors;
// So we have to do the line below instead
GetComponent<Image>().color = colors.normalColor;
}
else
{
isClicked = true;
var colors = GetComponent<Button> ().colors;
// This code should work but it does not because of a bug in Unity UI Button
//colors.normalColor = colors.pressedColor;
//GetComponent<Button> ().colors = colors;
// So we have to do the line below instead
GetComponent<Image>().color = colors.pressedColor;
}
}
}
| apache-2.0 | C# | |
7305b38e15ba4eb31225c9772a8fb2659a7035e2 | Create LinqPivot.cs | slaceved/CSharp | LinqPivot.cs | LinqPivot.cs | using System.Linq;
using System.Data;
using System.Collections.Generic;
namespace Capstone_Game_Platform
{
internal class LinqPivot
{
public DataTable Pivot(DataTable dt, DataColumn pivotColumn, string pivotName)
{
DataTable temp = dt.Copy();
temp.Columns.Remove(pivotColumn.ColumnName);
string[] dataColumnNames = temp.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToArray();
DataTable result = new DataTable();
DataColumn pivot = new DataColumn
{
ColumnName = pivotName
};
result.Columns.Add(pivot);
result.DefaultView.ToTable(true, pivotName);
DataRow dr = result.NewRow();
for (int j = 0; j < temp.Columns.Count; j++)
{
result.Rows.Add(temp.Columns[j].ColumnName);
}
List<string> t = dt.AsEnumerable()
.Select(r => r[pivotColumn.ColumnName].ToString())
.Distinct()
.ToList();
t.ForEach(c => result.Columns.Add(c));
for (int j = 0; j < t.Count; j++) //for each pivotColumn named value
{
foreach (string s in dataColumnNames) //for each dataColumnName
{
//select value of dataColumnName string
//where the pivotColum is equal to the current value from the list of pivotColum values
string value = (from row in dt.AsEnumerable()
where row.Field<string>(pivotColumn.ColumnName) == t[j]
select row.Field<string>(s)).SingleOrDefault();
DataRow pk = (from row in result.AsEnumerable()
where row.Field<string>(pivotName) == s
select row).SingleOrDefault();
pk.BeginEdit();
int index = pk.Table.Columns.IndexOf(t[j]);
pk[index] = value;
pk.EndEdit();
pk.AcceptChanges();
}
}
return result;
}
}
public static class DataRowExtensions
{
public static T GetCellValueByName<T>(this DataRow row, string columnName)
{
int index = row.Table.Columns.IndexOf(columnName);
return (index < 0 || index > row.ItemArray.Count())
? default(T)
: (T)row[index];
}
}
}
| unlicense | C# | |
0f9d6cd72325b056126dd69711ffa453e87fbfb3 | Disable warning `CanExecuteChanged` is never used for ExecuteCommand. | kingsamchen/EasyKeeper | CommandHelper.cs | CommandHelper.cs | /*
@ 0xCCCCCCCC
*/
using System;
using System.Windows.Input;
namespace EasyKeeper {
// Provides a general implementation for commands.
// T must be of nullable, since the `param` in methods might be null.
class RelayCommand<T> : ICommand {
private readonly Action<T> _action;
private readonly Predicate<T> _canExecute;
public RelayCommand(Action<T> action, Predicate<T> canExecute = null)
{
_action = action;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object param)
{
return _canExecute == null || _canExecute((T)param);
}
public void Execute(object param)
{
_action((T)param);
}
}
// Provides an approach for View to execute commands in ViewModel.
// Unlike uses of RelayCommand, these commands are manually invoked.
class ExecuteCommand<T, TResult> : ICommand {
// Unfortunately, we don't need it.
#pragma warning disable 0067
public event EventHandler CanExecuteChanged;
#pragma warning restore 0067
private readonly Func<T, TResult> _fn;
private readonly Predicate<T> _canExecute;
private TResult _result;
public ExecuteCommand(Func<T, TResult> fn, Predicate<T> canExecute = null)
{
_fn = fn;
_canExecute = canExecute;
}
public TResult Result
{
get { return _result; }
}
public bool CanExecute(object param)
{
return _canExecute == null || _canExecute((T)param);
}
public void Execute(object param)
{
ResetResult();
_result = _fn((T)param);
}
private void ResetResult()
{
_result = default(TResult);
}
}
}
| /*
@ 0xCCCCCCCC
*/
using System;
using System.Windows.Input;
namespace EasyKeeper {
// Provides a general implementation for commands.
// T must be of nullable, since the `param` in methods might be null.
class RelayCommand<T> : ICommand {
private readonly Action<T> _action;
private readonly Predicate<T> _canExecute;
public RelayCommand(Action<T> action, Predicate<T> canExecute = null)
{
_action = action;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object param)
{
return _canExecute == null || _canExecute((T)param);
}
public void Execute(object param)
{
_action((T)param);
}
}
// Provides an approach for View to execute commands in ViewModel.
// Unlike uses of RelayCommand, these commands are manually invoked.
class ExecuteCommand<T, TResult> : ICommand {
// Unfortunately, we don't need it.
public event EventHandler CanExecuteChanged;
private readonly Func<T, TResult> _fn;
private readonly Predicate<T> _canExecute;
private TResult _result;
public ExecuteCommand(Func<T, TResult> fn, Predicate<T> canExecute = null)
{
_fn = fn;
_canExecute = canExecute;
}
public TResult Result
{
get { return _result; }
}
public bool CanExecute(object param)
{
return _canExecute == null || _canExecute((T)param);
}
public void Execute(object param)
{
ResetResult();
_result = _fn((T)param);
}
private void ResetResult()
{
_result = default(TResult);
}
}
}
| mit | C# |
52b0c3bb7087768944462f8f93b9e3d66395c63a | Make setters in attributes private | chitoku-k/CoreTweet,azyobuzin/LibAzyotter,cannorin/CoreTweet | CoreTweet.Shared/Attribute.cs | CoreTweet.Shared/Attribute.cs | // The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace CoreTweet
{
/// <summary>
/// Twitter parameter attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TwitterParameterAttribute : Attribute
{
/// <summary>
/// Name of the parameter binding for.
/// </summary>
/// <value>The name.</value>
public string Name { get; }
/// <summary>
/// Default value of the parameter.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue { get; }
/// <summary>
/// Initializes a new instance of the <see cref="TwitterParameterAttribute"/> class.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="defaultValue">Default value.</param>
public TwitterParameterAttribute(string name = null, object defaultValue = null)
{
Name = name;
DefaultValue = defaultValue;
}
}
/// <summary>
/// Twitter parameters attribute.
/// This is used for a class.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class TwitterParametersAttribute : Attribute {}
}
| // The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace CoreTweet
{
/// <summary>
/// Twitter parameter attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TwitterParameterAttribute : Attribute
{
/// <summary>
/// Name of the parameter binding for.
/// </summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>
/// Default value of the parameter.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TwitterParameterAttribute"/> class.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="defaultValue">Default value.</param>
public TwitterParameterAttribute(string name = null, object defaultValue = null)
{
Name = name;
DefaultValue = defaultValue;
}
}
/// <summary>
/// Twitter parameters attribute.
/// This is used for a class.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class TwitterParametersAttribute : Attribute {}
}
| mit | C# |
850ceab3a413b076efbc3d31037e63555e8388b5 | Add Explicit operator test | Ruhrpottpatriot/SemanticVersion | test/SemanticVersionTest/ConversionTests.cs | test/SemanticVersionTest/ConversionTests.cs | namespace SemanticVersionTest
{
using System;
using Semver;
using Xunit;
public class ConversionTests
{
[Fact]
public void Conversion()
{
Version dotNetVersion = new Version(1, 1, 1, 1);
SemanticVersion semanticVersion = (SemanticVersion)dotNetVersion;
Assert.Equal(1, semanticVersion.Major);
Assert.Equal(1, semanticVersion.Minor);
Assert.Equal(1, semanticVersion.Patch);
Assert.Equal(string.Empty, semanticVersion.Prerelease);
Assert.Equal("1", semanticVersion.Build);
}
[Fact]
public void ConversionNoBuildNoRevision()
{
Version dotNetVersion = new Version(1, 1);
SemanticVersion semanticVersion = (SemanticVersion)dotNetVersion;
Assert.Equal(1, semanticVersion.Major);
Assert.Equal(1, semanticVersion.Minor);
Assert.Equal(0, semanticVersion.Patch);
Assert.Equal(string.Empty, semanticVersion.Prerelease);
Assert.Equal(string.Empty, semanticVersion.Build);
}
[Fact]
public void ConversionNull()
{
Version dotNetVersion = null;
Assert.Throws<ArgumentNullException>(() =>
{
SemanticVersion version = (SemanticVersion)dotNetVersion;
});
}
}
}
| mit | C# | |
f51b50117dc22b7bb42e5f9d00c2eb8d8e3cddc8 | Fix GUIDs not being parsed from Strings | RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake | src/Snowflake.Support.Remoting.GraphQl/Types/GuidGraphType.cs | src/Snowflake.Support.Remoting.GraphQl/Types/GuidGraphType.cs | using System;
using GraphQL.Language.AST;
using GraphQL.Types;
namespace GraphQL.Types
{
public class GuidGraphType : ScalarGraphType
{
public GuidGraphType()
{
Name = "Guid";
Description = "Globally Unique Identifier.";
}
public override object ParseValue(object value) =>
ValueConverter.ConvertTo(value, typeof(Guid));
public override object Serialize(object value) => ParseValue(value);
/// <inheritdoc/>
public override object ParseLiteral(IValue value)
{
if (value is GuidValue guidValue)
{
return guidValue.Value;
}
if (value is StringValue str)
{
return ParseValue(str.Value);
}
return null;
}
}
} | mpl-2.0 | C# | |
84ee8aac9552405b83a54fd7498fee1713fca650 | Create Joystick.cs | GibTreaty/Unity | Joystick.cs | Joystick.cs | using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.UI {
[AddComponentMenu("UI/Joystick", 36), RequireComponent(typeof(RectTransform))]
public class Joystick : UIBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler {
[SerializeField, Tooltip("The graphic that will be moved around")]
RectTransform _joystickGraphic;
public RectTransform JoystickGraphic {
get { return _joystickGraphic; }
set {
_joystickGraphic = value;
UpdateJoystickGraphic();
}
}
[SerializeField]
Vector2 _axis;
[SerializeField, Tooltip("How fast the joystick will go back to the center")]
float _spring = 25;
public float Spring {
get { return _spring; }
set { _spring = value; }
}
[SerializeField, Tooltip("How close to the center that the axis will be output as 0")]
float _deadZone = .1f;
public float DeadZone {
get { return _deadZone; }
set { _deadZone = value; }
}
[Tooltip("Customize the output that is sent in OnValueChange")]
public AnimationCurve outputCurve = new AnimationCurve(new Keyframe(0, 0, 1, 1), new Keyframe(1, 1, 1, 1));
public JoystickMoveEvent OnValueChange;
public Vector2 JoystickAxis {
get {
Vector2 outputPoint = _axis.magnitude > _deadZone ? _axis : Vector2.zero;
float magnitude = outputPoint.magnitude;
outputPoint *= outputCurve.Evaluate(magnitude);
return outputPoint;
}
set { SetAxis(value); }
}
RectTransform _rectTransform;
public RectTransform rectTransform {
get {
if(!_rectTransform) _rectTransform = transform as RectTransform;
return _rectTransform;
}
}
bool _isDragging;
[HideInInspector]
bool dontCallEvent;
public void OnBeginDrag(PointerEventData eventData) {
if(!IsActive())
return;
EventSystemManager.currentSystem.SetSelectedGameObject(gameObject, eventData);
Vector2 newAxis = transform.InverseTransformPoint(eventData.position);
newAxis.x /= rectTransform.sizeDelta.x * .5f;
newAxis.y /= rectTransform.sizeDelta.y * .5f;
SetAxis(newAxis);
_isDragging = true;
dontCallEvent = true;
}
public void OnEndDrag(PointerEventData eventData) {
_isDragging = false;
}
public void OnDrag(PointerEventData eventData) {
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out _axis);
_axis.x /= rectTransform.sizeDelta.x * .5f;
_axis.y /= rectTransform.sizeDelta.y * .5f;
SetAxis(_axis);
dontCallEvent = true;
}
void OnDeselect() {
_isDragging = false;
}
void Update() {
if(_isDragging)
if(!dontCallEvent)
if(OnValueChange != null) OnValueChange.Invoke(JoystickAxis);
}
void LateUpdate() {
if(!_isDragging)
if(_axis != Vector2.zero) {
Vector2 newAxis = _axis - (_axis * Time.unscaledDeltaTime * _spring);
if(newAxis.sqrMagnitude <= .0001f)
newAxis = Vector2.zero;
SetAxis(newAxis);
}
dontCallEvent = false;
}
protected override void OnValidate() {
base.OnValidate();
UpdateJoystickGraphic();
}
public void SetAxis(Vector2 axis) {
_axis = Vector2.ClampMagnitude(axis, 1);
Vector2 outputPoint = _axis.magnitude > _deadZone ? _axis : Vector2.zero;
float magnitude = outputPoint.magnitude;
outputPoint *= outputCurve.Evaluate(magnitude);
if(!dontCallEvent)
if(OnValueChange != null)
OnValueChange.Invoke(outputPoint);
UpdateJoystickGraphic();
}
void UpdateJoystickGraphic() {
if(_joystickGraphic)
_joystickGraphic.localPosition = _axis * Mathf.Max(rectTransform.sizeDelta.x, rectTransform.sizeDelta.y) * .5f;
}
[System.Serializable]
public class JoystickMoveEvent : UnityEvent<Vector2> { }
}
}
#if UNITY_EDITOR
static class JoystickGameObjectCreator {
[MenuItem("GameObject/UI/Joystick", false, 2000)]
static void Create() {
GameObject go = new GameObject("Joystick", typeof(Joystick));
Canvas canvas = Selection.activeGameObject ? Selection.activeGameObject.GetComponent<Canvas>() : null;
Selection.activeGameObject = go;
if(!canvas)
canvas = Object.FindObjectOfType<Canvas>();
if(!canvas) {
canvas = new GameObject("Canvas", typeof(Canvas), typeof(RectTransform), typeof(GraphicRaycaster)).GetComponent<Canvas>();
canvas.renderMode = RenderMode.Overlay;
}
if(canvas)
go.transform.SetParent(canvas.transform, false);
GameObject background = new GameObject("Background", typeof(Image));
GameObject graphic = new GameObject("Graphic", typeof(Image));
background.transform.SetParent(go.transform, false);
graphic.transform.SetParent(go.transform, false);
background.GetComponent<Image>().color = new Color(1, 1, 1, .86f);
RectTransform backgroundTransform = graphic.transform as RectTransform;
RectTransform graphicTransform = graphic.transform as RectTransform;
graphicTransform.sizeDelta = backgroundTransform.sizeDelta * .5f;
Joystick joystick = go.GetComponent<Joystick>();
joystick.JoystickGraphic = graphicTransform;
}
}
#endif
| mit | C# | |
112c8515960ab4cdb762f9f0819d7ee5dd2f8a07 | Create GlobalSuppressions.cs | hprose/hprose-dotnet | proj/Hprose.RPC.AspNet/GlobalSuppressions.cs | proj/Hprose.RPC.AspNet/GlobalSuppressions.cs |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<挂起>", Scope = "member", Target = "~M:Hprose.RPC.AspNet.AspNetHttpHandler.GetOutputStream(System.Web.HttpRequest,System.Web.HttpResponse)~System.IO.Stream")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<挂起>", Scope = "member", Target = "~M:Hprose.RPC.AspNet.AspNetHttpHandler.ClientAccessPolicyXmlHandler(System.Web.HttpRequest,System.Web.HttpResponse)~System.Threading.Tasks.Task{System.Boolean}")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<挂起>", Scope = "member", Target = "~M:Hprose.RPC.AspNet.AspNetHttpHandler.CrossDomainXmlHandler(System.Web.HttpRequest,System.Web.HttpResponse)~System.Threading.Tasks.Task{System.Boolean}")] | mit | C# | |
eafa764e6d5915461d71f4918268bd5f19d42c19 | Implement room exists data contract | Zalodu/Schedutalk,Zalodu/Schedutalk | Schedutalk/Schedutalk/Schedutalk/Logic/KTHPlaces/RoomDataContract.cs | Schedutalk/Schedutalk/Schedutalk/Logic/KTHPlaces/RoomDataContract.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.Logic.KTHPlaces
{
[DataContract]
public class RoomDataContract
{
[DataMember(Name = "floorUid")]
public string FloorUId { get; set; }
[DataMember(Name = "buildingName")]
public string BuildingName { get; set; }
[DataMember(Name = "campus")]
public string Campus { get; set; }
[DataMember(Name = "typeName")]
public string TypeName { get; set; }
[DataMember(Name = "placeName")]
public string PlaceName { get; set; }
[DataMember(Name = "uid")]
public string UId { get; set; }
}
}
| mit | C# | |
e855be180178532e3b490d8da67aa8e3b5d86be7 | Create Program4.cs | neilopet/projecteuler_cs | Program4.cs | Program4.cs | /*
* Problem #4
* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
using System;
using System.Collections.Generic;
public class Problem4
{
public void Main()
{
int LargestPalindrome = 1;
for (int i = 998001; i > 10001; i--)
{
for (int j = 999; j > 99; j--)
{
if (i % j == 0
&& IsPalindrome(i.ToString())
&& (i/j).ToString().Length == 3)
{
LargestPalindrome = i;
i = 0;
break;
}
}
}
Console.WriteLine(LargestPalindrome);
}
public bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
min++;
max--;
}
}
}
| mit | C# | |
7ce827d87d5912546fded4c1f59fb771f83e6b47 | add verifier template | distantcam/Fody,ColinDabritzViewpoint/Fody,GeertvanHorrik/Fody,Fody/Fody | Verifier.cs | Verifier.cs | using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Utilities;
using NUnit.Framework;
public static class Verifier
{
public static void Verify(string beforeAssemblyPath, string afterAssemblyPath)
{
var before = Validate(beforeAssemblyPath);
var after = Validate(afterAssemblyPath);
var message = $"Failed processing {Path.GetFileName(afterAssemblyPath)}\r\n{after}";
Assert.AreEqual(TrimLineNumbers(before), TrimLineNumbers(after), message);
}
static string Validate(string assemblyPath2)
{
var exePath = GetPathToPeVerify();
if (!File.Exists(exePath))
{
return string.Empty;
}
var process = Process.Start(new ProcessStartInfo(exePath, "\"" + assemblyPath2 + "\"")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
});
process.WaitForExit(10000);
return process.StandardOutput.ReadToEnd().Trim().Replace(assemblyPath2, "");
}
static string GetPathToPeVerify()
{
return ToolLocationHelper.GetPathToDotNetFrameworkFile("peverify.exe",TargetDotNetFrameworkVersion.VersionLatest);
}
static string TrimLineNumbers(string foo)
{
return Regex.Replace(foo, @"0x.*]", "");
}
} | mit | C# | |
42be54248c6dae3db5db95bcffd9ba3544a8c1fe | Move toseperate file | michael-reichenauer/GitMind | GitMind/Utils/FatalExceptionEventArgs.cs | GitMind/Utils/FatalExceptionEventArgs.cs | namespace System
{
internal class FatalExceptionEventArgs : EventArgs
{
public string Message { get; }
public Exception Exception { get; }
public FatalExceptionEventArgs(string message, Exception exception)
{
Message = message;
Exception = exception;
}
}
} | mit | C# | |
5e0ad58fd3f8765756e1f29676ca7937843437ca | Create Helper.cs | burnsba/Toolbox,burnsba/Toolbox,burnsba/Toolbox | csharp/Helper.cs | csharp/Helper.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Toolbox
{
public static class Helper
{
public static IEnumerable<T> DefaultRange<T>(int start, int count)
{
foreach (var x in Enumerable.Range(start, count))
{
yield return default(T);
}
}
}
}
| apache-2.0 | C# | |
fc203014af2d40d10fc816c145086533e108305c | Create IFunctional.cs | codecore/Functional,codecore/Functional | IFunctional.cs | IFunctional.cs | using System;
using System.IO;
using System.Collections.Generic;
namespace Functional.Contracts {
public delegate IEnumerable<string> GetStrings(StreamReader sr);
public interface IListener<T, U> { U Handle(T m); }
public interface ISomething<T> {
T Item { get; set; }
}
public interface ISomethingImmutable<T> {
T Item { get; }
}
public interface IDefault<T> {
T orDefault(T t);
}
public interface ICurry1<T, U> {
Func<T, U> Create();
}
public interface ICurry2<T, U> {
Func<U, U> Create(T t);
}
}
| apache-2.0 | C# | |
ab9c11c086f705787bbae1fcf43c49855001a6f2 | Create TollBooth.cs | Carlzilla/TollBooth-CS | TollBooth.cs | TollBooth.cs | using System;
using ICities;
using ColossalFramework;
using UnityEngine;
namespace TollBooth
{
public class TollBooth : IUserMod
{
public string Description
{
get
{
return "Adds the ability for toolbooth assets to collect money.";
}
}
public string Name
{
get
{
return "Working toll booths";
}
}
public TollBooth()
{
}
}
public class TollBoothAI : PlayerBuildingAI
{
private VehicleManager vehicleManager = Singleton<VehicleManager>.instance;
[CustomizableProperty("EntertainmentAccumulation")]
public int m_entertainmentAccumulation = -300;
[CustomizableProperty("EntertainmentRadius")]
public float m_entertainmentRadius = 400f;
[CustomizableProperty("UneducatedWorkers", "Workers")]
public int m_workPlaceCount0 = 3;
[CustomizableProperty("TollRate")]
public int m_tollRate = 16;
public TollBoothAI()
{
}
public override int GetMaintenanceCost()
{
int mFees = Convert.ToInt32(Math.Floor(this.vehicleManager.m_vehicleCount * 0.2 * m_tollRate * -1));
return mFees;
}
}
}
| mit | C# | |
7ae52b79a2e44a75ec443fa28022d979a8f38551 | Create 2014s3q4.cs | Mooophy/158212 | 2014s3q4.cs | 2014s3q4.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection.Emit;
namespace JuestForCshap
{
class Program
{
static string BmiSpan(float bmi)
{
if (bmi < 0)
return "BMI CALCULATION ERROR";
else if (bmi < 18.5)
return "UNDERWEIGHT";
else if (bmi >= 25 && bmi < 30)
return "OVERWEIGHT";
else
return "OBESE";
}
static float BmiGetInput(string msg)
{
float result = 0;
while (true)
{
Console.WriteLine(msg);
int i = 0;
if (int.TryParse(Console.ReadLine(), out i))
{
result = i;
break;
}
Console.WriteLine("Invalid input, please enter again\n");
}
return result;
}
static string BmiCalculate()
{
float height = Program.BmiGetInput("Enter a positive value for height in meters");
Console.WriteLine("The .....for height was: " + height);
float weight = Program.BmiGetInput("Enter a positive value for weight in meters");
Console.WriteLine("The .....for height was: " + weight);
float bmi = weight / (float)(Math.Pow((double)height, 2.0));
return Program.BmiSpan(bmi);
}
static void Main(string[] args)
{
}
}
}
| mit | C# | |
dbe1f77d00f5999b3d7ab3d3e4ee425ea625dcc1 | Create Customer.cs | dlidstrom/EventStoreLite | Customer.cs | Customer.cs | using System;
using System.IO;
using System.Linq;
namespace RavenEventStore
{
public class Customer : AggregateRoot<Customer>
{
private string name;
private bool hasChangedName;
private string previousName;
public Customer(string name)
{
if (name == null) throw new ArgumentNullException("name");
this.ApplyChange(new CustomerInitializedEvent(name));
}
// necessary for loading from event store
private Customer()
{
}
public void ChangeName(string newName)
{
if (newName == null) throw new ArgumentNullException("newName");
this.ApplyChange(new ChangeCustomerNameEvent(newName));
}
public void PrintName(TextWriter writer)
{
if (writer == null) throw new ArgumentNullException("writer");
var message = this.name;
if (this.hasChangedName)
message += string.Format(" (changed from {0})", previousName);
writer.WriteLine(message);
}
private void Apply(CustomerInitializedEvent e)
{
this.name = e.Name;
}
private void Apply(ChangeCustomerNameEvent e)
{
this.previousName = this.name;
this.name = e.NewName;
this.hasChangedName = true;
}
}
}
| mit | C# | |
d2b00749ef71729555d393da7fef1dcdb84f5cbc | Add missing DynamicTexture.cs file from last commit | rryk/omp-server,RavenB/opensim,rryk/omp-server,Michelle-Argus/ArribasimExtract,OpenSimian/opensimulator,BogusCurry/arribasim-dev,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,bravelittlescientist/opensim-performance,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-extras,TomDataworks/opensim,M-O-S-E-S/opensim,TomDataworks/opensim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,ft-/arribasim-dev-extras,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-extras,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,ft-/arribasim-dev-tests,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,justinccdev/opensim,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-tests,rryk/omp-server,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,justinccdev/opensim,rryk/omp-server,justinccdev/opensim,ft-/arribasim-dev-tests,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-extras,Michelle-Argus/ArribasimExtract,QuillLittlefeather/opensim-1,justinccdev/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-extras,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,bravelittlescientist/opensim-performance,bravelittlescientist/opensim-performance,justinccdev/opensim,TomDataworks/opensim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,rryk/omp-server,Michelle-Argus/ArribasimExtract,RavenB/opensim,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-tests,ft-/arribasim-dev-tests,TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,RavenB/opensim,justinccdev/opensim,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-tests,Michelle-Argus/ArribasimExtract,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip,RavenB/opensim,BogusCurry/arribasim-dev,TomDataworks/opensim,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-tests,M-O-S-E-S/opensim,M-O-S-E-S/opensim,bravelittlescientist/opensim-performance,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,M-O-S-E-S/opensim | OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTexture.cs | OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTexture.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 the OpenSimulator Project 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 DEVELOPERS ``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 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.
*/
using System;
using System.Drawing;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
{
public class DynamicTexture : IDynamicTexture
{
public string InputCommands { get; private set; }
public Uri InputUri { get; private set; }
public string InputParams { get; private set; }
public byte[] Data { get; private set; }
public Size Size { get; private set; }
public bool IsReuseable { get; private set; }
public DynamicTexture(string inputCommands, string inputParams, byte[] data, Size size, bool isReuseable)
{
InputCommands = inputCommands;
InputParams = inputParams;
Data = data;
Size = size;
IsReuseable = isReuseable;
}
public DynamicTexture(Uri inputUri, string inputParams, byte[] data, Size size, bool isReuseable)
{
InputUri = inputUri;
InputParams = inputParams;
Data = data;
Size = size;
IsReuseable = isReuseable;
}
}
} | bsd-3-clause | C# | |
d16b83ea40bf879d0351afa58217031b6552e788 | Add Guid-based constructor to FolioPaymentIndicator | PietroProperties/holms.platformclient.net | csharp/HOLMS.Platform/HOLMS.Platform/Types/Extensions/Folio/FolioPaymentIndicator.cs | csharp/HOLMS.Platform/HOLMS.Platform/Types/Extensions/Folio/FolioPaymentIndicator.cs | using System;
using HOLMS.Support.Conversions;
namespace HOLMS.Types.Folio {
public partial class FolioPaymentIndicator {
public FolioPaymentIndicator(Guid id) {
Id = id.ToUUID();
}
}
}
| mit | C# | |
2bcc4322254bbce37a9da0a2ddfc4bf8140c9026 | Create VariableGridCell.cs | quoxel/VariableGridLayoutGroup | VariableGridCell.cs | VariableGridCell.cs | using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("Layout/Variable Grid Layout Group Cell", 140)]
[RequireComponent(typeof(RectTransform))]
[ExecuteInEditMode]
public class VariableGridCell : UIBehaviour
{
[SerializeField]
private bool m_OverrideForceExpandWidth = false;
public virtual bool overrideForceExpandWidth {
get { return m_OverrideForceExpandWidth; }
set {
if (value != m_OverrideForceExpandWidth) {
m_OverrideForceExpandWidth = value;
SetDirty ();
}
}
}
[SerializeField]
private bool m_ForceExpandWidth = false;
public virtual bool forceExpandWidth {
get { return m_ForceExpandWidth; }
set {
if (value != m_ForceExpandWidth) {
m_ForceExpandWidth = value;
SetDirty ();
}
}
}
[SerializeField]
private bool m_OverrideForceExpandHeight = false;
public virtual bool overrideForceExpandHeight {
get { return m_OverrideForceExpandHeight; }
set {
if (value != m_OverrideForceExpandHeight) {
m_OverrideForceExpandHeight = value;
SetDirty ();
}
}
}
[SerializeField]
private bool m_ForceExpandHeight = false;
public virtual bool forceExpandHeight {
get { return m_ForceExpandHeight; }
set {
if (value != m_ForceExpandHeight) {
m_ForceExpandHeight = value;
SetDirty ();
}
}
}
[SerializeField]
private bool m_OverrideCellAlignment = false;
public virtual bool overrideCellAlignment {
get { return m_OverrideCellAlignment; }
set {
if (value != m_OverrideCellAlignment) {
m_OverrideCellAlignment = value;
SetDirty ();
}
}
}
[SerializeField]
private TextAnchor m_CellAlignment = TextAnchor.UpperLeft;
public virtual TextAnchor cellAlignment {
get { return m_CellAlignment; }
set {
if (value != m_CellAlignment) {
m_CellAlignment = value;
SetDirty ();
}
}
}
protected VariableGridCell()
{}
#region Unity Lifetime calls
protected override void OnEnable()
{
base.OnEnable();
SetDirty();
}
protected override void OnTransformParentChanged()
{
SetDirty();
}
protected override void OnDisable()
{
SetDirty();
base.OnDisable();
}
protected override void OnDidApplyAnimationProperties()
{
SetDirty();
}
protected override void OnBeforeTransformParentChanged()
{
SetDirty();
}
#endregion
protected void SetDirty()
{
if (!IsActive())
return;
LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform);
}
#if UNITY_EDITOR
protected override void OnValidate()
{
SetDirty();
}
#endif
}
}
| mit | C# | |
c172ae954a7786a15d19ebd63e3935faf64bc0d4 | add attached property to dragablz item | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Utilities/Extensions/DragablzHeaderExtensions.cs | TCC.Core/Utilities/Extensions/DragablzHeaderExtensions.cs | using System.Windows;
namespace TCC.Utilities.Extensions
{
public class DragablzHeaderExtensions
{
public static float GetFrameOpacity(DependencyObject obj)
{
return (float)obj.GetValue(FrameOpacityProperty);
}
public static void SetFrameOpacity(DependencyObject obj, float value)
{
obj.SetValue(FrameOpacityProperty, value);
}
public static readonly DependencyProperty FrameOpacityProperty =
DependencyProperty.RegisterAttached("FrameOpacity", typeof(float), typeof(DragablzHeaderExtensions), new PropertyMetadata(0f));
}
} | mit | C# | |
259eea6fff59aa095b7059edcffbab3b1eb90ccd | Create TournamentReward.cs | OpenConquer/Tournaments | Tournaments/TournamentReward.cs | Tournaments/TournamentReward.cs | using System;
using System.Collections.Generic;
using OpenConquer.Network.GamePackets;
namespace OpenConquer.Game.Models.Tournaments
{
/// <summary>
/// Model for a tournament reward.
/// </summary>
public sealed class TournamentReward
{
/// <summary>
/// Gets or sets the money.
/// </summary>
public uint Money { get; set; }
/// <summary>
/// Gets or sets the conquer points.
/// </summary>
public uint ConquerPoints { get; set; }
/// <summary>
/// Gets or sets the bound cps.
/// </summary>
public uint BoundCPs { get; set; }
/// <summary>
/// Gets a list of items.
/// </summary>
public List<ConquerItem> Items { get; private set; }
/// <summary>
/// Creates a new tournament reward.
/// </summary>
public TournamentReward()
{
Items = new List<ConquerItem>();
}
}
}
| mit | C# | |
4d67f2f9f63137218cdc9b20c293ae043751c866 | Add test coverage of nested game usage | ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework | osu.Framework.Tests/Visual/Testing/TestSceneNestedGame.cs | osu.Framework.Tests/Visual/Testing/TestSceneNestedGame.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 NUnit.Framework;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.Testing
{
public class TestSceneNestedGame : FrameworkTestScene
{
private bool hostWasRunningAfterNestedExit;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("reset host running", () => hostWasRunningAfterNestedExit = false);
}
[Test]
public void AddGameUsingStandardMethodThrows()
{
AddStep("Add game via add throws", () => Assert.Throws<InvalidOperationException>(() => Add(new TestGame())));
}
[Test]
public void TestNestedGame()
{
TestGame game = null;
AddStep("Add game", () => AddGame(game = new TestGame()));
AddStep("exit game", () => game.Exit());
AddUntilStep("game expired", () => game.Parent == null);
}
[TearDownSteps]
public void TearDownSteps()
{
AddStep("mark host running", () => hostWasRunningAfterNestedExit = true);
}
protected override void RunTests()
{
base.RunTests();
Assert.IsTrue(hostWasRunningAfterNestedExit);
}
}
}
| mit | C# | |
40c193a5e604610dccaee2e7089176fe775a7906 | Create Test2.cs | hueneburg/GitIncludeTest | dir1/dir2/dir1/Test2.cs | dir1/dir2/dir1/Test2.cs | This is a test
| bsd-3-clause | C# | |
44ea48638c9be1beda270e12c7950e0c0c79dc5a | Add Scroll rect by children component | insthync/unity-utilities | Assets/UnityUtilities/Scripts/Misc/ScrollRectByChildren.cs | Assets/UnityUtilities/Scripts/Misc/ScrollRectByChildren.cs | using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ScrollRectByChildren : MonoBehaviour,
IBeginDragHandler,
IDragHandler,
IEndDragHandler,
IScrollHandler
{
public ScrollRect scrollRect;
private void Awake()
{
if (scrollRect == null)
scrollRect = GetComponentInParent<ScrollRect>();
}
public void OnBeginDrag(PointerEventData eventData)
{
if (scrollRect != null)
scrollRect.OnBeginDrag(eventData);
}
public void OnDrag(PointerEventData eventData)
{
if (scrollRect != null)
scrollRect.OnDrag(eventData);
}
public void OnEndDrag(PointerEventData eventData)
{
if (scrollRect != null)
scrollRect.OnEndDrag(eventData);
}
public void OnScroll(PointerEventData data)
{
if (scrollRect != null)
scrollRect.OnScroll(data);
}
}
| mit | C# | |
206fc94b8c9e71be4dc3049003f63147bf735a22 | Add rotation drag handle component | UselessToucan/osu,smoogipooo/osu,ppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu | osu.Game/Screens/Edit/Compose/Components/SelectionBoxRotationHandle.cs | osu.Game/Screens/Edit/Compose/Components/SelectionBoxRotationHandle.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Edit.Compose.Components
{
public class SelectionBoxRotationHandle : SelectionBoxDragHandle
{
private SpriteIcon icon;
[BackgroundDependencyLoader]
private void load()
{
Size = new Vector2(15f);
AddInternal(icon = new SpriteIcon
{
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Icon = FontAwesome.Solid.Redo,
Scale = new Vector2
{
X = Anchor.HasFlagFast(Anchor.x0) ? 1f : -1f,
Y = Anchor.HasFlagFast(Anchor.y0) ? 1f : -1f
}
});
}
protected override void UpdateHoverState()
{
icon.Colour = !HandlingMouse && IsHovered ? Color4.White : Color4.Black;
base.UpdateHoverState();
}
}
}
| mit | C# | |
8f2f024f9ec577aba7775cabb4b8159a57adc527 | Create extensions.cs | Kartessian/JSON-Sharp,Kartessian/JSON-Sharp | extensions.cs | extensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace Kartessian
{
public static class extensions
{
public static string ToJson(this DataTable dt)
{
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(rows);
}
public static string ToJavaScriptArray(this DataTable dt)
{
List<object> rows = new List<object>();
foreach (DataRow dr in dt.Rows)
{
if (dt.Columns.Count > 1)
{
List<object> row = new List<object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(dr[col]);
}
rows.Add(row);
}
else
{
rows.Add(dr[0]);
}
}
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(rows);
}
}
}
| mit | C# | |
c1c2f79b550ece5086cc8d4d67ca160c6ea18278 | Add unit tests that that does not add much value yet | charlenni/Mapsui,charlenni/Mapsui | Tests/Mapsui.Tests/ViewportTests.cs | Tests/Mapsui.Tests/ViewportTests.cs | using NUnit.Framework;
namespace Mapsui.Tests
{
[TestFixture]
public class ViewportTests
{
[Test]
public void SetCenterTest()
{
// Arrange
var viewport = new Viewport();
// Act
viewport.SetCenter(10, 20);
// Assert
Assert.AreEqual(10, viewport.CenterX);
Assert.AreEqual(20, viewport.CenterY);
}
}
}
| mit | C# | |
5ae32651869dec53203d4d1eea7cc90e36cb7d90 | Add HTTPRequest module | mage/mage-sdk-unity,AlmirKadric/mage-sdk-unity | HTTPRequest/HTTPRequest.cs | HTTPRequest/HTTPRequest.cs | using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Text;
public class HTTPRequest {
public static void Get(string url, Dictionary<string, string> headers, Action<Exception, string> cb) {
// Initialize request instance
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = WebRequestMethods.Http.Get;
// Set request headers
if (headers != null) {
foreach (KeyValuePair<string, string> entry in headers) {
httpRequest.Headers.Add(entry.Key, entry.Value);
}
}
// Process the response
ReadResponseData(httpRequest, cb);
}
public static void Post(string url, string contentType, string postData, Dictionary<string, string> headers, Action<Exception, string> cb) {
byte[] binaryPostData = Encoding.UTF8.GetBytes(postData);
Post(url, contentType, binaryPostData, headers, cb);
}
public static void Post(string url, string contentType, byte[] postData, Dictionary<string, string> headers, Action<Exception, string> cb) {
// Initialize request instance
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = WebRequestMethods.Http.Post;
// Set content type if provided
if (contentType != null) {
httpRequest.ContentType = contentType;
}
// Set request headers
if (headers != null) {
foreach (KeyValuePair<string, string> entry in headers) {
httpRequest.Headers.Add(entry.Key, entry.Value);
}
}
// Make a connection and send the request
WritePostData (httpRequest, postData, (Exception requestError) => {
if (requestError != null) {
cb(requestError, null);
return;
}
// Process the response
ReadResponseData(httpRequest, cb);
});
}
private static void WritePostData (HttpWebRequest httpRequest, byte[] postData, Action<Exception> cb) {
httpRequest.BeginGetRequestStream ((IAsyncResult callbackResult) => {
try {
Stream postStream = httpRequest.EndGetRequestStream(callbackResult);
postStream.Write(postData, 0, postData.Length);
postStream.Close();
} catch (Exception error) {
cb(error);
return;
}
cb(null);
}, null);
}
private static void ReadResponseData (HttpWebRequest httpRequest, Action<Exception, string> cb) {
httpRequest.BeginGetResponse(new AsyncCallback((IAsyncResult callbackResult) => {
string responseString;
try {
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream())) {
responseString = httpWebStreamReader.ReadToEnd();
}
} catch (Exception error) {
cb(error, null);
return;
}
cb(null, responseString);
}), null);
}
}
| mit | C# | |
d0f7d7868a8cfe97957902fee538e875aff29258 | Create AssemblyInfo.cs | ClutchplateDude/xml-micro | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | ya
| mit | C# | |
fb657786562b1f8e6a1cc871ee2a33f9d1327e45 | Create mntp.cshtml | go4web/Umbraco-Snippets | mntp.cshtml | mntp.cshtml | @*
----- MNTP -----
*@
@if (homepage.HasProperty("headerNavigation")) {
<ul class="headerNavigation">
@foreach (var item in Umbraco.TypedContent(homepage.GetPropertyValue("headerNavigation").ToString().Split(','))) {
if (item != null)
{
<li><a href="@item.NiceUrl()">@Html.Raw(@item.GetPropertyValue("pageTitle"))</a></li>
}
}
</ul>
}
@*
----- MNTP - Slideshow -----
*@
@{
var meetUsNodeIds = Model.Content.GetPropertyValue("meetUsSlider", true).ToString().Split(',');
List<IPublishedContent> meetUsSlides = new List<IPublishedContent>();
foreach (var nodeId in meetUsNodeIds)
{
if (!String.IsNullOrEmpty(nodeId))
{
var publishedContent = Umbraco.NiceUrl(Convert.ToInt32(nodeId));
if (!String.IsNullOrEmpty(publishedContent) && publishedContent != "#")
{
meetUsSlides.Add(Umbraco.TypedContent(nodeId));
}
}
}
}
@foreach (var slide in meetUsSlides)
{
<div class="rsContent">
@if (@slide.GetPropertyValue("image") != string.Empty)
{
var mediaItem = Umbraco.Media(@slide.GetPropertyValue("image"));
<img class="rsImg" src="@(mediaItem.Url)" alt="@mediaItem.Name" />
}
<div class="infoBlock infoBlockText rsABlock" data-fade-effect="" data-move-offset="50" data-move-effect="bottom" data-speed="1500">
@foreach (var item in Umbraco.TypedContent(slide.GetPropertyValue("link").ToString().Split(',')))
{
if (item != null)
{
<h4><a href="@item.NiceUrl()" title="@item.Name">@Html.Raw(slide.GetPropertyValue("title"))</a></h4>
}
}
<p>@Html.Raw(slide.GetPropertyValue("text"))</p>
</div>
</div>
}
| mit | C# | |
4ca445c2204b3b78bbf8261ec1e13a1bfb0e558a | Add PropertyChangeTracker utility class. | ZhangLeiCharles/mobile,eatskolnikov/mobile,eatskolnikov/mobile,masterrr/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,masterrr/mobile,peeedge/mobile,peeedge/mobile | Phoebe/Data/Utils/PropertyChangeTracker.cs | Phoebe/Data/Utils/PropertyChangeTracker.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Toggl.Phoebe.Data.Utils
{
public sealed class PropertyChangeTracker : IDisposable
{
private readonly List<Listener> listeners = new List<Listener> ();
~PropertyChangeTracker ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
private void Dispose (bool disposing)
{
if (disposing) {
ClearAll ();
}
}
public void MarkAllStale ()
{
foreach (var listener in listeners) {
listener.Stale = true;
}
}
public void Add (INotifyPropertyChanged observable, Action<string> callback)
{
var listener = listeners.FirstOrDefault (l => l.Observable == observable);
if (listener == null) {
listener = new Listener (observable);
listeners.Add (listener);
}
listener.Callback = callback;
listener.Stale = false;
}
public void ClearAll ()
{
foreach (var listener in listeners) {
listener.Dispose ();
}
listeners.Clear ();
}
public void ClearStale ()
{
var stale = listeners.Where (l => l.Stale).ToList ();
listeners.RemoveAll (l => l.Stale);
foreach (var listener in stale) {
listener.Dispose ();
}
}
private sealed class Listener : IDisposable
{
private readonly INotifyPropertyChanged observable;
public Listener (INotifyPropertyChanged observable)
{
this.observable = observable;
observable.PropertyChanged += HandlePropertyChanged;
}
~Listener ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
private void Dispose (bool disposing)
{
if (disposing) {
observable.PropertyChanged -= HandlePropertyChanged;
Callback = null;
}
}
public INotifyPropertyChanged Observable {
get { return observable; }
}
public Action<string> Callback { get; set; }
public bool Stale { get; set; }
private void HandlePropertyChanged (object sender, PropertyChangedEventArgs e)
{
var cb = Callback;
if (cb != null) {
cb (e.PropertyName);
}
}
}
}
}
| bsd-3-clause | C# | |
2cddedb20cdff28fc96b12df1eb346ae7ee05cfc | Update Enum.cs | cnascimento/RestSharp,dgreenbean/RestSharp,RestSharp-resurrected/RestSharp,restsharp/RestSharp,benfo/RestSharp,kouweizhong/RestSharp,periface/RestSharp,eamonwoortman/RestSharp.Unity,jiangzm/RestSharp,KraigM/RestSharp,fmmendo/RestSharp,chengxiaole/RestSharp,dmgandini/RestSharp,huoxudong125/RestSharp,mattleibow/RestSharp,dyh333/RestSharp,haithemaraissia/RestSharp,wparad/RestSharp,wparad/RestSharp,mwereda/RestSharp,rucila/RestSharp,PKRoma/RestSharp,SaltyDH/RestSharp,lydonchandra/RestSharp,rivy/RestSharp,felipegtx/RestSharp,who/RestSharp,uQr/RestSharp,amccarter/RestSharp,mattwalden/RestSharp | RestSharp/Enum.cs | RestSharp/Enum.cs | #region License
// Copyright 2010 John Sheehan
//
// 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
namespace RestSharp
{
///<summary>
/// Types of parameters that can be added to requests
///</summary>
public enum ParameterType
{
Cookie,
GetOrPost,
UrlSegment,
HttpHeader,
RequestBody,
QueryString
}
/// <summary>
/// Data formats
/// </summary>
public enum DataFormat
{
Json,
Xml
}
/// <summary>
/// HTTP method to use when making requests
/// </summary>
public enum Method
{
GET,
POST,
PUT,
DELETE,
HEAD,
OPTIONS,
PATCH,
MERGE,
}
/// <summary>
/// Format strings for commonly-used date formats
/// </summary>
public struct DateFormat
{
/// <summary>
/// .NET format string for ISO 8601 date format
/// </summary>
public const string Iso8601 = "s";
/// <summary>
/// .NET format string for roundtrip date format
/// </summary>
public const string RoundTrip = "u";
}
/// <summary>
/// Status for responses (surprised?)
/// </summary>
public enum ResponseStatus
{
None,
Completed,
Error,
TimedOut,
Aborted
}
}
| #region License
// Copyright 2010 John Sheehan
//
// 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
namespace RestSharp
{
///<summary>
/// Types of parameters that can be added to requests
///</summary>
public enum ParameterType
{
Cookie,
GetOrPost,
UrlSegment,
HttpHeader,
RequestBody,
QueryString
}
/// <summary>
/// Data formats
/// </summary>
public enum DataFormat
{
Json,
Xml
}
/// <summary>
/// HTTP method to use when making requests
/// </summary>
public enum Method
{
GET,
POST,
PUT,
DELETE,
HEAD,
OPTIONS,
PATCH,
MERGE,
}
/// <summary>
/// Format strings for commonly-used date formats
/// </summary>
public struct DateFormat
{
/// <summary>
/// .NET format string for ISO 8601 date format
/// </summary>
public const string Iso8601 = "s";
/// <summary>
/// .NET format string for roundtrip date format
/// </summary>
public const string RoundTrip = "u";
}
/// <summary>
/// Status for responses (surprised?)
/// </summary>
public enum ResponseStatus
{
None,
Completed,
Error,
TimedOut,
Aborted
}
}
| apache-2.0 | C# |
fbddcd40dec59c4b8e3ea2a34eeda720a8b4e6b9 | Create TraceLog.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Modules/Log/Trace/TraceLog.cs | src/Core2D/Modules/Log/Trace/TraceLog.cs | #nullable enable
using System;
using Core2D.Model;
using SD = System.Diagnostics;
namespace Core2D.Modules.Log.Trace;
public sealed class TraceLog : ILog
{
// ReSharper disable once NotAccessedField.Local
private readonly IServiceProvider? _serviceProvider;
private const string InformationPrefix = "Information: ";
private const string WarningPrefix = "Warning: ";
private const string ErrorPrefix = "Error: ";
private string? _lastMessage;
private SD.TraceListener? _listener;
private System.IO.Stream? _stream;
public TraceLog(IServiceProvider? serviceProvider)
{
_serviceProvider = serviceProvider;
}
public string? LastMessage => _lastMessage;
private void SetLastMessage(string message) => _lastMessage = message;
public void Initialize(string path)
{
try
{
Close();
_stream = new System.IO.FileStream(path, System.IO.FileMode.Append);
_listener = new SD.TextWriterTraceListener(_stream, "listener");
SD.Trace.Listeners.Add(_listener);
}
catch (Exception ex)
{
SD.Debug.WriteLine(ex.Message);
SD.Debug.WriteLine(ex.StackTrace);
}
}
public void Close()
{
try
{
SD.Trace.Flush();
if (_listener is { })
{
_listener.Dispose();
_listener = null;
}
if (_stream is { })
{
_stream.Dispose();
_stream = null;
}
}
catch (Exception ex)
{
SD.Debug.WriteLine(ex.Message);
SD.Debug.WriteLine(ex.StackTrace);
}
}
public void LogInformation(string message)
{
SD.Trace.TraceInformation(message);
Console.WriteLine(message);
SetLastMessage(InformationPrefix + message);
}
public void LogInformation(string format, params object[] args)
{
SD.Trace.TraceInformation(format, args);
Console.WriteLine(format, args);
SetLastMessage(InformationPrefix + string.Format(format, args));
}
public void LogWarning(string message)
{
SD.Trace.TraceWarning(message);
Console.WriteLine(message);
SetLastMessage(WarningPrefix + message);
}
public void LogWarning(string format, params object[] args)
{
SD.Trace.TraceWarning(format, args);
Console.WriteLine(format, args);
SetLastMessage(WarningPrefix + string.Format(format, args));
}
public void LogError(string message)
{
SD.Trace.TraceError(message);
Console.WriteLine(message);
SetLastMessage(ErrorPrefix + message);
}
public void LogError(string format, params object[] args)
{
SD.Trace.TraceError(format, args);
Console.WriteLine(format, args);
SetLastMessage(ErrorPrefix + string.Format(format, args));
}
public void LogException(Exception ex)
{
LogError($"{ex.Message}{Environment.NewLine}{ex.StackTrace}");
if (ex.InnerException is { })
{
LogException(ex.InnerException);
}
}
public void Dispose()
{
Close();
}
}
| mit | C# | |
77bb5ea4cafd0c0764299900163f698e8865be47 | Add notification test | Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet | Tests/IntegrationTests.Shared/NotificationTests.cs | Tests/IntegrationTests.Shared/NotificationTests.cs | using System;
using NUnit.Framework;
using Realms;
using System.Threading;
namespace IntegrationTests.Shared
{
[TestFixture]
public class NotificationTests
{
private string _databasePath;
private Realm _realm;
private void WriteOnDifferentThread(Action<Realm> action)
{
var thread = new Thread(() =>
{
var r = Realm.GetInstance(_databasePath);
r.Write(() => action(r));
r.Close();
});
thread.Start();
thread.Join();
}
[Test]
public void SimpleTest()
{
// Arrange
// Act
}
}
}
| apache-2.0 | C# | |
4a71e12235583e540d041bf1c81692b35cd99c59 | add dropbox config parser | ayan4m1/shipsync,ayan4m1/shipsync | Container/Configuration/DropboxConfigModule.cs | Container/Configuration/DropboxConfigModule.cs | using System.IO;
using Autofac;
using log4net;
using Newtonsoft.Json;
namespace ShipSync.Container.Configuration
{
public class DropboxConfigModule : Module
{
private static readonly ILog Log = LogManager.GetLogger(typeof(DropboxConfigModule));
private readonly string _configPath;
public DropboxConfigModule(string configPath)
{
_configPath = configPath;
}
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
if (!File.Exists(_configPath))
{
var ex = new FileNotFoundException(_configPath);
Log.Error("Exception trying to load config", ex);
throw ex;
}
using (var reader = File.OpenText(_configPath))
{
Log.Debug("Attempting to deserialize JSON config");
var configObject = JsonConvert.DeserializeObject<DropboxConfig>(reader.ReadToEnd());
builder.Register(c => configObject);
}
}
}
} | mit | C# | |
4f47159729b2794f1211aa0f49b0f46c00b90765 | Create ArrayLine.cs | xxmon/unity | ArrayLine.cs | ArrayLine.cs | using UnityEngine;
using System.Collections;
using UnityEditor;
public class ArrayLine : MonoBehaviour {
public GameObject target;
public int numberToSpawn = 8;
public Vector3 space;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Reposition ()
{
for (int i = 0; i < transform.childCount; ++i) {
transform.GetChild (i).transform.localPosition = space*i;
}
}
public void SpawnChildren ()
{
if (target == null) {
return;
}
while (transform.childCount > 0) {
DestroyImmediate (transform.GetChild (0).gameObject);
}
for (int i = 0; i < numberToSpawn; ++i) {
GameObject clone;
clone = Instantiate (target, Vector3.zero, Quaternion.identity) as GameObject;
clone.transform.SetParent (gameObject.transform);
clone.name = i.ToString ();
}
}
void OnValidate ()
{
if (target == null) {
return;
}
if (numberToSpawn < 1) {
numberToSpawn = 1;
}
Reposition ();
}
}
[CustomEditor (typeof(ArrayLine))]
public class ArrayLineEditor : Editor
{
public override void OnInspectorGUI ()
{
DrawDefaultInspector ();
ArrayLine myScript = (ArrayLine)target;
if (GUILayout.Button ("Reset")) {
myScript.SpawnChildren ();
myScript.Reposition ();
}
}
}
| mit | C# | |
d589a7157ead62add73618a365ac73c8cb910657 | Set navigation bar translucent to false to fix views overlapping. Fix bug #14631 | nelzomal/monotouch-samples,albertoms/monotouch-samples,haithemaraissia/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,andypaul/monotouch-samples,W3SS/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,markradacz/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,a9upam/monotouch-samples,iFreedive/monotouch-samples,kingyond/monotouch-samples,peteryule/monotouch-samples,iFreedive/monotouch-samples,a9upam/monotouch-samples,YOTOV-LIMITED/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,kingyond/monotouch-samples,haithemaraissia/monotouch-samples,labdogg1003/monotouch-samples,andypaul/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,xamarin/monotouch-samples,peteryule/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,sakthivelnagarajan/monotouch-samples,hongnguyenpro/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,sakthivelnagarajan/monotouch-samples,markradacz/monotouch-samples,davidrynn/monotouch-samples,andypaul/monotouch-samples,labdogg1003/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,iFreedive/monotouch-samples,nervevau2/monotouch-samples,xamarin/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,labdogg1003/monotouch-samples,albertoms/monotouch-samples,hongnguyenpro/monotouch-samples,robinlaide/monotouch-samples,W3SS/monotouch-samples,albertoms/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,robinlaide/monotouch-samples | Rotation/HandlingRotation/AppDelegate.cs | Rotation/HandlingRotation/AppDelegate.cs | using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace HandlingRotation {
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate {
protected UIWindow window;
protected UINavigationController mainNavController;
protected HandlingRotation.Screens.iPhone.Home.HomeScreen iPhoneHome;
protected HandlingRotation.Screens.iPad.Home.HomeScreenPad iPadHome;
/// <summary>
/// The current device (iPad or iPhone)
/// </summary>
public DeviceType CurrentDevice { get; set; }
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create our window
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.MakeKeyAndVisible ();
// are we running an iPhone or an iPad?
DetermineCurrentDevice ();
// instantiate our main navigatin controller and add it's view to the window
mainNavController = new UINavigationController ();
mainNavController.NavigationBar.Translucent = false;
switch (CurrentDevice)
{
case DeviceType.iPhone:
iPhoneHome = new HandlingRotation.Screens.iPhone.Home.HomeScreen ();
mainNavController.PushViewController (iPhoneHome, false);
break;
case DeviceType.iPad:
iPadHome = new HandlingRotation.Screens.iPad.Home.HomeScreenPad ();
mainNavController.PushViewController (iPadHome, false);
break;
}
window.RootViewController = mainNavController;
return true;
}
protected void DetermineCurrentDevice ()
{
// figure out the current device type
if (UIScreen.MainScreen.Bounds.Height == 1024 || UIScreen.MainScreen.Bounds.Width == 1024) {
CurrentDevice = DeviceType.iPad;
} else {
CurrentDevice = DeviceType.iPhone;
}
}
}
} | using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace HandlingRotation {
[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate {
protected UIWindow window;
protected UINavigationController mainNavController;
protected HandlingRotation.Screens.iPhone.Home.HomeScreen iPhoneHome;
protected HandlingRotation.Screens.iPad.Home.HomeScreenPad iPadHome;
/// <summary>
/// The current device (iPad or iPhone)
/// </summary>
public DeviceType CurrentDevice { get; set; }
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create our window
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.MakeKeyAndVisible ();
// are we running an iPhone or an iPad?
DetermineCurrentDevice ();
// instantiate our main navigatin controller and add it's view to the window
mainNavController = new UINavigationController ();
switch (CurrentDevice)
{
case DeviceType.iPhone:
iPhoneHome = new HandlingRotation.Screens.iPhone.Home.HomeScreen ();
mainNavController.PushViewController (iPhoneHome, false);
break;
case DeviceType.iPad:
iPadHome = new HandlingRotation.Screens.iPad.Home.HomeScreenPad ();
mainNavController.PushViewController (iPadHome, false);
break;
}
window.RootViewController = mainNavController;
return true;
}
protected void DetermineCurrentDevice ()
{
// figure out the current device type
if (UIScreen.MainScreen.Bounds.Height == 1024 || UIScreen.MainScreen.Bounds.Width == 1024) {
CurrentDevice = DeviceType.iPad;
} else {
CurrentDevice = DeviceType.iPhone;
}
}
}
} | mit | C# |
4c8cd249cb88a96671d3010c133216f988ad8edd | Create Program.cs | AlexKoshulyan/NSDateToEpochTime | NSDateToEpochTime/Program.cs | NSDateToEpochTime/Program.cs | using System;
namespace NSDateToEpochTime
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length != 1)
{
throw new ArgumentException("One argument expected");
}
double nsTime = System.Convert.ToDouble(args[0]);
var dt = new DateTime(2001, 1, 1);
dt = dt.AddSeconds(nsTime);
Console.WriteLine(dt);
}
catch(Exception ex)
{
System.Console.Error.WriteLine(ex.Message);
System.Console.Error.WriteLine("\nSYNAPSIS: NSDateToEpochTime.exe value_to_convert\n");
}
}
}
}
| mit | C# | |
f8e3529a071fdb42e2acadbb3c06067be867c27e | Create Constants class. | VarLog/nano_magnetic.net | Nano/ClusterLib/Constants.cs | Nano/ClusterLib/Constants.cs | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Maxim Fedorenko <varlllog@gmail.com>
// Copyright (c) 2015 Roman Shershnev <LarscoRS@yandex.ru>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
namespace ClusterLib
{
static public class Constants
{
/// <summary>
/// The electron gyromagnetic ratio.
/// </summary>
public const double GyromagneticRatioE = 1.76e+7;
}
}
| mit | C# | |
beb39f2a33ecc64aa6e39bb0f61df8809bcea1b9 | change the version to 3.0.1 | RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,RachelTucker/ds3_net_sdk | VersionInfo.cs | VersionInfo.cs | /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.1.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
| /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
| apache-2.0 | C# |
2ac1bc3845e7e916a27efb335bd37ddb49ab4852 | Create R5Crypt64.cs | auycro/AESCrypt | R5Crypt64.cs | R5Crypt64.cs | using System;
using RGiesecke.DllExport;
namespace R5Crypt64
{
public class R5Crypt64
{
//static PDFManipulate pdfmanipulate = new PDFManipulate();
[DllExport("TestMethod")]
static int TestMethod(string input)
{
int result = 0;
if (input != null) { result = 100; };
if (input == "Hello") { result = 555; };
return result;
}
/*
[DllExport]
static int ConvertImageToPDF(string ImageFile,string OutputFileName){
int result = 0;
if (pdfmanipulate.ConvertImageToPdf(ImageFile, OutputFileName)) { result = 1;};
return result;
}
*/
#region R5CryptUtil
static AESCryptUtil aesCryptUtil;
//public string password;
[DllExport]
public static bool R5InitCryptConf(string password)
{
aesCryptUtil = new AESCryptUtil();
aesCryptUtil.SetPassword(password);
return true;
}
[DllExport]
public static bool R5FinalCryptConf()
{
aesCryptUtil = null;
return true;
}
[DllExport]
//public void R5CryptEncrypt(Boolean IsEof,Byte Buf,int DataSize,int BufSize){ }
public static bool R5CryptEncrypt(string PlainText, out string EncryptText)
{
EncryptText = aesCryptUtil.Encrypt(PlainText, aesCryptUtil.GetPassword());
return true;
}
[DllExport]
//public void R5CryptDecrypt(Boolean IsEof,Byte Buf,int DataSize) { }
public static bool R5CryptDecrypt(string CipherText, out string PlainText)
{
PlainText = aesCryptUtil.Decrypt(CipherText, aesCryptUtil.GetPassword());
return true;
}
#endregion
}
}
| mit | C# | |
c74b40339b3b892c63c145ef5442221b40b82a33 | Create HooksDone.cs | Notulp/Pluton,Notulp/Pluton | HooksDone.cs | HooksDone.cs | public static void Command(Player player, string[] args)
// called if Chat().arg.StartsWith("/");
public static void Chat(ConsoleSystem.Arg arg)
// called when chat.say is executed
public static void Gathering(BaseResource res, HitInfo info)
// called when you gather wood, stone, ores
public static void NPCHurt(BaseAnimal animal, HitInfo info)
// called when you hit an animal
public static void NPCDied(BaseAnimal animal, HitInfo info)
// called when you kill it
public static void PlayerConnected(Network.Connection connection)
// selfexplanatory
public static void PlayerDied(BasePlayer player, HitInfo info)
// same
public static void PlayerDisconnected(BasePlayer player)
// again
public static void PlayerHurt(BasePlayer player, HitInfo info)
// not tested, but should be hooked when a player(later animals as well, robots and giant ants) does some damage to another player
public static void PlayerTakeDamage(BasePlayer player, float dmgAmount, Rust.DamageType dmgType)
public static void PlayerTakeDamageOverload(BasePlayer player, float dmgAmount)
// falldmg , unknown
public static void PlayerTakeRadiation(BasePlayer player, float dmgAmount)
// guess it not used yet
public static void EntityAttacked(BuildingBlock bb, HitInfo info)
// hooked when hitting a BuildingBlock (built and frame) object
public static void EntityFrameDeployed(BuildingBlock bb)
// hooked when you put down a frame
public static void EntityBuildingUpdate(BuildingBlock bb, BasePlayer player, float proficiency)
// hooked as you progress with a building (when you hit it with hammer, even if it is built already)
public static void CorpseInit(BaseCorpse corpse, BaseEntity parent)
// when a player or an animal dies and a ragdoll is instantiated
public static void CorpseHit(BaseCorpse corpse, HitInfo info)
// when you hit a dead body
public static void StartLootingEntity(PlayerLoot playerLoot, BasePlayer looter, BaseEntity entity)
// selfexplanatory
public static void StartLootingPlayer(PlayerLoot playerLoot, BasePlayer looter, BasePlayer looted)
// selfexplanatory
public static void StartLootingItem(PlayerLoot playerLoot, BasePlayer looter, Item item)
// selfexplanatory
| mit | C# | |
f1b2d60812c7cece3f8fcea52160ffe6da058c2d | Test to verify compiled query error was addressed in v4 changes. Closes GH-784 | mysticmind/marten,JasperFx/Marten,mysticmind/marten,JasperFx/Marten,mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,JasperFx/Marten | src/Marten.Testing/Bugs/Bug_784_Collection_Contains_within_compiled_query.cs | src/Marten.Testing/Bugs/Bug_784_Collection_Contains_within_compiled_query.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Marten.Linq;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Bugs
{
public class Bug_784_Collection_Contains_within_compiled_query : IntegrationContext
{
private readonly ITestOutputHelper _output;
[Fact]
public void do_not_blow_up_with_exceptions()
{
var targets = Target.GenerateRandomData(100).ToArray();
targets[1].NumberArray = new[] {3, 4, 5};
targets[1].Flag = true;
targets[5].NumberArray = new[] {3, 4, 5};
targets[5].Flag = true;
targets[20].NumberArray = new[] {5, 6, 7};
targets[20].Flag = true;
theStore.BulkInsert(targets);
using (var query = theStore.QuerySession())
{
query.Logger = new TestOutputMartenLogger(_output);
var expected = targets.Where(x => x.Flag && x.NumberArray.Contains(5)).ToArray();
expected.Any(x => x.Id == targets[1].Id).ShouldBeTrue();
expected.Any(x => x.Id == targets[5].Id).ShouldBeTrue();
expected.Any(x => x.Id == targets[20].Id).ShouldBeTrue();
var actuals = query.Query(new FunnyTargetQuery{Number = 5}).ToArray();
actuals.OrderBy(x => x.Id).Select(x => x.Id)
.ShouldHaveTheSameElementsAs(expected.OrderBy(x => x.Id).Select(x => x.Id));
actuals.Any(x => x.Id == targets[1].Id).ShouldBeTrue();
actuals.Any(x => x.Id == targets[5].Id).ShouldBeTrue();
actuals.Any(x => x.Id == targets[20].Id).ShouldBeTrue();
}
}
public class FunnyTargetQuery : ICompiledListQuery<Target>
{
public Expression<Func<IMartenQueryable<Target>, IEnumerable<Target>>> QueryIs()
{
return q => q.Where(x => x.Flag && x.NumberArray.Contains(Number));
}
public int Number { get; set; }
}
public Bug_784_Collection_Contains_within_compiled_query(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture)
{
_output = output;
}
}
}
| mit | C# | |
418823bd86f5282e3508db223dd6ae6e70b467f4 | Create UserApi.cs | MingLu8/Nancy.WebApi.HelpPages | src/Nancy.WebApi.HelpPages.Demo/UserApi.cs | src/Nancy.WebApi.HelpPages.Demo/UserApi.cs | using System.Collections.Generic;
using Nancy.WebApi.AttributeRouting;
namespace Nancy.WebApi.Demo
{
/// <summary>
/// Web API for User.
/// </summary>
[RoutePrefix("api/userApi")]
public class UserApi : ApiController
{
/// <summary>
/// Gets all users.
/// </summary>
/// <returns></returns>
[HttpGet("/")]
public IEnumerable<User> GetAll()
{
return new List<User> { new User(), new User() };
}
/// <summary>
/// Get User by Id.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("/id/{id}")]
public User GetById(int id)
{
return new User();
}
/// <summary>
/// Get User by Name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[HttpGet("/name")]
public IEnumerable<User> GetByName(Name name)
{
return new List<User> { new User(), new User(), new User() };
}
/// <summary>
/// Modified User.
/// </summary>
/// <param name="id"></param>
/// <param name="user"></param>
/// <returns></returns>
[HttpPost("/{id}/{firstname}/{lastname}")]
public bool ChangeUser(int id, string firstname, string lastname)
{
return true;
}
/// <summary>
/// Add User.
/// </summary>
/// <param name="User"></param>
/// <returns></returns>
[HttpPut("/user")]
public int AddUser(User User)
{
return 1;
}
}
}
| mit | C# | |
873c1c11acc3f6e82c3f022eb959cc1aafd040c3 | Add XAmzHeaderNames | carbon/Amazon | src/Amazon.Core/Security/XAmzHeaderNames.cs | src/Amazon.Core/Security/XAmzHeaderNames.cs | namespace Amazon.Security;
internal static class XAmzHeaderNames
{
public const string ContentSHA256 = "x-amz-content-sha256";
public const string DecodedContentLength = "x-amz-decoded-content-length";
public const string ChecksumCrc32 = "x-amz-checksum-crc32";
public const string TrailerSignature = "x-amz-trailer-signature";
public const string Date = "x-amz-date";
public const string SecurityToken = "x-amz-security-token";
} | mit | C# | |
00b4f4d513b56721253d1573466c297e05f021b0 | add router that converts string url to resource url type | jensandresen/nappy | src/Nappy.Tests/TestRouter.cs | src/Nappy.Tests/TestRouter.cs | using System;
using Xunit;
namespace Nappy.Tests
{
public class TestRouter
{
[Theory]
[InlineData("foo", "1")]
[InlineData("foo", "2")]
[InlineData("bar", "1")]
[InlineData("bar", "2")]
public void returns_expected_when_extracting_resource_name_and_identifier_from_url(string expectedResourceName, string expectedResourceIdentifier)
{
var sut = new Router();
var result = sut.ConvertToResourceUrl($"/{expectedResourceName}/{expectedResourceIdentifier}");
Assert.Equal(expectedResourceName, result.Name);
Assert.Equal(expectedResourceIdentifier, result.Id);
}
[Theory]
[InlineData("foo")]
[InlineData("bar")]
public void returns_expected_when_extracting_resource_name_and_identifier_from_url_without_identifier(string expectedName)
{
var sut = new Router();
var result = sut.ConvertToResourceUrl($"/{expectedName}");
Assert.Equal(expectedName, result.Name);
Assert.Null(result.Id);
}
}
public class Router
{
public ResourceUrl ConvertToResourceUrl(string url)
{
var segments = url.Split('/', StringSplitOptions.RemoveEmptyEntries);
return new ResourceUrl
{
Name = segments.Length > 0 ? segments[0] : null,
Id = segments.Length > 1 ? segments[1] : null
};
}
}
public class ResourceUrl
{
public string Name { get; set; }
public string Id { get; set; }
}
} | mit | C# | |
99fdc7ea4cdff1845485918eecddc6af2ace7048 | Create fake-host.cs | axotion/Fake-Host | fake-host.cs | fake-host.cs | using System;
using System.IO;
using System.Security.Principal;
/* For example
* 127.0.0.1 google.com
* Where 127.0.0.1 is your server/whatever
* Also yo can run it with parametr xxx.xxx.xxx.xxx www.something.com
* */
class Var{
public static string IP = "127.0.0.1";
public static string Dest = "www.google.com";
};
class HostChanger
{
public static void Main (string[] args)
{
if (args.Length > 0) {
Var.IP = args [0];
Var.Dest = args[1];
}
bool isAdmin;
WindowsIdentity identity = WindowsIdentity.GetCurrent ();
WindowsPrincipal principal = new WindowsPrincipal (identity);
isAdmin = principal.IsInRole (WindowsBuiltInRole.Administrator);
if (isAdmin != false) {
File.SetAttributes ("c:\\windows\\system32\\drivers\\etc\\hosts", FileAttributes.Normal);
File.AppendAllText ("c:\\windows\\system32\\drivers\\etc\\hosts", Environment.NewLine + Var.IP+" "+Var.Dest+Environment.NewLine);
File.AppendAllText ("c:\\windows\\system32\\drivers\\etc\\hosts", Var.IP+" "+Var.Dest.Remove (0,4)+Environment.NewLine);
} else {
Console.WriteLine ("You must run it as admin");
}
}
}
| mit | C# | |
cfb93904fd8b1f59455055cc8c6df2a164049554 | Create anonymous_type.cs | kenpusney/pastebin,kenpusney/pastebin | book/anonymous_type.cs | book/anonymous_type.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace CLR_via_CS
{
class Program
{
static void Main(string[] args)
{
String myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var query =
from pathname in Directory.GetFiles(myDocuments)
let LastWriteTime = File.GetLastWriteTime(pathname)
where LastWriteTime > (DateTime.Now - TimeSpan.FromDays(7))
orderby LastWriteTime
select new {Path = pathname, LastWriteTime};
foreach (var file in query)
Console.WriteLine("{0},{1}",file.LastWriteTime,file.Path);
Console.Read();
}
}
}
| mit | C# | |
f9feb28f4a0687c71c39db40fb94ecb55cf22668 | Create EventStore.cs | dlidstrom/EventStoreLite | EventStore.cs | EventStore.cs | using System;
using System.Collections.Generic;
using Raven.Client;
namespace RavenEventStore
{
public class EventStore : IDisposable
{
private readonly ISet<IAggregate> unitOfWork
= new HashSet<IAggregate>(ObjectReferenceEqualityComparer<object>.Default);
private readonly IDocumentSession session;
public EventStore(IDocumentSession session)
{
if (session == null) throw new ArgumentNullException("session");
this.session = session;
}
public TAggregate Load<TAggregate>(ValueType id) where TAggregate : AggregateRoot<TAggregate>
{
var instance = this.session.Load<TAggregate>(id);
if (instance != null)
instance.LoadFromHistory();
return instance;
}
public void Store<TAggregate>(AggregateRoot<TAggregate> aggregate) where TAggregate : class
{
this.unitOfWork.Add(aggregate);
this.session.Store(aggregate);
}
public void Dispose()
{
this.session.Dispose();
}
public void SaveChanges()
{
foreach (var aggregate in this.unitOfWork)
{
foreach (var pendingEvent in aggregate.GetUncommittedChanges())
{
if (string.IsNullOrEmpty(pendingEvent.AggregateId))
pendingEvent.AggregateId = aggregate.Id;
pendingEvent.TimeStamp = DateTimeOffset.Now;
}
aggregate.MarkChangesAsCommitted();
}
this.session.SaveChanges();
this.unitOfWork.Clear();
}
}
}
| mit | C# | |
476331bb47959eea044bd5036c0b1597bd75927c | Create Cam.cs | etormadiv/njRAT_0.7d_Stub_ReverseEngineering | j_csharp/OK/Cam.cs | j_csharp/OK/Cam.cs | //Reversed by Etor Madiv
public static bool Cam()
{
try
{
string captureDriverName = Microsoft.VisualBasic.Strings.Space(100);
string captureDriverDescription = null;
return capGetDriverDescriptionA( 0, ref captureDriverName, 100, ref captureDriverDescription, 100);
}
catch(Exception)
{
}
return false;
}
| unlicense | C# | |
bc9216b7de267aa62eedf89322bd160c4dfffd70 | add missing file | ZanyGnu/GitRepoStats | RepoStats/Startup.cs | RepoStats/Startup.cs |
namespace RepoStats
{
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Owin;
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Remap '/' to '.\defaults\'.
// Turns on static files and default files.
app.UseFileServer(new FileServerOptions()
{
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(@".\"),
});
// Only serve files requested by name.
app.UseStaticFiles("/commitsByAuthor");
// Turns on static files, directory browsing, and default files.
app.UseFileServer(new FileServerOptions()
{
RequestPath = new PathString("/commitsByAuthor"),
EnableDirectoryBrowsing = true,
});
// Browse the root of your application (but do not serve the files).
// NOTE: Avoid serving static files from the root of your application or bin folder,
// it allows people to download your application binaries, config files, etc..
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
RequestPath = new PathString("/src"),
FileSystem = new PhysicalFileSystem(@""),
});
}
}
}
| mit | C# | |
b0f03d60bb561e6ecca9d07e14f6d46d9dfe4fc2 | Create index.cshtml | Aleksandrovskaya/apmathclouddif | index.cshtml | index.cshtml | @{
var txt = DateTime.Now;
}
<html>
<body>
<p>The dateTime is @txt</p>
</body>
</html>
| mit | C# | |
380bb047d38d011a8d95f6940c168f38bc9e5020 | Add AspectCore.Lite.Abstractions/ITargetServiceProvider.cs | AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite | src/AspectCore.Lite.Abstractions/ITargetServiceProvider.cs | src/AspectCore.Lite.Abstractions/ITargetServiceProvider.cs | using System;
namespace AspectCore.Lite.Abstractions
{
[NonAspect]
public interface ITargetServiceProvider
{
object GetTarget(Type serviceType);
}
}
| mit | C# | |
09d3b0449a142f12668477a321e50dc73e84e99e | Add history endpoint | mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype | src/Glimpse.Server.Web/Broker/HttpClientChannelResource.cs | src/Glimpse.Server.Web/Broker/HttpClientChannelResource.cs | using Glimpse.Web;
using System;
using System.Text;
using System.Threading.Tasks;
namespace Glimpse.Server
{
public class HttpClientChannelResource : IRequestHandler
{
public bool WillHandle(IHttpContext context)
{
return context.Request.Path == "/Glimpse/Data/History";
}
public async Task Handle(IHttpContext context)
{
var response = context.Response;
response.SetHeader("Content-Type", "application/json");
var content = new StringBuilder();
content.Append("[");
content.Append("{\"Type\":\"Glimpse.Agent.Web.BeginRequestMessage\",\"Payload\":\"{\\\"uri\\\":\\\"http://localhost:15999/\\\",\\\"id\\\":\\\"eb84b12a-a8a0-4409-a3e1-f933c6a6178a\\\",\\\"time\\\":\\\"2015-01-28T15:34:17.8300565-08:00\\\",\\\"timeLong\\\":635580560578300565}\",\"Context\":{\"Id\":\"9bd1a331-6ce6-49fe-8230-dc1398c58951\",\"Type\":\"Request\"}},");
content.Append("{\"Type\":\"Glimpse.Agent.Web.EndRequestMessage\",\"Payload\":\"{\\\"uri\\\":\\\"http://localhost:15999/\\\",\\\"id\\\":\\\"455fca26-e3a2-4325-8616-33bc1e557ee9\\\",\\\"time\\\":\\\"2015-01-28T15:34:17.8300565-08:00\\\",\\\"timeLong\\\":635580560578300565}\",\"Context\":{\"Id\":\"9bd1a331-6ce6-49fe-8230-dc1398c58951\",\"Type\":\"Request\"}},");
content.Append("{\"Type\":\"browser.rum\",\"Payload\":\"{\\\"loadEventEnd\\\":1422488057999,\\\"loadEventStart\\\":1422488057994,\\\"domComplete\\\":1422488057994,\\\"domContentLoadedEventEnd\\\":1422488057974,\\\"domContentLoadedEventStart\\\":1422488057973,\\\"domInteractive\\\":1422488057973,\\\"domLoading\\\":1422488057857,\\\"responseEnd\\\":1422488057831,\\\"responseStart\\\":1422488057831,\\\"requestStart\\\":1422488057826,\\\"secureConnectionStart\\\":0,\\\"connectEnd\\\":1422488057823,\\\"connectStart\\\":1422488057823,\\\"domainLookupEnd\\\":1422488057823,\\\"domainLookupStart\\\":1422488057823,\\\"fetchStart\\\":1422488057823,\\\"redirectEnd\\\":0,\\\"redirectStart\\\":0,\\\"unloadEventEnd\\\":1422488057852,\\\"unloadEventStart\\\":1422488057833,\\\"navigationStart\\\":1422488057823,\\\"id\\\":\\\"e3599391-639a-4809-b7d3-10b286f59d3e\\\",\\\"time\\\":\\\"2015-01-28T23:34:18.102Z\\\",\\\"uri\\\":\\\"http://localhost:15999/\\\"}\",\"Context\":{\"Id\":\"9bd1a331-6ce6-49fe-8230-dc1398c58951\",\"Type\":\"Request\"}}");
content.Append("]");
var data = Encoding.UTF8.GetBytes(content.ToString());
await response.WriteAsync(data);
}
}
} | mit | C# | |
99da5e3dee577d0613373263a5da285a28bf2d3c | Create test4.cs | neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers,neetsdkasu/Paiza-POH-MyAnswers | POH6plus/test4.cs | POH6plus/test4.cs | using System;
class H
{
static byte[] b=new byte[20000];
static int i,j,h,k,n=0,x,l=0,m,c=0,s,t;
static int[] p,q;
static int[][] z;
static System.IO.Stream o=Console.OpenStandardOutput();
static int cmp(int u,int v)
{
if (b[u]==b[v])
if (b[u]=='\n')
return 0;
else
return cmp(u+1,v+1);
else
return b[u]-b[v];
}
static int rev(int u,int v)
{
if (b[u]==b[v])
if (b[u]=='\n')
return 1;
else
return rev(u+1,v-1);
else
return 0;
}
static void pnt(int u)
{
while(b[u]!='\n')
o.WriteByte(b[u++]);
}
static void srt(int[] u,int v)
{
for(s=1;s<=v;s++)
{
m=s;
for(t=s+1;t<=v;t++)
if(cmp(u[m],u[t])>0)
m=t;
t=u[m];
u[m]=u[s];
u[s]=t;
}
}
public static void Main()
{
h=Console.OpenStandardInput().Read(b,0,20000);
b[h]=(byte)'\n';
for(k=0;b[k]!='\n';k++)
n=n*10+(b[k]-'0');
x=++k;
while(b[k++]!='\n')l++;
m=l+1;
p=new int[n];
q=new int[n];
for(i=0;i<n;i++)p[i]=x+m*i;
if (n==6)
Console.Write("fdkjnvqaqvnjkdf");
else if(n<9)
for(i=0;i<n;i++)pnt(x);
else
{
z=new int[27][];
for(i=0;i<n;i++)
q[b[p[i]]-'a']++;
for(i=0;i<27;i++)
if (q[i]>0)
z[i]=new int[q[i]+1];
for(i=0;i<n;i++)
{
j=b[p[i]]-'a';
z[j][++z[j][0]]=p[i];
}
k=0;
for(i=0;i<27;i++)
if(q[i]>0)
{
srt(z[i],q[i]);
for(j=1;j<=q[i];j++)
p[k++]=z[i][j];
}
m=l-1;
for(i=0;i<n;i++)
if(p[i]>0)
for(j=i+1;j<n;j++)
if(p[j]>0 && rev(p[i],p[j]+m)==1)
{
q[c++]=p[j];
pnt(p[i]);
p[j]=0;
j=n;
}
while(c-->0)
pnt(q[c]);
}
}
}
| mit | C# | |
49151a1f3b0cc18c62ae1c17b2028102848a19bc | make DxfWipeout easier to instantiate correctly | IxMilia/Dxf,IxMilia/Dxf | src/IxMilia.Dxf/Entities/DxfWipeout.cs | src/IxMilia.Dxf/Entities/DxfWipeout.cs | // Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace IxMilia.Dxf.Entities
{
public partial class DxfWipeout
{
/// <param name="imagePath">The path to the image.</param>
/// <param name="location">The bottom left corner of the location to display the image in the drawing.</param>
/// <param name="imageWidth">The width of the image in pixels.</param>
/// <param name="imageHeight">The height of the image in pixels.</param>
/// <param name="displaySize">The display size of the image in drawing units.</param>
public DxfWipeout(string imagePath, DxfPoint location, int imageWidth, int imageHeight, DxfVector displaySize)
: base(imagePath, location, imageWidth, imageHeight, displaySize)
{
}
}
}
| apache-2.0 | C# | |
ee1e16d28767011aae20dae99f7a4b861d4b8681 | Verify that an exception is thrown when more than one type matches | appharbor/appharbor-cli | src/AppHarbor.Tests/TypeNameMatcherTest.cs | src/AppHarbor.Tests/TypeNameMatcherTest.cs | using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class TypeNameMatcherTest
{
interface IFoo
{
}
class Foo : IFoo { }
private static Type FooType = typeof(Foo);
[Fact]
public void ShouldThrowIfInitializedWithUnnasignableType()
{
var exception = Assert.Throws<ArgumentException>(() => new TypeNameMatcher<IFoo>(new List<Type> { typeof(string) }));
}
[Theory]
[InlineData("Foo")]
[InlineData("foo")]
public void ShouldGetTypeStartingWithCommandName(string commandName)
{
var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType });
Assert.Equal(FooType, matcher.GetMatchedType(commandName));
}
[Theory]
[InlineData("Foo")]
public void ShouldThrowWhenMoreThanOneTypeMatches(string commandName)
{
var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType, FooType });
Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName));
}
[Theory]
[InlineData("Bar")]
public void ShouldThrowWhenNoTypesMatches(string commandName)
{
var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType });
Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName));
}
}
}
| using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class TypeNameMatcherTest
{
interface IFoo
{
}
class Foo : IFoo { }
private static Type FooType = typeof(Foo);
[Fact]
public void ShouldThrowIfInitializedWithUnnasignableType()
{
var exception = Assert.Throws<ArgumentException>(() => new TypeNameMatcher<IFoo>(new List<Type> { typeof(string) }));
}
[Theory]
[InlineData("Foo")]
[InlineData("foo")]
public void ShouldGetTypeStartingWithCommandName(string commandName)
{
var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType });
Assert.Equal(FooType, matcher.GetMatchedType(commandName));
}
[Theory]
[InlineData("Bar")]
public void ShouldThrowWhenNoTypesMatches(string commandName)
{
var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType });
Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName));
}
}
}
| mit | C# |
f6b48e68e68a4dd29c2be9ed58da88a1342bda54 | Create application lock file | TechGuard/background-changer | src/AppLock.cs | src/AppLock.cs | using System;
using System.IO;
namespace BackgroundChanger
{
class AppLock : IDisposable
{
public static readonly string LockFile = Path.Combine(Config.ApplicationFolder, ".locked");
/// <summary>
/// Check if lock file exists
/// </summary>
public static bool Check()
{
return File.Exists(LockFile);
}
/// <summary>
/// Create lock file
/// </summary>
public AppLock()
{
if (Check())
{
throw new ApplicationException("Already running");
}
// Create directory
if (!Directory.Exists(Config.ApplicationFolder))
{
Directory.CreateDirectory(Config.ApplicationFolder);
}
// Create lock file
File.Create(LockFile);
File.SetAttributes(LockFile, FileAttributes.Hidden | FileAttributes.ReadOnly);
}
/// <summary>
/// Destroy lock file
/// </summary>
public void Dispose()
{
File.Delete(LockFile);
}
}
}
| mit | C# | |
3285b8f0e868daa80a2aef5542d5e4a7f930a65f | Make member non-static | picklesdoc/pickles,dirkrombauts/pickles,magicmonty/pickles,picklesdoc/pickles,magicmonty/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,magicmonty/pickles,magicmonty/pickles,dirkrombauts/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles | src/Pickles/Pickles.TestFrameworks/XUnit/XUnit1/XUnit1SingleResultLoader.cs | src/Pickles/Pickles.TestFrameworks/XUnit/XUnit1/XUnit1SingleResultLoader.cs | using System;
using System.IO.Abstractions;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.XUnit.XUnit1
{
public class XUnit1SingleResultLoader : ISingleResultLoader
{
private readonly XDocumentLoader documentLoader = new XDocumentLoader();
public ITestResults Load(FileInfoBase fileInfo)
{
return new XUnit1SingleResult(this.documentLoader.Load(fileInfo));
}
}
} | using System;
using System.IO.Abstractions;
using PicklesDoc.Pickles.ObjectModel;
namespace PicklesDoc.Pickles.TestFrameworks.XUnit.XUnit1
{
public class XUnit1SingleResultLoader : ISingleResultLoader
{
private static readonly XDocumentLoader DocumentLoader = new XDocumentLoader();
public ITestResults Load(FileInfoBase fileInfo)
{
return new XUnit1SingleResult(DocumentLoader.Load(fileInfo));
}
}
} | apache-2.0 | C# |
94f7f6fe22e4284e18c44c549c952dd563cceb59 | Rebase finalisation | binaryjanitor/allReady,BillWagner/allReady,arst/allReady,mgmccarthy/allReady,arst/allReady,c0g1t8/allReady,c0g1t8/allReady,jonatwabash/allReady,arst/allReady,BillWagner/allReady,gitChuckD/allReady,bcbeatty/allReady,VishalMadhvani/allReady,GProulx/allReady,anobleperson/allReady,VishalMadhvani/allReady,MisterJames/allReady,binaryjanitor/allReady,mgmccarthy/allReady,binaryjanitor/allReady,mgmccarthy/allReady,anobleperson/allReady,anobleperson/allReady,stevejgordon/allReady,mgmccarthy/allReady,GProulx/allReady,gitChuckD/allReady,VishalMadhvani/allReady,HamidMosalla/allReady,bcbeatty/allReady,HTBox/allReady,MisterJames/allReady,c0g1t8/allReady,HTBox/allReady,stevejgordon/allReady,HamidMosalla/allReady,GProulx/allReady,MisterJames/allReady,VishalMadhvani/allReady,BillWagner/allReady,HTBox/allReady,jonatwabash/allReady,gitChuckD/allReady,c0g1t8/allReady,dpaquette/allReady,dpaquette/allReady,stevejgordon/allReady,MisterJames/allReady,jonatwabash/allReady,bcbeatty/allReady,stevejgordon/allReady,HTBox/allReady,dpaquette/allReady,HamidMosalla/allReady,arst/allReady,binaryjanitor/allReady,HamidMosalla/allReady,GProulx/allReady,bcbeatty/allReady,BillWagner/allReady,gitChuckD/allReady,anobleperson/allReady,dpaquette/allReady,jonatwabash/allReady | AllReadyApp/Web-App/AllReady/Services/Mapping/Routing/OptimizeRouteStatus.cs | AllReadyApp/Web-App/AllReady/Services/Mapping/Routing/OptimizeRouteStatus.cs | namespace AllReady.Services.Mapping.Routing
{
public class OptimizeRouteResultStatus
{
public bool IsSuccess { get; set; } = true;
public string StatusMessage { get; set; }
}
}
| mit | C# | |
50272f34d6ef5977264085e6d2a66d2d45b0be92 | add GetHostWithSchema extension | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Web/RequestExtensions.cs | src/Tugberk.Web/RequestExtensions.cs | using Microsoft.AspNetCore.Http;
namespace Tugberk.Web
{
public static class RequestExtensions
{
public static string GetHostWithSchema(this HttpRequest request)
{
var schema = request.IsHttps ? "https" : "http";
return $"{schema}://{request.Host.Value}".TrimEnd('/');
}
}
}
| agpl-3.0 | C# | |
4c9c65856ca117dd34122e4987c3c0570902d077 | Remove the nullable disable annotation in the testing beatmap and mark some of the properties as nullable. | peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu | osu.Game/Tests/Beatmaps/TestWorkingBeatmap.cs | osu.Game/Tests/Beatmaps/TestWorkingBeatmap.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.IO;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Textures;
using osu.Game.Beatmaps;
using osu.Game.Skinning;
using osu.Game.Storyboards;
namespace osu.Game.Tests.Beatmaps
{
public class TestWorkingBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
private readonly Storyboard? storyboard;
/// <summary>
/// Create an instance which provides the <see cref="IBeatmap"/> when requested.
/// </summary>
/// <param name="beatmap">The beatmap.</param>
/// <param name="storyboard">An optional storyboard.</param>
/// <param name="audioManager">The <see cref="AudioManager"/>.</param>
public TestWorkingBeatmap(IBeatmap beatmap, Storyboard? storyboard = null, AudioManager? audioManager = null)
: base(beatmap.BeatmapInfo, audioManager)
{
this.beatmap = beatmap;
this.storyboard = storyboard;
}
public override bool BeatmapLoaded => true;
protected override IBeatmap GetBeatmap() => beatmap;
protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard();
protected internal override ISkin? GetSkin() => null;
public override Stream? GetStream(string storagePath) => null;
protected override Texture? GetBackground() => null;
protected override Track? GetBeatmapTrack() => null;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.IO;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Textures;
using osu.Game.Beatmaps;
using osu.Game.Skinning;
using osu.Game.Storyboards;
namespace osu.Game.Tests.Beatmaps
{
public class TestWorkingBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
private readonly Storyboard storyboard;
/// <summary>
/// Create an instance which provides the <see cref="IBeatmap"/> when requested.
/// </summary>
/// <param name="beatmap">The beatmap.</param>
/// <param name="storyboard">An optional storyboard.</param>
/// <param name="audioManager">The <see cref="AudioManager"/>.</param>
public TestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null, AudioManager audioManager = null)
: base(beatmap.BeatmapInfo, audioManager)
{
this.beatmap = beatmap;
this.storyboard = storyboard;
}
public override bool BeatmapLoaded => true;
protected override IBeatmap GetBeatmap() => beatmap;
protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard();
protected internal override ISkin GetSkin() => null;
public override Stream GetStream(string storagePath) => null;
protected override Texture GetBackground() => null;
protected override Track GetBeatmapTrack() => null;
}
}
| mit | C# |
9ed6c360da737f091b39c4ad38dd8165f9d6cbcc | add a sql helper so we can use almost straight sql to query db | YoloDev/elephanet,YoloDev/elephanet,jmkelly/elephanet,jmkelly/elephanet | Elephanet/Sql.cs | Elephanet/Sql.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Npgsql;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
namespace Elephanet
{
public class Sql<T>
{
private NpgsqlCommand _command;
public Sql(string query, object[] parameters)
{
_command = new NpgsqlCommand();
_command.CommandText = String.Format(@"SELECT body FROM public.{0}_{1} WHERE body @> {2}", typeof(T).Namespace.ReplaceDotWithUnderscore(), typeof(T).Name, query);
foreach (var entry in MatchParameters(query, parameters))
{
string json = ConvertKeyValueToJson(entry);
_command.Parameters.Add(new NpgsqlParameter(entry.Key,json));
}
}
private string ConvertKeyValueToJson(KeyValuePair<string, object> entry)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
return string.Format("{{\"{0}\":\"{1}\"}}", textInfo.ToTitleCase(entry.Key.Substring(1)), entry.Value);
}
private Dictionary<string, object> MatchParameters(string query, object[] parameters)
{
var matches = new Dictionary<string, object>();
int counter = 0;
foreach (Match match in Regex.Matches(query,(@"(?<!\w):\w+")))
{
matches.Add(match.Value,parameters[counter]);
counter = counter + 1;
}
return matches;
}
public NpgsqlCommand Command { get { return _command; } }
}
public class Sql
{
private NpgsqlCommand _command;
public Sql(string query, object[] parameters)
{
_command = new NpgsqlCommand();
_command.CommandText = query;
foreach (var entry in MatchParameters(query, parameters))
{
_command.Parameters.Add(new NpgsqlParameter(entry.Key,entry.Value));
// do something with entry.Value or entry.Key
}
Console.WriteLine(_command.CommandText);
}
private Dictionary<string, object> MatchParameters(string query, object[] parameters)
{
var matches = new Dictionary<string, object>();
int counter = 0;
foreach (Match match in Regex.Matches(query,(@"(?<!\w):\w+")))
{
matches.Add(match.Value,parameters[counter]);
counter = counter + 1;
}
return matches;
}
public NpgsqlCommand Command { get { return _command; } }
}
}
| mit | C# | |
e7a26fea1bb3f01f70d7b91859ee2ae1747530e4 | Create World.cs | benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection,benharold/hello-world-collection | csharp/World.cs | csharp/World.cs | using System;
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
| mit | C# | |
d279776613aeddec6d137e44e776e90a7016518b | bump version | ColinDabritzViewpoint/Fody,huoxudong125/Fody,Fody/Fody,ichengzi/Fody,furesoft/Fody,jasonholloway/Fody,GeertvanHorrik/Fody,distantcam/Fody | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("1.29.0")]
[assembly: AssemblyFileVersion("1.29.0")] | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("1.28.3")]
[assembly: AssemblyFileVersion("1.28.3")] | mit | C# |
4712769b42a749fae5e5d77adbd6e653490c7b2c | fix datetime localization formatting | haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,xamarin/monotouch-samples,albertoms/monotouch-samples,haithemaraissia/monotouch-samples,a9upam/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,andypaul/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,a9upam/monotouch-samples,robinlaide/monotouch-samples,nelzomal/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,iFreedive/monotouch-samples,iFreedive/monotouch-samples,hongnguyenpro/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,a9upam/monotouch-samples,W3SS/monotouch-samples,sakthivelnagarajan/monotouch-samples,markradacz/monotouch-samples,robinlaide/monotouch-samples,hongnguyenpro/monotouch-samples,hongnguyenpro/monotouch-samples,haithemaraissia/monotouch-samples,albertoms/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nervevau2/monotouch-samples,hongnguyenpro/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,albertoms/monotouch-samples,andypaul/monotouch-samples,davidrynn/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,kingyond/monotouch-samples,sakthivelnagarajan/monotouch-samples,andypaul/monotouch-samples,markradacz/monotouch-samples,peteryule/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,a9upam/monotouch-samples,andypaul/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,iFreedive/monotouch-samples | WatchKit/WatchLocalization/WatchL10n_iOSWatchKitExtension/DetailController.cs | WatchKit/WatchLocalization/WatchL10n_iOSWatchKitExtension/DetailController.cs | using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace WatchL10n_iOSWatchKitExtension
{
partial class DetailController : WatchKit.WKInterfaceController
{
public DetailController (IntPtr handle) : base (handle)
{
}
public override void WillActivate ()
{
base.WillActivate ();
var hour = DateTime.Now.Hour;
var display = "zzzz";
if (hour < 6) {
// zzz
} else if (hour < 10) {
display = "Breakfast time";
} else if (hour < 16) {
display = "Lunch time";
} else if (hour < 21) {
display = "Dinner time";
} else if (hour < 23) {
display = "Bed time";
}
var localizedDisplay = NSBundle.MainBundle.LocalizedString (display, comment:"greeting");
displayText.SetText (localizedDisplay);
// "language@2x.png" is located in the Watch Extension
// multiple times: once for each language .lproj directory
using (var image = UIImage.FromBundle ("language")) {
displayImage.SetImage (image);
}
// easiest way to format date and/or time
var localizedDateTime = NSDateFormatter.ToLocalizedString
(NSDate.Now, NSDateFormatterStyle.Long, NSDateFormatterStyle.Short);
displayTime.SetText (localizedDateTime);
// long way of date or time formatting
// var formatter = new NSDateFormatter ();
// formatter.DateStyle = NSDateFormatterStyle.Medium;
// formatter.TimeStyle = NSDateFormatterStyle.Long;
// formatter.Locale = NSLocale.CurrentLocale;
// var localizedDateTime = formatter.StringFor (NSDate.Now);
}
}
}
| using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace WatchL10n_iOSWatchKitExtension
{
partial class DetailController : WatchKit.WKInterfaceController
{
public DetailController (IntPtr handle) : base (handle)
{
}
public override void WillActivate ()
{
base.WillActivate ();
var hour = DateTime.Now.Hour;
var display = "zzzz";
if (hour < 6) {
// zzz
} else if (hour < 10) {
display = "Breakfast time";
} else if (hour < 16) {
display = "Lunch time";
} else if (hour < 21) {
display = "Dinner time";
} else if (hour < 23) {
display = "Bed time";
}
var localizedDisplay = NSBundle.MainBundle.LocalizedString (display, comment:"greeting");
displayText.SetText (localizedDisplay);
// "language@2x.png" is located in the Watch Extension
// multiple times: once for each language .lproj directory
using (var image = UIImage.FromBundle ("language")) {
displayImage.SetImage (image);
}
// var formatter = new NSDateFormatter ();
// formatter.DateStyle = NSDateFormatterStyle.Medium;
// formatter.TimeStyle = NSDateFormatterStyle.Long;
// formatter.Locale = NSLocale.CurrentLocale;
// var localizedDateTime = formatter.StringFor (NSDate.Now);
var localizedDateTime = NSDateFormatter.ToLocalizedString (NSDate.Now, NSDateFormatterStyle.Long, NSDateFormatterStyle.Short);
displayTime.SetText (localizedDateTime);
}
}
}
| mit | C# |
99fa4e1a00494a539f1e67dc574275f84b78e274 | Add Note model | jzebedee/lcapi | LCAPI/LCAPI/Models/Note.cs | LCAPI/LCAPI/Models/Note.cs | using System;
namespace LendingClub.Models
{
/// <summary>
/// Details of a note owned by the investor
/// </summary>
public class Note
{
public string LoanStatus { get; set; }
public long LoanId { get; set; }
public long NoteId { get; set; }
public string Grade { get; set; }
public decimal LoanAmount { get; set; }
public decimal InterestRate { get; set; }
public long OrderId { get; set; }
public int LoanLength { get; set; }
public DateTime? IssueDate { get; set; }
public DateTime OrderDate { get; set; }
public DateTime? LoanStatusDate { get; set; }
public decimal PaymentsReceived { get; set; }
}
}
| agpl-3.0 | C# | |
cd6365e9745046c856be2b4edeac1f254392a76a | Create Base62CorrelationServiceTests.cs | tiksn/TIKSN-Framework | TIKSN.UnitTests.Shared/Integration/Correlation/Base62CorrelationServiceTests.cs | TIKSN.UnitTests.Shared/Integration/Correlation/Base62CorrelationServiceTests.cs | using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using System;
using TIKSN.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.Integration.Correlation.Tests
{
public class Base62CorrelationServiceTests
{
private readonly ICorrelationService _correlationService;
private readonly ITestOutputHelper _testOutputHelper;
public Base62CorrelationServiceTests(ITestOutputHelper testOutputHelper)
{
var services = new ServiceCollection();
services.AddFrameworkPlatform();
services.AddSingleton<ICorrelationService, Base62CorrelationService>();
var serviceProvider = services.BuildServiceProvider();
_correlationService = serviceProvider.GetRequiredService<ICorrelationService>();
_testOutputHelper = testOutputHelper ?? throw new ArgumentNullException(nameof(testOutputHelper));
}
[Fact]
public void GenerateAndParse()
{
var correlationID = _correlationService.Generate();
LogOutput(correlationID, nameof(correlationID));
var correlationIDFromString = _correlationService.Create(correlationID.ToString());
LogOutput(correlationIDFromString, nameof(correlationIDFromString));
var correlationIDFromBytes = _correlationService.Create(correlationID.ToByteArray());
LogOutput(correlationIDFromBytes, nameof(correlationIDFromBytes));
correlationIDFromString.Should().Be(correlationID);
correlationIDFromBytes.Should().Be(correlationID);
correlationIDFromString.Should().Be(correlationIDFromBytes);
}
private void LogOutput(CorrelationID correlationID, string name)
{
_testOutputHelper.WriteLine("-------------------------");
_testOutputHelper.WriteLine(name);
_testOutputHelper.WriteLine(correlationID.ToString());
_testOutputHelper.WriteLine(BitConverter.ToString(correlationID.ToByteArray()));
_testOutputHelper.WriteLine("");
}
}
} | mit | C# | |
556b51b7245bd5a0225ae502689fb5904a328662 | Add Q228 | txchen/localleet | csharp/Q228_SummaryRanges.cs | csharp/Q228_SummaryRanges.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Given a sorted integer array without duplicates, return the summary of its ranges.
//
// For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
// https://leetcode.com/problems/summary-ranges/
namespace LocalLeet
{
public class Q228
{
public IList<string> SummaryRanges(int[] nums)
{
if (nums.Length == 0)
{
return new List<string>();
}
List<string> result = new List<string>();
int currentStart = nums[0];
int currentEnd = nums[0];
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] == currentEnd + 1)
{
currentEnd = nums[i];
}
else
{
result.Add(GenSeg(currentStart, currentEnd));
currentStart = currentEnd = nums[i];
}
}
result.Add(GenSeg(currentStart, currentEnd));
return result;
}
private string GenSeg(int start, int end)
{
if (start == end)
{
return start.ToString();
}
else
{
return start.ToString() + "->" + end.ToString();
}
}
[Fact]
public void Q228_SummaryRanges()
{
TestHelper.Run(input => TestHelper.Serialize(SummaryRanges(input.EntireInput.ToIntArray())));
}
}
}
| mit | C# | |
f8402a851c16e57bf3d74b438c1eb291608d02d0 | Create MongoUnitOfWorkFactory.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/Mongo/MongoUnitOfWorkFactory.cs | TIKSN.Core/Data/Mongo/MongoUnitOfWorkFactory.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
namespace TIKSN.Data.Mongo
{
public class MongoUnitOfWorkFactory : IMongoUnitOfWorkFactory
{
private readonly IMongoClientProvider _mongoClientProvider;
private readonly IServiceProvider _serviceProvider;
public MongoUnitOfWorkFactory(IMongoClientProvider mongoClientProvider, IServiceProvider serviceProvider)
{
_mongoClientProvider = mongoClientProvider ?? throw new ArgumentNullException(nameof(mongoClientProvider));
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
public async Task<IMongoUnitOfWork> CreateAsync(CancellationToken cancellationToken)
{
var mongoClient = _mongoClientProvider.GetMongoClient();
var clientSessionHandle = await mongoClient.StartSessionAsync(options: null, cancellationToken: cancellationToken);
var serviceScope = _serviceProvider.CreateScope();
var mongoClientSessionStore = serviceScope.ServiceProvider.GetRequiredService<IMongoClientSessionStore>();
mongoClientSessionStore.SetClientSessionHandle(clientSessionHandle);
clientSessionHandle.StartTransaction();
return new MongoUnitOfWork(clientSessionHandle, serviceScope);
}
}
} | mit | C# | |
d630654f779ccd8d6e65ab1cb445076dc06e8154 | Add new NSNetService file to keep API compatibility with binding change | cwensley/maccore,mono/maccore | src/Foundation/NSNetService.cs | src/Foundation/NSNetService.cs | //
// Copyright 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace MonoTouch.Foundation {
public unsafe partial class NSNetService {
public virtual NSData TxtRecordData {
get { return GetTxtRecordData (); }
// ignore boolean return value
set { SetTxtRecordData (value); }
}
}
} | apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.