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 |
|---|---|---|---|---|---|---|---|---|
f13d221acd8304396742e08a07c1eaaf26704eac | Create ConsoleTestAssemblyInfo.cs | codecore/Functional,codecore/Functional | ConsoleTestAssemblyInfo.cs | ConsoleTestAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DonCode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DonCode")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("810bc213-2639-4eac-b652-7839fe797bd3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# | |
c0879a04a97acd1bfa3f8705d8ffc582f09a6977 | Add some basic tests for tags | mvno/Okanshi,mvno/Okanshi,mvno/Okanshi | tests/Okanshi.Tests/TagTest.cs | tests/Okanshi.Tests/TagTest.cs | using FluentAssertions;
using Xunit;
namespace Okanshi.Test
{
public class TagTest
{
[Fact]
public void Creating_a_new_tag_sets_the_correct_key()
{
var expectedKey = "key";
var tag = new Tag(expectedKey, "anything");
tag.Key.Should().Be(expectedKey);
}
[Fact]
public void Creating_a_new_tag_sets_the_correct_value()
{
var expectedValue = "value";
var tag = new Tag("anything", expectedValue);
tag.Value.Should().Be(expectedValue);
}
[Fact]
public void Two_tags_with_the_same_key_and_value_should_be_equal()
{
var tag1 = new Tag("key", "value");
var tag2 = new Tag("key", "value");
tag1.Should().Be(tag2);
}
[Fact]
public void Two_tags_with_the_same_key_and_value_should_have_same_hash()
{
var tag1Hash = new Tag("key", "value").GetHashCode();
var tag2Hash = new Tag("key", "value").GetHashCode();
tag1Hash.Should().Be(tag2Hash);
}
}
} | mit | C# | |
4d1b3735fa23f7a31001c159a25c8dd1e1683931 | Add weaklist benchmarks | smoogipooo/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework | osu.Framework.Benchmarks/BenchmarkWeakList.cs | osu.Framework.Benchmarks/BenchmarkWeakList.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using BenchmarkDotNet.Attributes;
using NUnit.Framework;
using osu.Framework.Lists;
namespace osu.Framework.Benchmarks
{
public class BenchmarkWeakList : BenchmarkTest
{
private readonly object[] objects = new object[1000];
private WeakList<object> weakList;
public override void SetUp()
{
for (int i = 0; i < 1000; i++)
objects[i] = new object();
}
[IterationSetup]
[SetUp]
public void IterationSetup()
{
weakList = new WeakList<object>();
foreach (var obj in objects)
weakList.Add(obj);
}
[Benchmark]
public void Add() => weakList.Add(new object());
[Benchmark]
public void Remove() => weakList.Remove(objects[0]);
[Benchmark]
public bool Contains() => weakList.Contains(objects[0]);
[Benchmark]
public object[] Enumerate() => weakList.ToArray();
[Benchmark]
public object[] RemoveAllAndEnumerate()
{
foreach (var obj in objects)
weakList.Remove(obj);
return weakList.ToArray();
}
}
}
| mit | C# | |
20f6ff769c07dfdb81dab3dd1aa4b3a1be8558de | Add tests | peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework.Tests/Localisation/LocalisableEnumAttributeTest.cs | osu.Framework.Tests/Localisation/LocalisableEnumAttributeTest.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.Extensions;
using osu.Framework.Localisation;
namespace osu.Framework.Tests.Localisation
{
[TestFixture]
public class LocalisableEnumAttributeTest
{
[TestCase(EnumA.Item1, "Item1")]
[TestCase(EnumA.Item2, "B")]
public void TestNonLocalisableEnumReturnsDescriptionOrToString(EnumA value, string expected)
{
Assert.That(value.GetLocalisableDescription().ToString(), Is.EqualTo(expected));
}
[TestCase(EnumB.Item1, "A")]
[TestCase(EnumB.Item2, "B")]
public void TestLocalisableEnumReturnsMappedValue(EnumB value, string expected)
{
Assert.That(value.GetLocalisableDescription().ToString(), Is.EqualTo(expected));
}
[Test]
public void TestLocalisableEnumWithInvalidBaseTypeThrows()
{
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Assert.Throws<ArgumentException>(() => EnumC.Item1.GetLocalisableDescription().ToString());
}
[Test]
public void TestLocalisableEnumWithInvalidGenericTypeThrows()
{
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
Assert.Throws<InvalidOperationException>(() => EnumD.Item1.GetLocalisableDescription().ToString());
}
public enum EnumA
{
Item1,
[System.ComponentModel.Description("B")]
Item2
}
[LocalisableEnum(typeof(EnumBEnumLocalisationMapper))]
public enum EnumB
{
Item1,
Item2
}
private class EnumBEnumLocalisationMapper : EnumLocalisationMapper<EnumB>
{
public override LocalisableString Map(EnumB value)
{
switch (value)
{
case EnumB.Item1:
return "A";
case EnumB.Item2:
return "B";
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
}
[LocalisableEnum(typeof(EnumCEnumLocalisationMapper))]
public enum EnumC
{
Item1,
}
private class EnumCEnumLocalisationMapper
{
}
[LocalisableEnum(typeof(EnumDEnumLocalisationMapper))]
public enum EnumD
{
Item1,
}
private class EnumDEnumLocalisationMapper : EnumLocalisationMapper<EnumA>
{
public override LocalisableString Map(EnumA value) => "A";
}
}
}
| mit | C# | |
f1c7191cf96e3221d041c4c470679a5ac10a5088 | Create SaveFileInExcel97-2003format.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Files/Handling/SaveFileInExcel97-2003format.cs | Examples/CSharp/Files/Handling/SaveFileInExcel97-2003format.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Files.Handling
{
public class SavingFiles
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a Workbook object
Workbook workbook = new Workbook();
//Your Code goes here for any workbook related operations
//Save in Excel 97 – 2003 format
workbook.Save(dataDir + "book1.out.xls");
//OR
workbook.Save(dataDir + "book1.out.xls", new XlsSaveOptions(SaveFormat.Excel97To2003));
//ExEnd:1
}
}
}
| mit | C# | |
a94fe786fb932019cfc1c5478b48de3b47d3429c | add test about yaml comments. | aaubry/YamlDotNet,aaubry/YamlDotNet,aaubry/YamlDotNet | YamlDotNet.Test/Serialization/YamlCommentTests.cs | YamlDotNet.Test/Serialization/YamlCommentTests.cs | using Xunit;
using Xunit.Abstractions;
using YamlDotNet.Serialization;
namespace YamlDotNet.Test.Serialization
{
public class YamlCommentTests
{
protected readonly ITestOutputHelper Output;
public YamlCommentTests(ITestOutputHelper helper)
{
Output = helper;
}
[Fact]
public void SerializationWithComment()
{
var person = new Person();
person.Name = "PandaTea";
person.Age = 100;
person.Sex = "male";
Serializer serializer = new Serializer();
string result = serializer.Serialize(person);
Output.WriteLine(result);
}
class Person
{
[YamlMember(Description = "this is a yaml comment about name property")]
public string Name { get; set; }
[YamlMember(Description = "this is age")]
public int Age { get; set; }
[YamlMember(Description = "male or female")]
public string Sex { get; set; }
}
}
}
| mit | C# | |
bb3703808dcf7671bc58546a1d75fc52939a0709 | Create AssemblyInfo.cs | APEdevelopment/APE,APEdevelopment/APE | APE.Bridge/APE.Bridge/Properties/AssemblyInfo.cs | APE.Bridge/APE.Bridge/Properties/AssemblyInfo.cs | apache-2.0 | C# | ||
ac0d6c83728687624fa9b88529318138170cf42d | Create AssemblyInfo.cs | MazyModz/CSharp-WebSocket-Server,MazyModz/CSharp-WebSocket-Server | Example/Server/Server/Properties/AssemblyInfo.cs | Example/Server/Server/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Server")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3c76a0b5-4c60-41c3-9073-811bfed6a1a2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# | |
b282621cf144cda6b3ac1bbe9f11c46b698bd5bc | Create pingt.cs | imba-tjd/CSharp-Code-Repository | 单个文件的程序/pingt.cs | 单个文件的程序/pingt.cs | using System;
using System.Diagnostics;
// 对tcping的简单封装,自动使用443
class PingT
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("参数不正确");
Environment.Exit(1);
}
// 无论输入主机还是网址都能运行,后者会自动提取出主机,;但为了使用Uri,又要当输入前者时加上协议
string url = args[0].Trim();
if (!url.StartsWith("http"))
url = "http://" + url;
string host = new Uri(url).Host;
Process.Start(new ProcessStartInfo("tcping", $"-n 8 {host} 443") { UseShellExecute = false }).WaitForExit();
}
}
| mit | C# | |
9dca0aa5956b15337dd16bb624dfc06dcdf32ccb | Create Default.aspx.cs | lerwine/JSCookbook,lerwine/JSCookbook,lerwine/JSCookbook | JSCookbook/Default.aspx.cs | JSCookbook/Default.aspx.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace JSCookbook
{
public partial class Default_Page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
| apache-2.0 | C# | |
36bfe637c0786353981d5f34acee6fff1eb89761 | Create PhotosAreaRegistration.cs | fatmagazaile/Projet | PhotosAreaRegistration.cs | PhotosAreaRegistration.cs | using System.Web.Mvc;
namespace MvcMeublatexApp.Areas.Photos
{
public class PhotosAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Photos";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"photos_default",
"{culture}/photos/{controller}/{action}/{id}",
new { culture = "en-IE", controller = "PhotosHome", action = "Index", id = "" },
new { culture = "^[a-zA-Z]{2,2}-[a-zA-Z]{2,2}$" }
);
}
}
}
| apache-2.0 | C# | |
1fc100aaabcdb11f145a11d6115e865a007541c3 | Create re.cs | sainand/test | re.cs | re.cs | asasd
| unlicense | C# | |
4f4c1481cb8a6f32e89fa0a9925c0aaf42e2f654 | Add SNOMED folder | HIISORG/CORE | SNOMED/org.hiis.snomed.cs | SNOMED/org.hiis.snomed.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace org.hiis {
class SNOMED {
}
}
| bsd-3-clause | C# | |
4d3ff6e5d63c98e7e8b687772735b9e4a86c8fe6 | Create temp.cs | StupidChris/LMC-Emulator,StupidChris/LMC-Emulator | Virtual-Machine/CSharp/temp.cs | Virtual-Machine/CSharp/temp.cs | mit | C# | ||
a63f3a8eeeabf1e96791afe4dc34743eb8667d0a | Add ModelState.TryAddModelError | tempusdigital/Tempus.Utils | Tempus.Utils.AspNetCore/ModelStateExtensions.cs | Tempus.Utils.AspNetCore/ModelStateExtensions.cs | using FluentValidation;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Data.SqlClient;
namespace Tempus.Utils.AspNetCore
{
public static class ModelStateExtensions
{
public static bool TryAddModelError(this ModelStateDictionary source, Exception exception)
{
return
TryProcessServerSideException(source, exception)
|| TryProcessValidationExpection(source, exception)
|| TryProcessDeleteExpection(source, exception)
|| TryProcessConcurrencyExpection(source, exception);
}
static bool TryProcessServerSideException(ModelStateDictionary source, Exception exception)
{
if (exception is ServerSideValidationException serverSide)
{
source.AddModelError("", serverSide.Message);
return true;
}
return false;
}
static bool TryProcessValidationExpection(ModelStateDictionary source, Exception exception)
{
if (exception is ValidationException validationException)
{
foreach (var error in validationException.Errors)
{
var message = string.IsNullOrWhiteSpace(error.ErrorMessage) ? Recurso.predicate_error : error.ErrorMessage;
if (string.IsNullOrWhiteSpace(error.ErrorCode))
source.AddModelError(error.PropertyName, message);
else
source.AddModelError(error.PropertyName, message);
}
return true;
}
return false;
}
static bool TryProcessConcurrencyExpection(ModelStateDictionary source, Exception exception)
{
if (exception?.GetType()?.Name == "DbUpdateConcurrencyException" || exception?.InnerException?.GetType()?.Name == "DbUpdateConcurrencyException")
{
source.AddModelError("", Recurso.ErroDeConcorrencia);
return true;
}
return false;
}
static bool TryProcessDeleteExpection(ModelStateDictionary source, Exception exception)
{
if (exception?.InnerException is SqlException sqlException && sqlException.Number == 547 && sqlException.Message.Contains("DELETE"))
{
source.AddModelError("", Recurso.ErroAoExcluir);
return true;
}
return false;
}
}
}
| mit | C# | |
403dab39a2e3944ebebfc36d7719275951b7e821 | Add build.cake | CatenaLogic/JiraCli | build.cake | build.cake | //=======================================================
// DEFINE PARAMETERS
//=======================================================
// Define the required parameters
var Parameters = new Dictionary<string, object>();
Parameters["SolutionName"] = "JiraCli";
Parameters["Company"] = "CatenaLogic";
Parameters["RepositoryUrl"] = string.Format("https://github.com/{0}/{1}", GetBuildServerVariable("Company"), GetBuildServerVariable("SolutionName"));
Parameters["StartYear"] = "2014";
Parameters["UseVisualStudioPrerelease"] = "true";
// Note: the rest of the variables should be coming from the build server,
// see `/deployment/cake/*-variables.cake` for customization options
//
// If required, more variables can be overridden by specifying them via the
// Parameters dictionary, but the build server variables will always override
// them if defined by the build server. For example, to override the code
// sign wild card, add this to build.cake
//
// Parameters["CodeSignWildcard"] = "Orc.EntityFramework";
//=======================================================
// DEFINE COMPONENTS TO BUILD / PACKAGE
//=======================================================
Tools.Add(string.Format("{0}", GetBuildServerVariable("SolutionName")));
TestProjects.Add(string.Format("{0}.Tests", GetBuildServerVariable("SolutionName")));
//=======================================================
// REQUIRED INITIALIZATION, DO NOT CHANGE
//=======================================================
// Now all variables are defined, include the tasks, that
// script will take care of the rest of the magic
#l "./deployment/cake/tasks.cake" | mit | C# | |
1282a6352a65439e541f559f794685a21cee2d90 | add unit test to cover bitwise offsetting | SixLabors/Fonts | tests/SixLabors.Fonts.Tests/Issues/Issues_104.cs | tests/SixLabors.Fonts.Tests/Issues/Issues_104.cs | using SixLabors.Fonts.Exceptions;
using SixLabors.Fonts.Tables.General.CMap;
using Xunit;
using static SixLabors.Fonts.Tables.General.CMap.Format4SubTable;
namespace SixLabors.Fonts.Tests.Issues
{
public class Issues_104
{
[Fact]
public void Format4SubTableWithSegmentsHasOffByOneWhenOverflowing()
{
var tbl = new Format4SubTable(0, WellKnownIds.PlatformIDs.Windows, 0, new[] {
new Segment(0,
ushort.MaxValue, // end
ushort.MinValue, // start of range
(short)(short.MaxValue), //delta
0 // zero to force correctly tested codepath
)
}, null);
var delta = short.MaxValue + 2;// extra 2 to handle the difference between ushort and short when offsettings
var codePoint = delta + 5;
Assert.True(tbl.TryGetGlyphId(codePoint, out var gid));
Assert.Equal(5, gid);
}
}
}
| apache-2.0 | C# | |
54b66d7cf4fb214bdef3341e0d0645f19dd1f894 | Add files via upload | abhinavveenu/Algorithms | trie.cs | trie.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pract
{
class trie
{
trie[] children { get; set; }
bool isLeaf;
public trie()
{
children = new trie[26];
}
/// <summary>
/// Inserts string in trie if it does not there in the trie object
/// </summary>
/// <param name="str"></param>
public void insert(string str)
{
if (ContainsString(str)) return;
trie crawler = this;
for (int i = 0; i < str.Length; i++)
{
int index = str[i] - 'a';
if (crawler.children[index] == null)
{
crawler.children[index] = new trie();
}
crawler = crawler.children[index];
}
}
/// <summary>
/// Search for the string in trie data structure. If string exists then it returns true else false
/// </summary>
/// <param name="str"></param>
/// <returns>true: if string exists, else returns false</returns>
public bool ContainsString(string str)
{
bool result = true;
trie crawler = this;
for (int i = 0; i < str.Length; i++)
{
int index = str[i] - 'a';
if (crawler.children[index] == null)
{
result = false;
break;
}
crawler = crawler.children[index];
}
return result;
}
}
}
| apache-2.0 | C# | |
07126f9bfb6cb1ab865a09aa4c2a4c41bef57f81 | Fix copyright in assemblyinfo | xamarin/XamarinComponents,topgenorth/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,topgenorth/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,topgenorth/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,topgenorth/XamarinComponents,xamarin/XamarinComponents | Android/Glide/source/Xamarin.Android.Glide/Properties/AssemblyInfo.cs | Android/Glide/source/Xamarin.Android.Glide/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Android.Glide")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Android.Glide")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
2e07c83cfbbc0e762a6c875ee321be24d1a7bf2d | Mark Height Components with region transgression | sts-CAD-Software/PCB-Investigator-Scripts | MarkHeightRegionTransgression.cs | MarkHeightRegionTransgression.cs | //-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 16.06.2016
// Autor Fabio.Gruber
//
// Mark all components in max height regions of drc_comp layer.
// This checks each cmp over the surfaces on relevant layer with drc_max_height attribute.
//-----------------------------------------------------------------------------------
// GUID markHeightRegionTransgression_635963030633639805
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
public void Execute(IPCBIWindow parent)
{
// IStep step = parent.GetCurrentStep();
if (step == null) return;
string layernameTopHeightRestrictions = "drc_comp";
ICMPLayer topCMPLayer = step.GetCMPLayer(true); //for bottom change here to false
ILayer HeightRestirctionLayer = step.GetLayer(layernameTopHeightRestrictions);
// check each cmp for height restrictions
foreach (ICMPObject cmp in topCMPLayer.GetAllLayerObjects())
{
foreach (IODBObject surface in HeightRestirctionLayer.GetAllObjectInRectangle(cmp.Bounds))
{
if (surface.IsPointOfSecondObjectIncluded(cmp, false)) //intersecting is ok?
{
//check height of cmp
IAttributeElement attributeMaxHeight = null;
foreach (IAttributeElement attribute in IAttribute.GetAllAttributes(surface))
{
if (attribute.AttributeEnum == PCBI.FeatureAttributeEnum.drc_max_height)
{
attributeMaxHeight = attribute;
break;
}
}
if (attributeMaxHeight == null) continue;
if (cmp.CompHEIGHT > (double)attributeMaxHeight.Value) //we know this attribute has double values
{
cmp.ObjectColorTemporary(Color.LightCoral); //change color to highlight cmps
//surface.ObjectColorTemporary(Color.Wheat);
surface.FreeText = "Check Height of " + cmp.Ref;
break;
}
}
}
}
topCMPLayer.EnableLayer(true);
HeightRestirctionLayer.EnableLayer(true);
parent.UpdateView();
}
}
} | bsd-3-clause | C# | |
d395b628382f847278ea574fde8d4e1dba34d74d | Add IDisposable wrapper on GCHandle | DrabWeb/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,peppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework | osu.Framework/Allocation/ObjectHandle.cs | osu.Framework/Allocation/ObjectHandle.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Allocation
{
/// <summary>
/// Wrapper on <see cref="GCHandle" /> that supports the <see cref="IDisposable" /> pattern.
/// </summary>
public class ObjectHandle<T> : IDisposable
{
/// <summary>
/// The object being referenced.
/// </summary>
public T Target { get; private set; }
/// <summary>
/// The pointer from the <see cref="GCHandle" />, if it is allocated. Otherwise <see cref="IntPtr.Zero" />.
/// </summary>
public IntPtr Handle => handle.IsAllocated ? GCHandle.ToIntPtr(handle) : IntPtr.Zero;
private GCHandle handle;
/// <summary>
/// Wraps the provided object with a <see cref="GCHandle" />, using the given <see cref="GCHandleType" />.
/// </summary>
/// <param name="target">The target object to wrap.</param>
/// <param name="handleType">The handle type to use.</param>
public ObjectHandle(T target, GCHandleType handleType)
{
Target = target;
handle = GCHandle.Alloc(target, handleType);
}
/// <summary>
/// Wrapper on <see cref="GCHandle.FromIntPtr" /> that returns the associated object.
/// </summary>
/// <returns>The associated object.</returns>
/// <param name="handle">The pointer to the associated object.</param>
public static T FromPointer(IntPtr handle) => (T)GCHandle.FromIntPtr(handle).Target;
#region IDisposable Support
private bool disposedValue;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
Target = default;
if (handle.IsAllocated)
handle.Free();
disposedValue = true;
}
}
~ObjectHandle()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| mit | C# | |
9afa34fc33727069ef6f82b1568acd041accc8a5 | Replace surfacs by pads | sts-CAD-Software/PCB-Investigator-Scripts | ReplaceSurfacesBySpecialPads.cs | ReplaceSurfacesBySpecialPads.cs | //-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 25.04.2016
// Autor support@easylogix.de
// www.pcb-investigator.com
// SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html
// SDK http://www.pcb-investigator.com/en/sdk-participate
//
// Replace all selected surfaces by pads with new special symbol.
//-----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
public void Execute(IPCBIWindow parent)
{
IFilter filter = new IFilter(parent);
IStep curStep = parent.GetCurrentStep();
if (curStep == null) return;
List<IODBObject> selectedElements = curStep.GetSelectedElements();
//create list with all selected elements to make a new symbol of it
foreach (IODBObject obj in selectedElements)
{
List<IObjectSpecificsD> newSymbolSpecs = new List<IObjectSpecificsD>();
string relLayerName = "";
PCBI.MathUtils.RectangleD bounds = new PCBI.MathUtils.RectangleD();
int indexOfLastElement = 1;
newSymbolSpecs.Add(obj.GetSpecificsD());
relLayerName = obj.GetParentLayerName();
if (bounds == RectangleD.Empty)
{
bounds = obj.GetBoundsD();
}
else
{
bounds = PCBI.MathUtils.RectangleD.Union(bounds, obj.GetBoundsD());
}
indexOfLastElement = obj.GetIndexOnLayer();
IODBLayer relLayer = (IODBLayer)curStep.GetLayer(relLayerName);
if (relLayer == null) return;
//create new symbol for pads, the name must be unique. We try it with the index of one of the elements.
int nr = IFilter.AddToolDefinitionSpecial(relLayer, parent, "testsymbol3" + indexOfLastElement, newSymbolSpecs, -bounds.GetMidPoint().X, -bounds.GetMidPoint().Y);
if (nr < 0)
{
//no new symbol was created, maybe name is already existing
return;
}
//delete old elements
IAutomation.SuppressUserNotifications = false; //otherwise the delete action will be blocked
IODBObject pad = filter.CreatePad(relLayer);
IPadSpecificsD padSpec = (IPadSpecificsD)pad.GetSpecificsD();
padSpec.Location = bounds.GetMidPoint();
pad.SetSpecifics(padSpec, nr);
pad.SetAttribute("new symbol attribute");
// pad.Select(true);
}
parent.UIAction.Execute(ID_ActionItem.ID_DELETE);
parent.UpdateView();
}
}
} | bsd-3-clause | C# | |
159f31c4fbca15b92fbecf0b0b9e4ef227e44864 | Create diamond.cs | ashoktandan007/csharp,wchild30/asterisk | diamond.cs | diamond.cs | using System;
class prog
{
public static void Main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
Console.Write(" ");
}
for (int k = 0; k < i; k++)
{
Console.Write("*");
}
for (int k = 1; k < i; k++)
{
Console.Write("*");
}
Console.WriteLine("");
}
for (int i = 5; i > 0; i--)
{
for (int j = 5; j > i; j--)
{
Console.Write(" ");
}
for (int k = 0; k < i; k++)
{
Console.Write("*");
}
for (int k = 1; k < i; k++)
{
Console.Write("*");
}
Console.WriteLine("");
}
Console.ReadLine();
}
}
| apache-2.0 | C# | |
d02efa8d40844592bf8e84d88e8c91bf713ec9c7 | Create MonsterGirl.cs | TelerikAcademy2015/TelerikDefence | TowerDefense/Main/MonsterGirl.cs | TowerDefense/Main/MonsterGirl.cs | //Girl Monster - fast monster with low health.
namespace TowerDefense.Main
{
using System;
using System.Linq;
using TowerDefense.Interfaces;
using System.Windows.Media;
using TowerDefense.Utils;
class MonsterGirl : Monster//, IMonster, IGameObject, IMovable, ITarget - Commented because of team rule.
{
public MonsterGirl(IRoute route)
: base(route, 100, 10)
{
this.IsDestroyed = false;
this.ChangeImage();
}
public override ImageSource ImageSource
{
get
{
return ImageFactory.CreateImage("MonsterGirl.png");
}
}
public void ChangeImage()
{
}
}
}
| mit | C# | |
9eaa6cf8ae0537a9c702e506601c44f19fa0d584 | Add new CoinView class for query coins | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/CoinsView.cs | WalletWasabi/Models/CoinsView.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Models
{
public class CoinsView : IEnumerable<SmartCoin>
{
private IEnumerable<SmartCoin> _coins;
public CoinsView(IEnumerable<SmartCoin> coins)
{
_coins = Guard.NotNull(nameof(coins), coins);
}
public CoinsView UnSpent()
{
return new CoinsView(_coins.Where(x=>x.Unspent && !x.SpentAccordingToBackend));
}
public CoinsView Available()
{
return new CoinsView(_coins.Where(x=>!x.Unavailable));
}
public CoinsView CoinJoinInProcess()
{
return new CoinsView(_coins.Where(x=>x.CoinJoinInProgress));
}
public CoinsView Confirmed()
{
return new CoinsView(_coins.Where(x=>x.Confirmed));
}
public CoinsView Unconfirmed()
{
return new CoinsView(_coins.Where(x=>!x.Confirmed));
}
public CoinsView AtBlockHeight(Height height)
{
return new CoinsView(_coins.Where(x=>x.Height == height));
}
public CoinsView SpentBy(uint256 txid)
{
return new CoinsView(_coins.Where(x => x.SpenderTransactionId == txid));
}
public CoinsView ChildrenOf(SmartCoin coin)
{
return new CoinsView(_coins.Where(x => x.TransactionId == coin.SpenderTransactionId));
}
public CoinsView DescendatOf(SmartCoin coin)
{
IEnumerable<SmartCoin> Generator(SmartCoin coin)
{
foreach(var child in ChildrenOf(coin))
{
foreach(var childDescendat in ChildrenOf(child))
{
yield return childDescendat;
}
yield return child;
}
}
return new CoinsView(Generator(coin));
}
public CoinsView FilterBy(Func<SmartCoin, bool> expression)
{
return new CoinsView(_coins.Where(expression));
}
public CoinsView OutPoints(IEnumerable<TxoRef> outPoints)
{
return new CoinsView(_coins.Where(x=> outPoints.Any( y=> y == x.GetOutPoint())));
}
public Money TotalAmount()
{
return _coins.Sum(x=>x.Amount);
}
public SmartCoin[] ToArray()
{
return _coins.ToArray();
}
public IEnumerator<SmartCoin> GetEnumerator()
{
return _coins.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _coins.GetEnumerator();
}
}
} | mit | C# | |
88cc3562558cf129c2ede05f632c4c145d4730ad | Create ArrayElemSumEqualsK.cs | shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms | geeksforgeeks/ArrayElemSumEqualsK.cs | geeksforgeeks/ArrayElemSumEqualsK.cs | //Given an array A and a key x, print a pair of elements which sum to x
public struct ans{
public int num1, num2;
}
public class Program
{
public static void Main(string[] args)
{
int []A = {23,12,3,544,56,567,435234,63,6,569,567,84,6724,62345};
int x = 1136; // method must return 569 and 567
Program p = new Program();
ans a = p.getSumPair(A, x);
Console.WriteLine(a.num1 + " " + a.num2);
}
private ans getSumPair(int[] A, int x){
Dictionary<int,bool> d = new Dictionary<int,bool>();
ans a = new ans();
foreach(int i in A){
bool b = false;
if(d.TryGetValue(x - i, out b)){
a.num1 = i;
a.num2 = x-i;
return a;
}
else
{
d.Add(i,true);
}
}
return a;
}
}
| mit | C# | |
86f28510b3f098dd114933be1a8e40d402948e94 | Set to version 2.5.0.0 | yonglehou/Thinktecture.IdentityModel.45,IdentityModel/Thinktecture.IdentityModel.45,shashwatchandra/Thinktecture.IdentityModel.45,jbn566/Thinktecture.IdentityModel.45,darraghoriordan/Thinktecture.IdentityModel.45,rmorris8812/Thinktecture.IdentityModel.45,nguyenbanguyen/Thinktecture.IdentityModel.45 | IdentityModel/Thinktecture.IdentityModel/Properties/AssemblyInfo.cs | IdentityModel/Thinktecture.IdentityModel/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Thinktecture.IdentityModel")]
[assembly: AssemblyDescription("Helper library for identity and access control in .NET 4.5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thinktecture")]
[assembly: AssemblyProduct("Thinktecture.IdentityModel")]
[assembly: AssemblyCopyright("Copyright © Dominick Baier & Brock Allen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2e3a2e3f-729c-42a4-9aee-48f2e14ae134")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.5.0.0")]
[assembly: AssemblyFileVersion("2.5.0.0")]
[assembly: CLSCompliant(true)]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Thinktecture.IdentityModel")]
[assembly: AssemblyDescription("Helper library for identity and access control in .NET 4.5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thinktecture")]
[assembly: AssemblyProduct("Thinktecture.IdentityModel")]
[assembly: AssemblyCopyright("Copyright © Dominick Baier & Brock Allen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2e3a2e3f-729c-42a4-9aee-48f2e14ae134")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.2.0")]
[assembly: AssemblyFileVersion("2.4.2.0")]
[assembly: CLSCompliant(true)]
| bsd-3-clause | C# |
6cee5819f7940d1f71ff91103160b26fc61f7fc4 | fix RIDER-47386 (right now we don't have settings to configure it) | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/HlslSupport/HlslCodeStyleDefaultSettings.cs | resharper/resharper-unity/src/HlslSupport/HlslCodeStyleDefaultSettings.cs | using JetBrains.Application.Settings;
using JetBrains.Application.Settings.Implementation;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Cpp.CodeStyle;
using JetBrains.ReSharper.Plugins.Unity.Settings;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.HlslSupport
{
[SolutionComponent]
public class HlslCodeStyleDefaultSettings : IUnitySolutionSettingsProvider
{
private readonly ISettingsSchema mySettingsSchema;
private readonly ILogger myLogger;
public HlslCodeStyleDefaultSettings(ISettingsSchema settingsSchema, ILogger logger)
{
mySettingsSchema = settingsSchema;
myLogger = logger;
}
public void InitialiseSolutionSettings(ISettingsStorageMountPoint mountPoint)
{
var entry = mySettingsSchema.GetScalarEntry((CppFormattingSettingsKey s) => s.INDENT_PREPROCESSOR_DIRECTIVES);
ScalarSettingsStoreAccess.SetValue(mountPoint, entry, null, PreprocessorIndent.Normal, true, null, myLogger);
}
}
} | apache-2.0 | C# | |
1f7c192344182779f0c02c87b5b3c3a308add58e | Add QueryParser skeleton class | TheBerkin/Rant | Rant/Core/Compiler/Parsing/QueryParser.cs | Rant/Core/Compiler/Parsing/QueryParser.cs | using System;
using System.Collections.Generic;
using Rant.Core.Compiler.Syntax;
namespace Rant.Core.Compiler.Parsing
{
internal class QueryParser : Parser
{
public override IEnumerator<Parser> Parse(RantCompiler compiler, CompileContext context, TokenReader reader, Action<RantAction> actionCallback)
{
throw new NotImplementedException();
}
}
} | mit | C# | |
2df10333ee07b5a1a1cbfe9e78e59638d9ceebc6 | Add LodViewProvider class | inohiro/LodViewProvider | LodViewProvider/LodViewProvider/LodViewProvider.cs | LodViewProvider/LodViewProvider/LodViewProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LodViewProvider {
class LodViewProvider : QueryProvider {
public override string GetQueryText( System.Linq.Expressions.Expression expression ) {
return string.Empty;
}
public override object Execute( System.Linq.Expressions.Expression expression ) {
return null;
}
public static IQueryable<T> CreateQueryable<T>() {
return new Query<T>( new LodViewProvider() );
}
}
}
| mit | C# | |
2152bfb12817f5b4c29554a089b350f73d064bf8 | Implement unit tests for the StringPattern class | openchain/openchain | test/OpenChain.Ledger.Tests/StringPatternTests.cs | test/OpenChain.Ledger.Tests/StringPatternTests.cs | // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using OpenChain.Ledger.Validation;
using Xunit;
namespace OpenChain.Ledger.Tests
{
public class StringPatternTests
{
[Fact]
public void IsMatch_Success()
{
Assert.True(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name_suffix"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nam"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nams"));
Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name"));
Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name_suffix"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nam"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nams"));
}
}
}
| apache-2.0 | C# | |
67a9ceff571335f993f29249b050302c97c9c4b4 | Create answer.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/answer.cs | POH6plus/answer.cs | using System;
using System.Linq;
public class Hello
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var w = new string[n];
for (var i = 0; i < n; i++)
w[i] = Console.ReadLine();
Array.Sort(w);
string s = "", t = "", c = "";
for (var i = 0; i < n; i++)
{
if (w[i] == "")
{
continue;
}
var r = new string(w[i].Reverse().ToArray());
var j = i + 1;
for (; j < n; j++)
{
if (w[j] == r)
{
s += w[i];
t = r + t;
w[j] = "";
break;
}
}
if (j < n)
{
continue;
}
if (w[i] == r && (c == "" || c.CompareTo(r) > 0))
{
c = r;
}
}
Console.WriteLine(s + c + t);
}
}
| mit | C# | |
2330c1607a619610f3884ddb9d7c896189b3c350 | Create TestingUtility.cs | billsheh/thread-affiliated-method-test | TestingUtility.cs | TestingUtility.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
public static class TestingUtility
{
public static void RunThreadAffiniatedAction(Func<Task> taskFunc, bool outputDebugInfo = false)
{
Dispatcher dispatcher = null;
DispatcherSynchronizationContext uiSyncCtx = null;
ManualResetEvent dispatcherReadyEvent = new ManualResetEvent(false);
TaskScheduler actionScheduler = null;
Exception actionException = null;
Thread actionThread = new Thread(new ThreadStart(() =>
{
dispatcher = Dispatcher.CurrentDispatcher;
uiSyncCtx = new DispatcherSynchronizationContext(dispatcher);
SynchronizationContext.SetSynchronizationContext(uiSyncCtx);
dispatcherReadyEvent.Set();
actionScheduler = TaskScheduler.FromCurrentSynchronizationContext();
if (outputDebugInfo)
Console.WriteLine("Starting action thread dispatcher...");
Dispatcher.Run();
if (outputDebugInfo)
Console.WriteLine("Exit action thread dispatcher");
}));
actionThread.Start();
if (outputDebugInfo)
Console.WriteLine("Action thread Id {0}", actionThread.ManagedThreadId);
dispatcherReadyEvent.WaitOne();
Func<Task> threadAction = async () =>
{
await taskFunc().ContinueWith(t =>
{
if (t.IsFaulted)
{
actionException = t.Exception;
}
else if (t.IsCanceled)
{
actionException = new OperationCanceledException("task was cancelled");
}
if (outputDebugInfo)
Console.WriteLine("Shutting down action thread...");
dispatcher.InvokeShutdown();
});
};
if (outputDebugInfo)
Console.WriteLine("Starting to execute action...");
dispatcher.InvokeAsync(threadAction);
if (outputDebugInfo)
Console.WriteLine("Wait for the action thread to finish...");
actionThread.Join();
if (outputDebugInfo)
Console.WriteLine("Action thread finished");
if (actionException != null)
{
var aggreException = actionException as AggregateException;
if (aggreException != null)
{
if (aggreException.InnerExceptions.Count() == 1)
{
throw aggreException.InnerExceptions[0];
}
else
throw aggreException.Flatten();
}else
{
throw actionException;
}
}
}
}
| mit | C# | |
cdc2d27a8a96c83475eec96913e88bde04d3037c | Add C# 7.0 Numeric Literal example | devlights/try-csharp | TryCSharp.Samples/CSharp7/NumericLiteralSamples01.cs | TryCSharp.Samples/CSharp7/NumericLiteralSamples01.cs | using TryCSharp.Common;
namespace TryCSharp.Samples.CSharp7
{
/// <summary>
/// C# 7.0 の新機能についてのサンプルです。
/// </summary>
/// <remarks>
/// Numeric Literal について
/// </remarks>
[Sample]
public class NumericLiteralSamples01 : IExecutable
{
public void Execute()
{
// C# 7.0 から数値の表現に「アンダースコア」を含めることが可能となった
// Pythonと同様な記載ができる
var million = 1_000_000;
// バイナリ表記も同様
var b = 0b1010_1011_1100_1101_1110_1111;
Output.WriteLine($"{million}, {b}");
}
}
} | mit | C# | |
2dd6e044336f81b44ac23d2911486927dfd1592b | Solve Average 2 in c# | deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground | solutions/uri/1006/1006.cs | solutions/uri/1006/1006.cs | using System;
using System.Collections.Generic;
class Solution {
static void Main() {
double a, b, c;
string val;
val = Console.ReadLine();
a = Convert.ToDouble(val);
val = Console.ReadLine();
b = Convert.ToDouble(val);
val = Console.ReadLine();
c = Convert.ToDouble(val);
Console.Write(
"MEDIA = {0:F1}{1}",
(a * 2.0 + b * 3.0 + c * 5.0) / 10.0,
Environment.NewLine
);
}
}
| mit | C# | |
afba7a4898427d8eaf00aadd990d7d7e6c461c3f | Add PinBox.cs | imazen/imageflow-dotnet | src/Imageflow/Bindings/PinBox.cs | src/Imageflow/Bindings/PinBox.cs | using System;
using System.Collections.Generic;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
namespace Imageflow.Net.Bindings
{
internal class PinBox : CriticalFinalizerObject, IDisposable
{
private List<GCHandle> _pinned;
internal void AddPinnedData(GCHandle handle)
{
if (_pinned == null) _pinned = new List<GCHandle>();
_pinned.Add(handle);
}
public void Dispose()
{
UnpinAll();
GC.SuppressFinalize(this);
}
private void UnpinAll()
{
//Unpin GCHandles
if (_pinned != null)
{
foreach (var active in _pinned)
{
if (active.IsAllocated) active.Free();
}
_pinned = null;
}
}
~PinBox()
{
UnpinAll();
}
}
}
| agpl-3.0 | C# | |
7876c6c4a48cd66a32fe7f52c6eae3edec176b83 | Create ItemId.cs | Pharap/SpengyUtils | Classes/ItemId.cs | Classes/ItemId.cs | // For getting a readable name from an IMyInventoryItem
// Use like:
// var item = entity.GetInventory().GetItems()[0];
// var itemId = new ItemId(item.Content);
public struct ItemId
{
private const string prefix = "MyObjectBuilder_";
private readonly string type;
private readonly string subtype;
public ItemId(VRage.ObjectBuilders.MyObjectBuilder_Base content)
{
var typeId = content.TypeId.ToString();
this.type = (typeId.IndexOf(prefix) == 0) ? typeId.Substring(prefix.Length) : "";
this.subtype = content.SubtypeName;
}
public string Type { get { return type; } }
public string Subtype { get { return subtype; } }
public override string ToString()
{
return string.Format("[{0}:{1}]", Type, Subtype);
}
}
| apache-2.0 | C# | |
1d8c4dcd5c67aca4c8a1ef7667eb6c19536ab61a | Create TitleEstimateController.cs | bigfont/webapi-cors | CORS/Controllers/TitleEstimateController.cs | CORS/Controllers/TitleEstimateController.cs | public class TitleEstimateController : ApiController
{
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
}
}
public class EstimateQuery
{
// Various fields
}
| mit | C# | |
eac7fee9bb006577394faab782b4f4359d58603f | Add BaseAspectAttribute | ziyasal/Aspector | src/Aspector/Attributes/BaseAspectAttribute.cs | src/Aspector/Attributes/BaseAspectAttribute.cs | using System;
namespace Aspector.Attributes
{
public class BaseAspectAttribute : Attribute
{
}
} | mit | C# | |
1e2fb196c31d552371fe8641417bc1dd4088d913 | Add AssumedRoleCredential | carbon/Amazon | src/Amazon.Sts/AssumedRoleCredential.cs | src/Amazon.Sts/AssumedRoleCredential.cs | using System.Threading.Tasks;
using Amazon.Sts;
namespace Amazon.Security;
public sealed class AssumedRoleCredential : IAwsCredential
{
private readonly string _roleArn;
private readonly string _roleSession;
private Credentials? _credentials = null;
private readonly StsClient _stsClient;
public AssumedRoleCredential(AwsRegion region, IAwsCredential credential, string roleArn, string roleSession)
{
ArgumentNullException.ThrowIfNull(roleArn);
ArgumentNullException.ThrowIfNull(roleSession);
_roleArn = roleArn;
_roleSession = roleSession;
_stsClient = new StsClient(region, credential);
}
public AssumedRoleCredential(StsClient stsClient, string roleArn, string roleSession)
{
ArgumentNullException.ThrowIfNull(roleArn);
ArgumentNullException.ThrowIfNull(roleSession);
_roleArn = roleArn;
_roleSession = roleSession;
_stsClient = stsClient;
}
public string AccessKeyId => _credentials?.AccessKeyId!;
public string SecretAccessKey => _credentials?.SecretAccessKey!;
public string SecurityToken => _credentials?.SessionToken!;
public bool ShouldRenew => _credentials is null || _credentials.ExpiresIn < TimeSpan.FromMinutes(5);
public async Task<bool> RenewAsync()
{
var request = new AssumeRoleRequest(_roleArn, _roleSession, TimeSpan.FromMinutes(15));
var result = await _stsClient.AssumeRoleAsync(request).ConfigureAwait(false);
_credentials = result.AssumeRoleResult.Credentials;
return true;
}
}
| mit | C# | |
a23503adcb510578ba4b053a768e6c3f5f7ca32e | Bump version to 1.2.1 | yonglehou/BTDB,karasek/BTDB,Bobris/BTDB,klesta490/BTDB | BTDB/Properties/AssemblyInfo.cs | BTDB/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BTDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BTDB")]
[assembly: AssemblyCopyright("Copyright Boris Letocha 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.2.1.0")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: InternalsVisibleTo("BTDBTest")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BTDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BTDB")]
[assembly: AssemblyCopyright("Copyright Boris Letocha 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: InternalsVisibleTo("BTDBTest")]
| mit | C# |
5e6ac0e10376e1f615f3edff4555f714d2f3d3cd | Add Attribution Model | 3nGercog/InstaSharp,danielmundim/InstaSharp,theShiva/InstaSharp,theShiva/InstaSharp,crashdavis23/InstaSharp,danielmundim/InstaSharp,crashdavis23/InstaSharp,3nGercog/InstaSharp,InstaSharp/InstaSharp | src/InstaSharp/Models/Attribution.cs | src/InstaSharp/Models/Attribution.cs | using InstaSharp.Infrastructure;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace InstaSharp.Models
{
public class Attribution
{
/// <summary>
/// Gets or sets the website.
/// </summary>
/// <value>
/// The website.
/// </value>
public string Website { get; set; }
/// <summary>
/// Gets or sets the itunes url.
/// </summary>
/// <value>
/// The itunes url.
/// </value>
[JsonProperty("itunes_url")]
public string ITunesUrl { get; set; }
/// <summary>
/// Gets or sets the comments.
/// </summary>
/// <value>
/// The comments.
/// </value>
public string Name { get; set; }
}
}
| apache-2.0 | C# | |
d843d2566250490ec4c1ca2354860c2a722e63fc | Add Category.cs | Ackara/Daterpillar | src/Tests/Tests.Daterpillar/Category.cs | src/Tests/Tests.Daterpillar/Category.cs | namespace Tests.Daterpillar
{
public class Category
{
public const string Integration = "Integration";
}
} | mit | C# | |
8e357e9dc2524813fc0e3098372c4cd2aae3102f | Add work/search object | windowsphonehacker/SparklrWP | SparklrLib/Objects/Responses/Work/Search.cs | SparklrLib/Objects/Responses/Work/Search.cs | using System.Collections.Generic;
namespace SparklrLib.Objects.Responses.Work
{
public class SearchUser
{
public string username { get; set; }
public int id { get; set; }
}
public class SearchPost
{
public int from { get; set; }
public int id { get; set; }
public object to { get; set; }
public int type { get; set; }
public object flags { get; set; }
public string meta { get; set; }
public int time { get; set; }
public int @public { get; set; }
public string message { get; set; }
public object lat { get; set; }
public object @long { get; set; }
public int? via { get; set; }
public int? origid { get; set; }
public int? commentcount { get; set; }
public int modified { get; set; }
public int network { get; set; }
}
public class Search
{
public List<SearchUser> users { get; set; }
public List<SearchPost> posts { get; set; }
}
}
| mit | C# | |
bce388ffb6e313f8bf29b4f15a217ba6ebb63684 | Add PatchRequest.cs | BYVoid/distribox | Distribox/Distribox.Network/Message/PatchRequest.cs | Distribox/Distribox.Network/Message/PatchRequest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Distribox.CommonLib;
using Distribox.FileSystem;
namespace Distribox.Network
{
class PatchRequest : ProtocolMessage
{
public List<AtomicPatch> Request { get; set; }
public PatchRequest(List<AtomicPatch> request, int myPort)
: base(myPort)
{
Request = request;
_type = MessageType.FileRequest;
}
public override void Accept(AntiEntropyProtocol visitor, Peer peer)
{
visitor.Process(this, peer);
}
}
}
| mit | C# | |
2a2bb7b036af4c8619f6c09858698e51fd999192 | Create ScaleCamera.cs | UnityCommunity/UnityLibrary | Scripts/2D/Camera/ScaleCamera.cs | Scripts/2D/Camera/ScaleCamera.cs | using UnityEngine;
// pixel perfect camera helpers, from old unity 2D tutorial videos
[ExecuteInEditMode]
public class ScaleCamera : MonoBehaviour
{
public int targetWidth = 640;
public float pixelsToUnits = 100;
void Start()
{
int height = Mathf.RoundToInt(targetWidth / (float)Screen.width * Screen.height);
GetComponent<Camera>().orthographicSize = height / pixelsToUnits / 2;
}
}
| mit | C# | |
c821ff2fb1a0c483a1cfbb0498c2badc92145f29 | Create CameraSwitcher.cs | UnityCommunity/UnityLibrary | Scripts/Camera/CameraSwitcher.cs | Scripts/Camera/CameraSwitcher.cs | // Camera switcher, https://forum.unity3d.com/threads/how-can-i-switch-between-multiple-cameras-using-one-key-click.472009/
// usage: Assign cameras into the array, press C to switch into next camera
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityLibrary
{
public class CameraSwitcher : MonoBehaviour
{
public Camera[] cameras;
int currentCamera = 0;
void Awake()
{
if (cameras == null || cameras.Length == 0)
{
Debug.LogError("No cameras assigned..", gameObject);
this.enabled = false;
}
EnableOnlyFirstCamera();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
// disable current
cameras[currentCamera].enabled = false;
// increment index and wrap after finished array
currentCamera = (currentCamera + 1) % cameras.Length;
// enable next
cameras[currentCamera].enabled = true;
}
}
void EnableOnlyFirstCamera()
{
for (int i = 0; i < cameras.Length; i++)
{
// only 1==0 returns true
cameras[i].enabled = (i == 0);
}
}
}
}
| mit | C# | |
097e10e688ffb1f56aa7d761524ee15d44f0e844 | Add WinForms C# solution class | jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015,jketo/arcusysdevday2015 | backrow_baddies/csharp/Form1.cs | backrow_baddies/csharp/Form1.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Open Image Files";
fDialog.Filter = "Java files|*.java";
fDialog.InitialDirectory = @"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
var s = File.ReadAllLines(fDialog.FileName.ToString());
int ras_mult = 1;
int ras_count = 0;
for (int i = 0; i < s.Length; i++)
{
for (int j = 0; j < s[i].Length; j++)
{
switch (s[i][j])
{
case '{':
ras_mult++;
break;
case '}':
ras_mult--;
break;
case ';':
ras_count += ras_mult;
break;
default:
break;
}
}
}
label1.Text = "Result: " + ras_count;
//MessageBox.Show(ras_count+"");
}
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Result: ";
}
}
}
| mit | C# | |
a433545cbae0471ee6b58618f79f7083a2229ca8 | Create DateTimeUtils.cs | ST-Software/Utils | src/DateTimeUtils.cs | src/DateTimeUtils.cs | using System;
namespace FinaDb.Common.Utils
{
public class DateTimeInterval
{
public DateTime? From { get; set; }
public DateTime? To { get; set; }
}
public static class DateTimeUtils
{
/// <summary>
/// Get the intersection between testInterval and allowedInterval.
/// </summary>
public static DateTimeInterval GetIntervalIntersection(DateTimeInterval testInterval, DateTimeInterval allowedInterval)
{
#region sanity check
const string errorMessage = "DateTimeUtils.GetIntervalIntersection - argument can not be null";
if (testInterval == null)
{
throw new ArgumentNullException("testInterval", errorMessage);
}
if (allowedInterval == null)
{
throw new ArgumentNullException("allowedInterval", errorMessage);
}
if (testInterval.From == null || testInterval.To == null || allowedInterval.From == null || allowedInterval.To == null)
{
throw new ArgumentException("DateTimeUtils.GetIntervalIntersection - argument can not be null");
}
#endregion sanity check
//Is testInterval totally outside the allowedInterval?
if (testInterval.From.Value < allowedInterval.From.Value && testInterval.To.Value < allowedInterval.From.Value
|| testInterval.From.Value > allowedInterval.To.Value && testInterval.To.Value > allowedInterval.To.Value)
{
return new DateTimeInterval();
}
DateTime from = testInterval.From < allowedInterval.From
? allowedInterval.From.Value
: testInterval.From.Value;
DateTime to = testInterval.To > allowedInterval.To
? allowedInterval.To.Value
: testInterval.To.Value;
var result = new DateTimeInterval
{
From = from,
To = to
};
return result;
}
public static double? GetIntervalDuration(DateTimeInterval interval)
{
if (interval.To == null || interval.From == null)
{
return null;
}
TimeSpan? difference = interval.To.Value.Date - interval.From.Value.Date;
double days = Math.Floor(difference.Value.TotalDays + 1);
return days;
}
}
}
| mit | C# | |
4e99b6778b8ee185e53263c366d1136f60728cb2 | Add a dynamic data loading sample | migueldeicaza/MonoTouch.Dialog,newky2k/MonoTouch.Dialog,benoitjadinon/MonoTouch.Dialog,hisystems/MonoTouch.Dialog,jstedfast/MonoTouch.Dialog,Milan1992/MonoTouch.Dialog,danmiser/MonoTouch.Dialog,ClusterReplyBUS/MonoTouch.Dialog | Sample/DemoDynamic.cs | Sample/DemoDynamic.cs | using System;
using System.Net;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using MonoTouch.UIKit;
using MonoTouch.Dialog;
namespace Sample
{
public partial class AppDelegate
{
DialogViewController dynamic;
AccountInfo account;
class AccountInfo {
[Section ("Twitter credentials", "This sample loads various information\nsources dynamically from your twitter\naccount.")]
[Entry ("Enter your login name")]
public string Username;
[Password ("Enter your password")]
public string Password;
[Section ("Tap to fetch the timeline")]
[OnTap ("FetchTweets")]
public string Login;
}
static void SetBusy (bool activity)
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = activity;
}
public void FetchTweets ()
{
SetBusy (true);
var request = (HttpWebRequest)WebRequest.Create ("http://twitter.com/statuses/friends_timeline.xml");
request.Credentials = new NetworkCredential (account.Username, account.Password);
request.BeginGetResponse (TimeLineLoaded, request);
}
// Creates the dynamic content from the twitter results
RootElement CreateDynamicContent (XDocument doc)
{
var users = doc.XPathSelectElements ("./statuses/status/user").ToArray ();
var texts = doc.XPathSelectElements ("./statuses/status/text").Select (x=>x.Value).ToArray ();
var people = doc.XPathSelectElements ("./statuses/status/user/name").Select (x=>x.Value).ToArray ();
var section = new Section ();
var root = new RootElement ("Tweets") { section };
for (int i = 0; i < people.Length; i++){
var line = new RootElement (people [i]) {
new Section ("Profile"){
new StringElement ("Screen name", users [i].XPathSelectElement ("./screen_name").Value),
new StringElement ("Name", people [i]),
new StringElement ("Followers:", users [i].XPathSelectElement ("./followers_count").Value)
},
new Section ("Tweet"){
new StringElement (texts [i])
}
};
section.Add (line);
}
return root;
}
void TimeLineLoaded (IAsyncResult result)
{
var request = result.AsyncState as HttpWebRequest;
try {
var response = request.EndGetResponse (result);
var stream = response.GetResponseStream ();
SetBusy (false);
var root = CreateDynamicContent (XDocument.Load (new XmlTextReader (stream)));
InvokeOnMainThread (delegate {
var tweetVC = new DialogViewController (root, true);
navigation.PushViewController (tweetVC, true);
});
} catch (WebException e){
InvokeOnMainThread (delegate {
using (var msg = new UIAlertView ("Error", "Code: " + e.Status, null, "Ok")){
msg.Show ();
}
});
}
}
public void DemoDynamic ()
{
account = new AccountInfo ();
var bc = new BindingContext (this, account, "Settings");
if (dynamic != null)
dynamic.Dispose ();
dynamic = new DialogViewController (bc.Root, true);
navigation.PushViewController (dynamic, true);
}
}
}
| mit | C# | |
f2715249c5b7c06c5097d264dd3a3ec9ea49fe48 | Add function proxy delegates. | SaxxonPike/NextLevelSeven | NextLevelSeven/Core/ProxyDelegates.cs | NextLevelSeven/Core/ProxyDelegates.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NextLevelSeven.Core
{
/// <summary>
/// Represents a proxy that gets a property using an index.
/// </summary>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <returns>Property value.</returns>
internal delegate TValue IndexedProxyGetter<out TValue>(int index);
/// <summary>
/// Represents a proxy that gets a property using an index.
/// </summary>
/// <typeparam name="TKey">Type of key.</typeparam>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <returns>Property value.</returns>
internal delegate TValue IndexedProxyGetter<in TKey, out TValue>(TKey index);
/// <summary>
/// Represents a proxy that sets a property using an index.
/// </summary>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <param name="value">New value.</param>
internal delegate void IndexedProxySetter<in TValue>(int index, TValue value);
/// <summary>
/// Represents a proxy that sets a property using an index.
/// </summary>
/// <typeparam name="TKey">Type of key.</typeparam>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <param name="value">New value.</param>
internal delegate void IndexedProxySetter<in TKey, in TValue>(TKey index, TValue value);
/// <summary>
/// Represents a proxy that is triggered when a value attempts to change.
/// </summary>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <param name="oldValue">Old value.</param>
/// <param name="newValue">New value.</param>
internal delegate void ProxyChangePendingNotifier<in TValue>(TValue oldValue, TValue newValue);
/// <summary>
/// Represents a proxy that gets a property.
/// </summary>
/// <typeparam name="TInput">Input type.</typeparam>
/// <typeparam name="TOutput">Output type.</typeparam>
/// <param name="value">Input value.</param>
/// <returns>Converted value.</returns>
internal delegate TOutput ProxyConverter<in TInput, out TOutput>(TInput value);
/// <summary>
/// Represents a proxy that gets a property.
/// </summary>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <returns>Property value.</returns>
internal delegate TValue ProxyGetter<out TValue>();
/// <summary>
/// Represents a proxy that sets a property.
/// </summary>
/// <typeparam name="TValue">Type of value.</typeparam>
/// <param name="value">New value.</param>
internal delegate void ProxySetter<in TValue>(TValue value);
}
| isc | C# | |
a3856c92fe8445e6fd54686b2b3e94567ea9fd85 | Add C# | alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year,alihesari/Happy-New-Year | happy-new-year.cs | happy-new-year.cs | //Happy New Year in C#
class HappyNewYear
{
static void Main()
{
System.Console.WriteLine("Happy New Year");
}
} | mit | C# | |
88fb7af604eff9e701d1dfe08218ccea796d96a1 | Fix in CatalogStrategy | repometric/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli | src/cli/Strategy/CatalogStrategy.cs | src/cli/Strategy/CatalogStrategy.cs | namespace Linterhub.Cli.Strategy
{
using System;
using System.IO;
using System.Linq;
using Linterhub.Cli.Runtime;
using Linterhub.Engine;
using Linterhub.Engine.Exceptions;
using Linterhub.Engine.Extensions;
using Linterhub.Engine.Linters;
public class CatalogStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine)
{
var catalog = GetCatalog(context, engine);
var result = engine.Factory.GetRecords().Select(x => new
{
name = x.Name,
languages = catalog.linters.FirstOrDefault(y => y.name == x.Name)?.languages
}).OrderBy(x => x.name);
return result;
}
private Linters GetCatalog(RunContext context, LinterEngine engine)
{
try
{
return false
? context.Input.DeserializeAsJson<Linters>()
: new LinterhubWrapper(context, engine).Info().DeserializeAsJson<Linters>();
}
catch (Exception exception)
{
throw new LinterParseException(exception);
}
}
}
} | namespace Linterhub.Cli.Strategy
{
using System;
using System.IO;
using System.Linq;
using Linterhub.Cli.Runtime;
using Linterhub.Engine;
using Linterhub.Engine.Exceptions;
using Linterhub.Engine.Extensions;
using Linterhub.Engine.Linters;
public class CatalogStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine)
{
var catalog = GetCatalog(context, engine);
var result = engine.Factory.GetRecords().Select(x => new
{
name = x.Name,
languages = catalog.linters.FirstOrDefault(y => y.name == x.Name)?.languages
}).OrderBy(x => x.name);
return result;
}
private Linters GetCatalog(RunContext context, LinterEngine engine)
{
try
{
return context.InputAwailable
? context.Input.DeserializeAsJson<Linters>()
: new LinterhubWrapper(context, engine).Info().DeserializeAsJson<Linters>();
}
catch (Exception exception)
{
throw new LinterParseException(exception);
}
}
}
} | mit | C# |
960f22d3cda859a286c170245cbacebc4b3710b8 | Add new service class | nqdien/littleaspnetcorebook,nqdien/littleaspnetcorebook | Services/TodoItemService.cs | Services/TodoItemService.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Data;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public class TodoItemService : ITodoItemService
{
private readonly ApplicationDbContext _context;
public TodoItemService(ApplicationDbContext context)
{
_context = context;
}
public async Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync()
{
}
}
} | apache-2.0 | C# | |
a6290af0371812adea6a7434962c0b0eb741f9e2 | Add type check tests | WorkMaze/JUST.net | UnitTests/TypeCheckTests.cs | UnitTests/TypeCheckTests.cs | using NUnit.Framework;
namespace JUST.UnitTests
{
[TestFixture, Category("Type"), Category("TypeCheck")]
public class TypeCheckTests
{
[TestCase("0", true)]
[TestCase("1.23", true)]
[TestCase("true", false)]
[TestCase("\"abc\"", false)]
[TestCase("[ \"abc\", \"xyz\" ]", false)]
public void IsNumber(string typedValue, bool expectedResult)
{
var input = $"{{ \"value\": {typedValue} }}";
var transformer = "{ \"result\": \"#isnumber(#valueof($.value))\" }";
var context = new JUSTContext
{
EvaluationMode = EvaluationMode.Strict
};
var result = new JsonTransformer(context).Transform(transformer, input);
Assert.AreEqual($"{{\"result\":{expectedResult.ToString().ToLower()}}}", result);
}
[TestCase("0", false)]
[TestCase("1.23", false)]
[TestCase("true", true)]
[TestCase("\"abc\"", false)]
[TestCase("[ \"abc\", \"xyz\" ]", false)]
public void IsBoolean(string typedValue, bool expectedResult)
{
var input = $"{{ \"value\": {typedValue} }}";
var transformer = "{ \"result\": \"#isboolean(#valueof($.value))\" }";
var context = new JUSTContext
{
EvaluationMode = EvaluationMode.Strict
};
var result = new JsonTransformer(context).Transform(transformer, input);
Assert.AreEqual($"{{\"result\":{expectedResult.ToString().ToLower()}}}", result);
}
[TestCase("0", false)]
[TestCase("1.23", false)]
[TestCase("true", false)]
[TestCase("\"abc\"", true)]
[TestCase("[ \"abc\", \"xyz\" ]", false)]
public void IsString(string typedValue, bool expectedResult)
{
var input = $"{{ \"value\": {typedValue} }}";
var transformer = "{ \"result\": \"#isstring(#valueof($.value))\" }";
var context = new JUSTContext
{
EvaluationMode = EvaluationMode.Strict
};
var result = new JsonTransformer(context).Transform(transformer, input);
Assert.AreEqual($"{{\"result\":{expectedResult.ToString().ToLower()}}}", result);
}
[TestCase("0", false)]
[TestCase("1.23", false)]
[TestCase("true", false)]
[TestCase("\"abc\"", false)]
[TestCase("[ \"abc\", \"xyz\" ]", true)]
public void IsArray(string typedValue, bool expectedResult)
{
var input = $"{{ \"value\": {typedValue} }}";
var transformer = "{ \"result\": \"#isarray(#valueof($.value))\" }";
var context = new JUSTContext
{
EvaluationMode = EvaluationMode.Strict
};
var result = new JsonTransformer(context).Transform(transformer, input);
Assert.AreEqual($"{{\"result\":{expectedResult.ToString().ToLower()}}}", result);
}
}
}
| mit | C# | |
9a3d13d038d108c2df4426a21bb50a43470303f4 | Convert to new Visual Studio project types | SimControl/SimControl.Reactive | SimControl.TestUtils.Tests/GlobalSuppressions.cs | SimControl.TestUtils.Tests/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("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>", Scope = "member", Target = "~M:SimControl.TestUtils.Tests.DisposableTestAdapterTests.DisposableTestAdapter__CreateAndDispose__succeeds")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>", Scope = "member", Target = "~M:SimControl.TestUtils.Tests.TempFilesTestAdapterTests.Create_temp_file__create_TempFilesTestAdapter__temp_file_is_deleted")] | mit | C# | |
740e16319c90a0409c8cadcd614825339ad45f7a | Write the ErrorLog into the exe's directory. | gregory-diaz/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,tellingmachine/MatterControl,ddpruitt/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,CodeMangler/MatterControl,mmoening/MatterControl,jlewin/MatterControl,MatterHackers/MatterControl,rytz/MatterControl,ddpruitt/MatterControl,unlimitedbacon/MatterControl,CodeMangler/MatterControl,larsbrubaker/MatterControl,CodeMangler/MatterControl,gregory-diaz/MatterControl,mmoening/MatterControl,tellingmachine/MatterControl,rytz/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,rytz/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,ddpruitt/MatterControl,MatterHackers/MatterControl,jlewin/MatterControl,MatterHackers/MatterControl | Testing/TestingDispatch.cs | Testing/TestingDispatch.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace MatterHackers.MatterControl.Testing
{
public class TestingDispatch
{
string errorLogFileName = null;
public TestingDispatch()
{
string exePath = Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
errorLogFileName = Path.Combine(exePath, "ErrorLog.txt");
string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now);
using (StreamWriter file = new StreamWriter(errorLogFileName))
{
file.WriteLine(firstLine);
}
}
public void RunTests(string[] testCommands)
{
try { ReleaseTests.AssertDebugNotDefined(); }
catch (Exception e) { DumpException(e); }
try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); }
catch (Exception e) { DumpException(e); }
}
void DumpException(Exception e)
{
using (StreamWriter w = File.AppendText(errorLogFileName))
{
w.WriteLine(e.Message);
w.Write(e.StackTrace);
w.WriteLine();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace MatterHackers.MatterControl.Testing
{
public class TestingDispatch
{
string errorLogFileName = null;
public TestingDispatch()
{
errorLogFileName = "ErrorLog.txt";
string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now);
using (StreamWriter file = new StreamWriter(errorLogFileName))
{
file.WriteLine(errorLogFileName, firstLine);
}
}
public void RunTests(string[] testCommands)
{
try { ReleaseTests.AssertDebugNotDefined(); }
catch (Exception e) { DumpException(e); }
try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); }
catch (Exception e) { DumpException(e); }
}
void DumpException(Exception e)
{
using (StreamWriter w = File.AppendText(errorLogFileName))
{
w.WriteLine(e.Message);
w.Write(e.StackTrace);
w.WriteLine();
}
}
}
}
| bsd-2-clause | C# |
e500e35a320446738ef53a188409117218987aaf | Revert the Quickstart file which is deleted by mistake | jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | jobs/api/QuickStart/QuickStart.cs | jobs/api/QuickStart/QuickStart.cs | /*
* Copyright (c) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
// [START quickstart]
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
// Imports the Google Cloud Job Discovery client library
using Google.Apis.JobService.v2;
using Google.Apis.JobService.v2.Data;
using System.Linq;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Authorize the client using Application Default Credentials.
// See: https://developers.google.com/identity/protocols/application-default-credentials
GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
// Specify the Service scope.
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped(new[]
{
Google.Apis.JobService.v2.JobServiceService.Scope.Jobs
});
}
// Instantiate the Cloud Key Management Service API.
JobServiceService jobServiceClient = new JobServiceService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
GZipEnabled = false
});
// List companies.
ListCompaniesResponse result = jobServiceClient.Companies.List().Execute();
Console.WriteLine("Request Id: " + result.Metadata.RequestId);
if (result.Companies != null)
{
Console.WriteLine("Companies: ");
result.Companies.ToList().ForEach(company => Console.WriteLine(company.Name));
}
else { Console.WriteLine("No companies found."); }
}
}
}
// [END quickstart] | apache-2.0 | C# | |
96fe2a60f4be85dbeb5e287944ece6be6c1ab03c | Add Paeth tests. Fixes #10. | bojanrajkovic/pingu | src/Pingu.Tests/PaethTests.cs | src/Pingu.Tests/PaethTests.cs | using System.Collections.Generic;
using Xunit;
using Pingu.Filters;
namespace Pingu.Tests
{
public class PaethFilterTests
{
public static IEnumerable<object[]> PaethFilterTestVectors()
{
unchecked {
yield return new object[] {
new byte [] { 10, 22, 47, 91, 106, 82, 28, 111 },
new byte [] { 91, 34, 18, 211, 235, 111, 9, 255 },
new byte [] { 81, 12, 227, 120, 129, 29, 247, 44 },
4
};
yield return new object[] {
null,
new byte [] { 91, 34, 18, 211, 235, 111, 9, 255 },
new byte [] { 91, 34, 18, 211, 144, 77, 247, 44 },
4
};
yield return new object[] {
new byte [] { 10, 22, 47, 91, 106, 82, 28, 111, 23, 43, 99, 101, 12 },
new byte [] { 91, 34, 18, 211, 235, 111, 9, 255, 34, 191, 54, 91, 233 },
new byte [] { 81, 12, 227, 120, 129, 29, 247, 44, 184, 109, 211, 92, 210 },
4
};
}
}
[Theory]
[MemberData(nameof(PaethFilterTestVectors))]
public void Can_filter_correctly(byte[] previous, byte[] current, byte[] expected, int bytesPerPixel)
{
var filter = PaethFilter.Instance;
var filteredScanline = new byte[expected.Length];
filter.FilterInto(filteredScanline, 0, current, previous, bytesPerPixel);
Assert.Equal(expected, filteredScanline);
}
}
}
| mit | C# | |
59e0c2775320a6fdebbc7af4c09d45ee32852931 | Add the EthernetFrame class missing from last commit | eyecreate/tapcfg,zhanleewo/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,zhanleewo/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg,juhovh/tapcfg | src/bindings/EthernetFrame.cs | src/bindings/EthernetFrame.cs |
namespace TAPCfg {
public class EthernetFrame {
private byte[] data;
public EthernetFrame(byte[] data) {
this.data = data;
}
public byte[] Data {
get {
return data;
}
}
}
}
| lgpl-2.1 | C# | |
f470eeeb942fbe75b00f570552c2834e2b9556cb | Test for SetEnvelopeName extension | pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,Microsoft/ApplicationInsights-dotnet | BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/Extensibility/Implementation/TelemetryExtensionsTests.cs | BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/Extensibility/Implementation/TelemetryExtensionsTests.cs | namespace Microsoft.ApplicationInsights.Extensibility.Implementation
{
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
[TestClass]
public class TelemetryExtensionsTests
{
class NonSerializableTelemetry : ITelemetry
{
public DateTimeOffset Timestamp { get; set; }
public TelemetryContext Context { get; set; }
public IExtension Extension { get; set; }
public string Sequence { get; set; }
public ITelemetry DeepClone()
{
return new NonSerializableTelemetry();
}
public void Sanitize()
{}
public void SerializeData(ISerializationWriter serializationWriter)
{}
}
[TestMethod]
public static void CanSetEnvelopeNameForSupportedTypes()
{
string testEnvelopeName = "Non_Standard*Envelope.Name";
var at = new AvailabilityTelemetry();
var dt = new DependencyTelemetry();
var et = new EventTelemetry();
var ext = new ExceptionTelemetry();
var mt = new MetricTelemetry();
var pvpt = new PageViewPerformanceTelemetry();
var pvt = new PageViewTelemetry();
var rt = new RequestTelemetry();
#pragma warning disable CS0618 // Type or member is obsolete
var pct = new PerformanceCounterTelemetry();
var sst = new SessionStateTelemetry();
#pragma warning restore CS0618 // Type or member is obsolete
at.SetEnvelopeName(testEnvelopeName);
dt.SetEnvelopeName(testEnvelopeName);
et.SetEnvelopeName(testEnvelopeName);
ext.SetEnvelopeName(testEnvelopeName);
mt.SetEnvelopeName(testEnvelopeName);
pvpt.SetEnvelopeName(testEnvelopeName);
pvt.SetEnvelopeName(testEnvelopeName);
rt.SetEnvelopeName(testEnvelopeName);
pct.SetEnvelopeName(testEnvelopeName);
sst.SetEnvelopeName(testEnvelopeName);
Assert.AreEqual(testEnvelopeName, at.EnvelopeName);
Assert.AreEqual(testEnvelopeName, dt.EnvelopeName);
Assert.AreEqual(testEnvelopeName, et.EnvelopeName);
Assert.AreEqual(testEnvelopeName, ext.EnvelopeName);
Assert.AreEqual(testEnvelopeName, mt.EnvelopeName);
Assert.AreEqual(testEnvelopeName, pvpt.EnvelopeName);
Assert.AreEqual(testEnvelopeName, pvt.EnvelopeName);
Assert.AreEqual(testEnvelopeName, rt.EnvelopeName);
Assert.AreEqual(testEnvelopeName, pct.Data.EnvelopeName);
Assert.AreEqual(testEnvelopeName, sst.Data.EnvelopeName);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public static void SetEnvelopeNameThrowsForUnsupportedTypes()
{
var nst = new NonSerializableTelemetry();
nst.SetEnvelopeName("Any"); // Throws, NonSerializableTelemetry does not implement IAiSerializableTelemetry
}
}
}
| mit | C# | |
45d6b2f7835962a24d688efca81eb1dfec1398fe | Add ReflectionParameter class stub | peachpiecompiler/peachpie,peachpiecompiler/peachpie,iolevel/peachpie-concept,iolevel/peachpie,peachpiecompiler/peachpie,iolevel/peachpie-concept,iolevel/peachpie,iolevel/peachpie-concept,iolevel/peachpie | src/Peachpie.Library/Reflection/ReflectionParameter.cs | src/Peachpie.Library/Reflection/ReflectionParameter.cs | using System;
using System.Collections.Generic;
using System.Text;
using Pchp.Core;
namespace Pchp.Library.Reflection
{
[PhpType("[name]"), PhpExtension(ReflectionUtils.ExtensionName)]
public class ReflectionParameter : Reflector
{
public string __toString()
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# | |
2591b65a52dec18f8e97339145866622bf617ee6 | Create LeBlenderGriddEditorParser.cs | dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu | Source/Our.Umbraco.Nexu.Parsers/GridEditorParsers/Core/LeBlenderGriddEditorParser.cs | Source/Our.Umbraco.Nexu.Parsers/GridEditorParsers/Core/LeBlenderGriddEditorParser.cs | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Our.Umbraco.Nexu.Core.Interfaces;
using Our.Umbraco.Nexu.Core.Models;
using System.Collections.Generic;
using System.Linq;
using global::Umbraco.Core;
using global::Umbraco.Web;
using log4net;
using System;
namespace Our.Umbraco.Nexu.Parsers.GridEditorParsers.Core
{
public class LeBlenderGridEditorParser : IGridEditorParser
{
private static readonly ILog Log = LogManager.GetLogger("SYP.Umbraco");
public bool IsParserFor(string editorview)
{
return editorview.Equals("/App_Plugins/LeBlender/editors/leblendereditor/LeBlendereditor.html");
}
public IEnumerable<ILinkedEntity> GetLinkedEntities(string value)
{
if (string.IsNullOrEmpty(value))
{
return Enumerable.Empty<ILinkedEntity>();
}
var linkedEntities = new List<ILinkedEntity>();
try
{
var jsonValue = JsonConvert.DeserializeObject<JArray>(value);
///get any value that's a udi
var props = jsonValue.Descendants().OfType<JProperty>().Where(p => p.Name == "value" && p.Value.ToString().StartsWith("umb://")).ToList();
var contentService = ApplicationContext.Current.Services.ContentService;
var mediaService = ApplicationContext.Current.Services.MediaService;
foreach (JProperty property in props)
{
var propvalue = property.Value.ToString();
var guidUdi = Udi.Parse(propvalue) as GuidUdi;
if (guidUdi != null)
{
if (propvalue.StartsWith("umb://document/"))
{
var node = contentService.GetById(guidUdi.Guid);
if (node != null)
{
linkedEntities.Add(new LinkedDocumentEntity(node.Id));
Log.Info(String.Concat("NEXU: Add Linked Document with id ", node.Id));
}
}
else if (propvalue.StartsWith("umb://media/"))
{
var media = mediaService.GetById(guidUdi.Guid);
if (media != null)
{
linkedEntities.Add(new LinkedMediaEntity(media.Id));
Log.Info(String.Concat("NEXU: Add Linked Media with id ", media.Id));
}
}
}
}
}
catch (Exception e)
{
Log.Info(String.Concat(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e.Message));
}
return linkedEntities;
}
}
}
| mit | C# | |
1259389dda076aa150d4a9b17ff77cb4739db453 | add book test integration | hirohito-protagonist/dotnet-core-rest | test/BooksLibrary/Tests/Integration/BooksTest.cs | test/BooksLibrary/Tests/Integration/BooksTest.cs | using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
using Xunit;
using BooksLibrary.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
namespace BooksLibrary.Tests.Integration
{
public class BooksIntegrationTest : IntegrationTestsBase<Startup>
{
private void AddRequestIpLimitHeaders(HttpRequestMessage request)
{
var clientId = "cl-key-b";
var ip = "::1";
request.Headers.Add("X-ClientId", clientId);
request.Headers.Add("X-Real-IP", ip);
}
private async Task<AuthorDto> CreateDummyAuthor()
{
var content = new StringContent(JsonConvert.SerializeObject(new AuthorCreationDto()),
Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "api/authors");
request.Content = content;
this.AddRequestIpLimitHeaders(request);
var response = await this.Client.SendAsync(request);
string rawAuthor = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AuthorDto>(rawAuthor);
}
private async Task<BookDto> CreateDummyBookForAuthor(Guid authorId)
{
var content = new StringContent(JsonConvert.SerializeObject(new BookManipulationDto()
{
Title = "test",
Description = "test"
}), Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "api/authors/" + authorId + "/books");
request.Content = content;
this.AddRequestIpLimitHeaders(request);
var response = await this.Client.SendAsync(request);
string rawBook = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<BookDto>(rawBook);
}
[Fact(DisplayName = "it should return collection of books for author")]
public async void TestGetBooks()
{
var author = await CreateDummyAuthor();
var book1 = await CreateDummyBookForAuthor(author.Id);
var book2 = await CreateDummyBookForAuthor(author.Id);
var request = new HttpRequestMessage(HttpMethod.Get, "api/authors/" + author.Id + "/books");
this.AddRequestIpLimitHeaders(request);
var response = await this.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
string raw = await response.Content.ReadAsStringAsync();
List<BookDto> outputModel = JsonConvert.DeserializeObject<List<BookDto>>(raw);
Assert.Equal(2, outputModel.Count);
}
}
}
| unlicense | C# | |
0867b61e3858fbee3265e74a42e1ff11e3140de4 | Use correct base class. | eatskolnikov/mobile,masterrr/mobile,peeedge/mobile,eatskolnikov/mobile,masterrr/mobile,eatskolnikov/mobile,peeedge/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile | Joey/UI/Fragments/EditCurrentTimeEntryFragment.cs | Joey/UI/Fragments/EditCurrentTimeEntryFragment.cs | using System;
using System.ComponentModel;
using Android.OS;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Data.Models;
using XPlatUtils;
using Fragment = Android.Support.V4.App.Fragment;
namespace Toggl.Joey.UI.Fragments
{
public class EditCurrentTimeEntryFragment : BaseEditTimeEntryFragment
{
private ActiveTimeEntryManager timeEntryManager;
public EditCurrentTimeEntryFragment ()
{
}
public EditCurrentTimeEntryFragment (IntPtr jref, Android.Runtime.JniHandleOwnership xfer) : base (jref, xfer)
{
}
private void OnTimeEntryManagerPropertyChanged (object sender, PropertyChangedEventArgs args)
{
if (Handle == IntPtr.Zero)
return;
if (args.PropertyName == ActiveTimeEntryManager.PropertyActive) {
ResetModel ();
}
}
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
if (timeEntryManager == null) {
timeEntryManager = ServiceContainer.Resolve<ActiveTimeEntryManager> ();
timeEntryManager.PropertyChanged += OnTimeEntryManagerPropertyChanged;
}
ResetModel ();
}
public override void OnDestroy ()
{
if (timeEntryManager != null) {
timeEntryManager.PropertyChanged -= OnTimeEntryManagerPropertyChanged;
timeEntryManager = null;
}
base.OnDestroy ();
}
protected override void ResetModel ()
{
if (timeEntryManager.Active == null) {
TimeEntry = null;
} else {
TimeEntry = new TimeEntryModel (timeEntryManager.Active);
}
}
}
}
| using System;
using System.ComponentModel;
using Android.OS;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Data.Models;
using XPlatUtils;
using Fragment = Android.Support.V4.App.Fragment;
namespace Toggl.Joey.UI.Fragments
{
public class EditCurrentTimeEntryFragment : EditTimeEntryFragment
{
private ActiveTimeEntryManager timeEntryManager;
public EditCurrentTimeEntryFragment ()
{
}
public EditCurrentTimeEntryFragment (IntPtr jref, Android.Runtime.JniHandleOwnership xfer) : base (jref, xfer)
{
}
private void OnTimeEntryManagerPropertyChanged (object sender, PropertyChangedEventArgs args)
{
if (Handle == IntPtr.Zero)
return;
if (args.PropertyName == ActiveTimeEntryManager.PropertyActive) {
ResetModel ();
}
}
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
if (timeEntryManager == null) {
timeEntryManager = ServiceContainer.Resolve<ActiveTimeEntryManager> ();
timeEntryManager.PropertyChanged += OnTimeEntryManagerPropertyChanged;
}
ResetModel ();
}
public override void OnDestroy ()
{
if (timeEntryManager != null) {
timeEntryManager.PropertyChanged -= OnTimeEntryManagerPropertyChanged;
timeEntryManager = null;
}
base.OnDestroy ();
}
protected override void ResetModel ()
{
if (timeEntryManager.Active == null) {
TimeEntry = null;
} else {
TimeEntry = new TimeEntryModel (timeEntryManager.Active);
}
}
}
}
| bsd-3-clause | C# |
5f5fb3e47f69ac2923187a69ebf381fe0e3e1690 | Add code to allow azure functions to force async on | stackify/stackify-api-dotnet,stackify/stackify-api-dotnet,stackify/stackify-api-dotnet | Src/StackifyLib/Utils/AsyncTracer.cs | Src/StackifyLib/Utils/AsyncTracer.cs | #if NET45 || NET451
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
namespace StackifyLib.Utils
{
public class AsyncTracer
{
private static bool _AsyncTracerEnabled = false;
private static DateTime _LastEnabledTest = DateTime.MinValue;
public static bool EnsureAsyncTracer()
{
if (_AsyncTracerEnabled)
return _AsyncTracerEnabled;
if (_LastEnabledTest > DateTime.UtcNow.AddMinutes(-5))
{
return _AsyncTracerEnabled;
}
try
{
var t = Type.GetType("System.Threading.Tasks.AsyncCausalityTracer");
if (t != null)
{
var field = t.GetField("f_LoggingOn", BindingFlags.NonPublic | BindingFlags.Static);
if (field == null)
{
StackifyLib.Utils.StackifyAPILogger.Log("Unable to enable the AsyncCausalityTracer, f_LoggingOn field not found");
return _AsyncTracerEnabled;
}
if (field.FieldType.Name == "Boolean")
{
bool current = (bool)field.GetValue(null);
if (!current)
{
field.SetValue(null, true);
}
}
else
{
field.SetValue(null, (byte)4);
}
_AsyncTracerEnabled = true;
}
else
{
_AsyncTracerEnabled = true; //never going to work.
StackifyLib.Utils.StackifyAPILogger.Log("Unable to enable the AsyncCausalityTracer, class not found");
}
}
catch (Exception ex)
{
StackifyLib.Utils.StackifyAPILogger.Log("EnsureAsyncTracer Exception: " + ex.ToString());
Debug.WriteLine(ex);
}
_LastEnabledTest = DateTime.UtcNow;
return _AsyncTracerEnabled;
}
}
}
#endif | apache-2.0 | C# | |
66aac15f4ccb660e93d80628448bfe6eedf63d84 | add methods for add/get/delete favorites | lighthorseinnovation/TableauAPI | TableauAPI/RESTRequests/Favorites.cs | TableauAPI/RESTRequests/Favorites.cs | using System.Xml;
using TableauAPI.FilesLogging;
using TableauAPI.RESTHelpers;
using TableauAPI.ServerData;
namespace TableauAPI.RESTRequests
{
public class Favorites : TableauServerSignedInRequestBase
{
private readonly TableauServerUrls _onlineUrls;
/// <summary>
/// Work with a user's favorites
/// </summary>
/// <param name="onlineUrls">Tableau Server Information</param>
/// <param name="logInInfo">Tableau Sign In Information</param>
public Favorites(TableauServerUrls onlineUrls, TableauServerSignIn logInInfo)
: base(logInInfo)
{
_onlineUrls = onlineUrls;
}
/// <summary>
/// Adds the specified workbook to a user's favorites.
/// </summary>
/// <param name="favoriteLabel">A label to assign to the favorite. This value is displayed when you search for favorites on the server. If the label is already in use for another workbook, an error is returned.</param>
/// <param name="workbookId">The ID (not name) of the workbook to add as a favorite.</param>
/// <returns></returns>
public void AddWorkbookToFavorites(string favoriteLabel, string workbookId)
{
var url = _onlineUrls.Url_AddWorkbookToFavorites(OnlineSession);
var webRequest = CreateLoggedInWebRequest(url);
webRequest.Method = "PUT";
var response = GetWebResponseLogErrors(webRequest, "add workbook to favorites");
}
/// <summary>
/// Deletes a workbook from a user's favorites. If the specified workbook is not a favorite of the specified user, this call has no effect.
/// </summary>
/// <param name="workbookId">The ID of the workbook to remove from the user's favorites.</param>
/// <returns></returns>
public void DeleteWorkbookFromFavorites(string workbookId)
{
var url = _onlineUrls.Url_DeleteWorkbookFromFavorites(workbookId, OnlineSession);
var webRequest = CreateLoggedInWebRequest(url);
webRequest.Method = "DELETE";
var response = GetWebResponseLogErrors(webRequest, "delete workbook from favorites");
}
/// <summary>
/// Returns a list of favorite projects, data sources, views, workbooks, and flows for a user.
/// </summary>
/// <param name="workbookId">The ID of the workbook to remove from the user's favorites.</param>
/// <returns></returns>
public void GetFavoritesForUser(string workbookId)
{
var url = _onlineUrls.Url_GetFavoritesForUser(OnlineSession);
var webRequest = CreateLoggedInWebRequest(url);
webRequest.Method = "GET";
var response = GetWebResponseLogErrors(webRequest, "get favorites for user");
}
}
}
| mit | C# | |
4cefb059ac7fc7a368cce22ed6ce346b921e29f4 | Add ChaosMonkey util | Spreads/Spreads | src/Spreads.Core/ChaosMonkey.cs | src/Spreads.Core/ChaosMonkey.cs | using System;
using System.Diagnostics;
using System.Threading;
namespace Spreads {
/// <summary>
/// When CHAOS_MONKEY conditional-compilation directive is set,
/// calling the methods will raise an error with a given probability
/// </summary>
public static class ChaosMonkey {
[ThreadStatic]
private static Random _rng;
[Conditional("CHAOS_MONKEY")]
public static void OutOfMemory(double probability = 0.1) {
if (probability == 0.0) return;
if (_rng == null) _rng = new Random();
if (_rng.NextDouble() > probability) return;
throw new OutOfMemoryException();
//var list = new List<List<long>>();
//try {
// while (true) {
// list.Add(new List<long>(int.MaxValue));
// }
//} catch (OutOfMemoryException ooex) {
// throw;
//}
}
[Conditional("CHAOS_MONKEY")]
public static void StackOverFlow(double probability = 0.1) {
if (probability == 0.0) return;
if (_rng == null) _rng = new Random();
if (_rng.NextDouble() > probability) return;
throw new StackOverflowException();
}
[Conditional("CHAOS_MONKEY")]
public static void ThreadAbort(double probability = 0.1) {
if (probability == 0.0) return;
if (_rng == null) _rng = new Random();
if (_rng.NextDouble() > probability) return;
Thread.CurrentThread.Abort();
}
[Conditional("CHAOS_MONKEY")]
public static void Chaos(double probability = 0.1) {
if (probability == 0.0) return;
if (_rng == null) _rng = new Random();
var rn = _rng.NextDouble();
if (rn > probability) return;
if (rn < probability / 3.0) {
throw new OutOfMemoryException();
}
if (rn < probability * 2.0 / 3.0) {
throw new StackOverflowException();
}
Thread.CurrentThread.Abort();
}
}
}
| mpl-2.0 | C# | |
8e3f39c497bbde9c9c44c0e531ff42beb12f51c6 | Add gambling stump | Daniele122898/SoraBot-v2,Daniele122898/SoraBot-v2 | SoraBot/SoraBot.Bot/Modules/GamblingModule.cs | SoraBot/SoraBot.Bot/Modules/GamblingModule.cs | using Discord.Commands;
using SoraBot.Common.Extensions.Modules;
namespace SoraBot.Bot.Modules
{
[Name("Gambling")]
[Summary("All commands around gambling and loosing all your Sora Coins ;)")]
public class GamblingModule : SoraSocketCommandModule
{
}
} | agpl-3.0 | C# | |
420dd23218b5cb43c1e141a997a7ef0c88ac2991 | Create ReferencePointShapeView.xaml.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D/Views/Shapes/ReferencePointShapeView.xaml.cs | src/Draw2D/Views/Shapes/ReferencePointShapeView.xaml.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Draw2D.Views.Shapes
{
public class ReferencePointShapeView : UserControl
{
public ReferencePointShapeView()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| mit | C# | |
a92e5ec40d5b7f9e2dbdd6c44e836fd53fe41b9b | Create ZeroGRotation.cs | scmcom/unitycode | ZeroGRotation.cs | ZeroGRotation.cs | //==========================================================
// defines 3D zero gravity physics per MOUSE input
// MOUSE INPUTS - CHANGE SPIN / ROTATIONAL MOMENTUM VECTOR
//
// mouse around viewscreen || VR look input
// looking around via mouse
// OR
// VR HMD - oculus, carboard, etc
//==========================================================
using UnityEngine;
using System.Collections;
public class ZeroGravityRotation : MonoBehaviour {
//public variables for mouse inputs
public string verticalAxisName = "Mouse Y";
public string horizontalAxisName = "Mouse X";
//programmer interface - define force amount
public float force = 10.0f;
public ForceMode forceMode;
// Use this for initialization
void Start () {}
//FixedUpdate for physics
void FixedUpdate (){
//adding torque to force scalar
GetComponent<Rigidbody>().AddTorque(transform.up * force * Input.GetAxis(horizontalAxisName), forceMode);
//torque from other direction
GetComponent<Rigidbody>().AddTorque(-transform.right * force * Input.GetAxis(verticalAxisName), forceMode);
}
}
| mit | C# | |
b43bd868be40e535d001af5cab8838b362e2da68 | Delete comment TEEEEEEEEEEST | maxcriser/CSharpLanguage,maxcriser/CSharpLanguage | PLanguage/GameConsole/Program.cs | PLanguage/GameConsole/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;
using System.Collections;
namespace GameConsole
{
public class Program
{
static int max;
static int min;
static int timerValue = 10000;
static bool exit = true;
static string gameWord;
static string inputWord;
static Timer timer = new Timer(timerValue);
static Game play;
public static void Settings(out int max, out int min)
{
do {
Console.Write("Minimum lenght: ");
min = int.Parse(Console.ReadLine());
} while (min < 3 || min > 20);
do {
Console.Write("Maximum lenght: ");
max = int.Parse(Console.ReadLine());
} while (max < min || max > 20);
}
static void Main(string[] args)
{
Settings(out max, out min);
play = new Game(max,min);
gameWord = play.gameWord;
Console.WriteLine("Your random word: " + gameWord);
timer.Elapsed += Timer_Elapsed;
timer.Start();
while (exit)
{
Console.Write("-> ");
inputWord=Console.ReadLine();
play.Test(inputWord);
};
}
private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
exit = false;
timer.Stop();
Console.WriteLine(play.ToString());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;
using System.Collections;
// TEEEEEEEEEEEEEEEEEEEEEEEEST
namespace GameConsole
{
public class Program
{
static int max;
static int min;
static int timerValue = 10000;
static bool exit = true;
static string gameWord;
static string inputWord;
static Timer timer = new Timer(timerValue);
static Game play;
public static void Settings(out int max, out int min)
{
do {
Console.Write("Minimum lenght: ");
min = int.Parse(Console.ReadLine());
} while (min < 3 || min > 20);
do {
Console.Write("Maximum lenght: ");
max = int.Parse(Console.ReadLine());
} while (max < min || max > 20);
}
static void Main(string[] args)
{
Settings(out max, out min);
play = new Game(max,min);
gameWord = play.gameWord;
Console.WriteLine("Your random word: " + gameWord);
timer.Elapsed += Timer_Elapsed;
timer.Start();
while (exit)
{
Console.Write("-> ");
inputWord=Console.ReadLine();
play.Test(inputWord);
};
}
private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
exit = false;
timer.Stop();
Console.WriteLine(play.ToString());
}
}
}
| apache-2.0 | C# |
4ea697b4503e7de6ca0e66d5b3dbf8896d3ebaa8 | Add operator None. | chtoucas/Narvalo.NET,chtoucas/Narvalo.NET | src/Narvalo.Fx/Linq/None.cs | src/Narvalo.Fx/Linq/None.cs | // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Linq
{
using System;
using System.Collections.Generic;
public static partial class Qperators
{
// Returns true if no element in the sequence satisfies the predicate; otherwise false.
public static bool None<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
Require.NotNull(source, nameof(source));
Require.NotNull(predicate, nameof(predicate));
// Same as !source.Any(predicate);
// Same as source.All(x => !predicate(x));
foreach (var element in source)
{
if (predicate(element))
{
return false;
}
}
return true;
}
}
}
| bsd-2-clause | C# | |
4d50d0237a8d4e863828bd98ee24b456d6586be5 | add enumeration performance unittest | deiruch/SATInterface | Tests/DarkerPerformanceTest.cs | Tests/DarkerPerformanceTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using SATInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tests
{
[TestClass]
public class DarkerPerformanceTest
{
[TestMethod]
public void DarkerPerformance()
{
using var m = new Model(); m.Configuration.Verbosity = 0;
m.Configuration.Solver = InternalSolver.CryptoMiniSat;
var I0 = m.AddUIntVar(255);
var I1 = m.AddUIntVar(255);
var I2 = m.AddUIntVar(255);
var I3 = m.AddUIntVar(255);
var I4 = m.AddUIntVar(255);
var I5 = m.AddUIntVar(255);
var I6 = m.AddUIntVar(255);
var I7 = m.AddUIntVar(255);
var H = new UIntVar[8];
H[0] = m.AddUIntVar(0x7A);
H[1] = m.AddUIntVar(0x7A);
H[2] = m.AddUIntVar(0x7A);
H[3] = m.AddUIntVar(40);
H[4] = m.AddUIntVar(0x7A);
H[5] = m.AddUIntVar(0x7A);
H[6] = m.AddUIntVar(0x7A);
H[7] = m.AddUIntVar(0x7A);
//H0 >= 21, H0 <= 7A
m.AddConstr(0x21 <= H[0]);
m.AddConstr(0x21 <= H[1]);
m.AddConstr(0x21 <= H[2]);
m.AddConstr(0x21 <= H[3]);
m.AddConstr(0x21 <= H[4]);
m.AddConstr(0x21 <= H[5]);
m.AddConstr(0x21 <= H[6]);
m.AddConstr(0x21 <= H[7]);
//I0 + I1 = I2
m.AddConstr(I0 + I1 == I2);
m.AddConstr(I2 - 10 == I3);
m.AddConstr(I4 + I5 == I6);
m.AddConstr(I6 - 10 == I7);
m.AddConstr(H[0] == I2);
m.AddConstr(H[1] == I4);
m.AddConstr(H[0] == H[1]);
m.AddConstr(H[2] == H[1] - 1);
m.AddConstr(H[3] <= 40);
m.AddConstr(H[4] == 'a');
m.AddConstr(H[5] == 'h');
m.AddConstr(H[6] == 'o');
m.AddConstr(H[7] == 'j');
var numFound = 0;
m.EnumerateSolutions(H, () =>
{
numFound++;
if (numFound > 1000)
m.Abort();
});
Assert.AreEqual(numFound, 712);
}
}
}
| mit | C# | |
b2c5fbc7fc65a0ee4a137e50a35bf874badbe8c8 | Undo unnecessary change | MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS | src/Host/Client/Impl/Session/RSessionRequestSource.cs | src/Host/Client/Impl/Session/RSessionRequestSource.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.R.Host.Client.Session {
internal sealed class RSessionRequestSource {
private readonly TaskCompletionSource<IRSessionInteraction> _createRequestTcs;
private readonly TaskCompletionSource<object> _responseTcs;
public Task<IRSessionInteraction> CreateRequestTask => _createRequestTcs.Task;
public bool IsVisible { get; }
public IReadOnlyList<IRContext> Contexts { get; }
public RSessionRequestSource(bool isVisible, IReadOnlyList<IRContext> contexts, CancellationToken ct) {
_createRequestTcs = new TaskCompletionSource<IRSessionInteraction>();
_responseTcs = new TaskCompletionSource<object>();
ct.Register(() => _createRequestTcs.TrySetCanceled(ct));
IsVisible = isVisible;
Contexts = contexts ?? new[] { RHost.TopLevelContext };
}
public void Request(string prompt, int maxLength, TaskCompletionSource<string> requestTcs) {
var request = new RSessionInteraction(requestTcs, _responseTcs, prompt, maxLength, Contexts);
if (_createRequestTcs.TrySetResult(request)) {
return;
}
request.Dispose();
if (CreateRequestTask.IsCanceled) {
throw new OperationCanceledException();
}
}
public void CompleteResponse() {
_responseTcs.SetResult(null);
}
public void Cancel() {
_createRequestTcs.TrySetCanceled();
_responseTcs.TrySetCanceled();
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.R.Host.Client.Session {
internal sealed class RSessionRequestSource {
private readonly TaskCompletionSource<IRSessionInteraction> _createRequestTcs;
private readonly TaskCompletionSource<object> _responseTcs;
public Task<IRSessionInteraction> CreateRequestTask => _createRequestTcs.Task;
public bool IsVisible { get; }
private IReadOnlyList<IRContext> Contexts { get; }
public RSessionRequestSource(bool isVisible, IReadOnlyList<IRContext> contexts, CancellationToken ct) {
_createRequestTcs = new TaskCompletionSource<IRSessionInteraction>();
_responseTcs = new TaskCompletionSource<object>();
ct.Register(() => _createRequestTcs.TrySetCanceled(ct));
IsVisible = isVisible;
Contexts = contexts ?? new[] { RHost.TopLevelContext };
}
public void Request(string prompt, int maxLength, TaskCompletionSource<string> requestTcs) {
var request = new RSessionInteraction(requestTcs, _responseTcs, prompt, maxLength, Contexts);
if (_createRequestTcs.TrySetResult(request)) {
return;
}
request.Dispose();
if (CreateRequestTask.IsCanceled) {
throw new OperationCanceledException();
}
}
public void CompleteResponse() {
_responseTcs.SetResult(null);
}
public void Cancel() {
_createRequestTcs.TrySetCanceled();
_responseTcs.TrySetCanceled();
}
}
} | mit | C# |
426ca537b664e82550e6f0b6e296126e94766bfa | Add class Runner and methods for collision | STzvetkov/Troll-runner | test/test/Runner.cs | test/test/Runner.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class Runner
{
public int X { get; set; }
public int Y { get; set; }
}
}
| mit | C# | |
1c7daef6a1ad8c4f9560703be00fe36099199ac9 | Add UserFile class to be used with files needed to be uploaded for an application | CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site,CS297Sp16/LCC_Co-op_Site | Coop_Listing_Site/Coop_Listing_Site/Models/UserFile.cs | Coop_Listing_Site/Coop_Listing_Site/Models/UserFile.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Coop_Listing_Site.Models
{
public class UserFile
{
public int UserFileID { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
public byte[] FileData { get; set; }
}
} | mit | C# | |
7c265cb73c074e0ccc2341b625101c2921abef7e | Add NonDisposableStream | nitacore/NetStitch,nitacore/NetStitch,nitacore/NetStitch | src/NetStitch.Server/NonDisposableStream.cs | src/NetStitch.Server/NonDisposableStream.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NetStitch.Server
{
public class NonDisposableStream : Stream
{
readonly Stream stream;
public NonDisposableStream(Stream stream)
{
this.stream = stream;
}
public override bool CanRead => stream.CanRead;
public override bool CanSeek => stream.CanSeek;
public override bool CanWrite => stream.CanWrite;
public override long Length => stream.Length;
public override long Position { get { return stream.Position; } set { stream.Position = value; } }
public override void Flush() => stream.Flush();
public override int Read(byte[] buffer, int offset, int count) => stream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => stream.Seek(offset, origin);
public override void SetLength(long value) => stream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => stream.Write(buffer, offset, count);
protected override void Dispose(bool disposing) { }
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
=> stream.CopyToAsync(destination, bufferSize, cancellationToken);
public override Task FlushAsync(CancellationToken cancellationToken) => stream.FlushAsync(cancellationToken);
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> stream.ReadAsync(buffer, offset, count);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> stream.WriteAsync(buffer, offset, count, cancellationToken);
public override int ReadByte() => stream.ReadByte();
public override void WriteByte(byte value) => stream.WriteByte(value);
}
}
| mit | C# | |
6036660732811e69d9edfa251270380e721888ad | add test for #156 | esskar/Serialize.Linq | src/Serialize.Linq.Tests/Issues/Issue156.cs | src/Serialize.Linq.Tests/Issues/Issue156.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Serialize.Linq.Factories;
using Serialize.Linq.Serializers;
namespace Serialize.Linq.Tests.Issues
{
// https://github.com/esskar/Serialize.Linq/issues/156
[TestClass]
public class Issue156
{
public enum SomeEnum
{
One = 1,
Two = 2,
Three = 3
}
public record SomeObject(SomeEnum Value);
private readonly IReadOnlyCollection<SomeEnum> values = new[] { SomeEnum.One, SomeEnum.Two };
private static bool SomeFunc(IReadOnlyCollection<SomeEnum> values, SomeObject @object) => values.Contains(@object.Value);
[TestMethod]
public void Reproduce()
{
Expression<Func<SomeObject, bool>> expression = x => SomeFunc(values, x);
var serializer = new ExpressionSerializer(new JsonSerializer());
serializer.AddKnownType(typeof(SomeEnum[]));
serializer.SerializeText(expression, new FactorySettings
{
AllowPrivateFieldAccess = true
});
}
}
}
| mit | C# | |
13ced5659f3f423355596bfb05f8ec01fe2f3be0 | add S_SHOW_CANDIDATE_LIST parser | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Parsing/Messages/S_SHOW_CANDIDATE_LIST.cs | TCC.Core/Parsing/Messages/S_SHOW_CANDIDATE_LIST.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TCC.Data;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class S_SHOW_CANDIDATE_LIST : ParsedMessage
{
public List<User> Candidates { get; set; }
public S_SHOW_CANDIDATE_LIST(TeraMessageReader reader) : base(reader)
{
var count = reader.ReadUInt16();
var offset = reader.ReadUInt16();
Candidates = new List<User>();
if (count == 0) return;
reader.BaseStream.Position = offset - 4;
for (int i = 0; i < count; i++)
{
var current = reader.ReadUInt16();
var next = reader.ReadUInt16();
var nameOffset = reader.ReadUInt16();
var playerId = reader.ReadUInt32();
var cls = (Class)reader.ReadUInt16();
reader.Skip(2 + 2);
var level = reader.ReadUInt16();
var worldId = reader.ReadUInt32();
var guardId = reader.ReadUInt32();
var sectionId = reader.ReadUInt32();
reader.BaseStream.Position = nameOffset - 4;
var name = reader.ReadTeraString();
Candidates.Add(new User(WindowManager.LfgListWindow.Dispatcher)
{
PlayerId = playerId,
UserClass = cls,
Level = level,
Location = SessionManager.MapDatabase.GetName(guardId, sectionId),
Online = true
});
if (next != 0) reader.BaseStream.Position = next - 4;
}
}
}
}
| mit | C# | |
f32008607ec0c32c56dee94f1a16dff390fa19b5 | Create EvenFibonacciNumbers.cs | DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges | Even_Fibonacci_Numbers/EvenFibonacciNumbers.cs | Even_Fibonacci_Numbers/EvenFibonacciNumbers.cs | namespace EvenFibonacciNumbers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("This program requires 2 starting integers, and the max terms to count!\n");
Environment.Exit(0);
}
int start1 = Convert.ToInt32(args[0]);
int start2 = Convert.ToInt32(args[1]);
int maxCount = Convert.ToInt32(args[2]);
if (maxCount < 2)
maxCount = 2;
int[] fullList = new int[maxCount];
fullList[0] = start1;
fullList[1] = start2;
for (int i = 2; i < maxCount; i++)
fullList[i] = fullList[i - 1] + fullList[i-2];
Console.Write("Result - {");
for (int i = 0; i < fullList.Length; i++)
{
if (fullList[i] % 2 == 0)
{
Console.Write($" {fullList[i]}");
}
}
Console.Write(" }");
Console.WriteLine();
Console.ReadKey();
}
}
}
| unlicense | C# | |
142b0834090e14322f7558d71d1648d48d67b6d2 | Create Program.cs | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | quickstart/csharp/sms/send-sms/Program.cs | quickstart/csharp/sms/send-sms/Program.cs | // Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace YourNewConsoleApp
{
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("+15017122661");
var message = MessageResource.Create(
to,
from: new PhoneNumber("+15558675310"),
body: "This is the ship that made the Kessel Run in fourteen parsecs?");
Console.WriteLine(message.Sid);
}
}
}
| mit | C# | |
6ff6e846c1efb1e67869499b39f00c4ac221a051 | Add TemporaryUrl class forgotten from earlier commit (for #22) | HelloFax/hellosign-dotnet-sdk | HelloSign/Models/TemporaryUrl.cs | HelloSign/Models/TemporaryUrl.cs | namespace HelloSign
{
/// <summary>
/// Information about a temporary URL (a public URL with an expiration date).
/// </summary>
public class TemporaryUrl
{
/// <summary>
/// Unix timestamp when this URL will expire (may become a DateTime in future releases).
/// </summary>
public int ExpiresAt { get; set; }
/// <summary>
/// The URL as a string.
/// </summary>
public string FileUrl { get; set; }
}
}
| mit | C# | |
e74d27f198c370cea2010dda2b643a46e429c792 | Add b_tree implementation in C# | ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms | data_structures/b_tree/C#/btree.cs | data_structures/b_tree/C#/btree.cs | using System;
// A BTree
class Btree
{
public BTreeNode root; // Pointer to root node
public int t; // Minimum degree
// Constructor (Initializes tree as empty)
Btree(int t)
{
this.root = null;
this.t = t;
}
// function to traverse the tree
public void traverse()
{
if (this.root != null)
this.root.traverse();
Console.WriteLine();
}
// function to search a key in this tree
public BTreeNode search(int k)
{
if (this.root == null)
return null;
else
return this.root.search(k);
}
}
// A BTree node
class BTreeNode
{
int[] keys; // An array of keys
int t; // Minimum degree (defines the range for number of keys)
BTreeNode[] C; // An array of child pointers
int n; // Current number of keys
bool leaf; // Is true when node is leaf. Otherwise false
// Constructor
BTreeNode(int t, bool leaf) {
this.t = t;
this.leaf = leaf;
this.keys = new int[2 * t - 1];
this.C = new BTreeNode[2 * t];
this.n = 0;
}
// A function to traverse all nodes in a subtree rooted with this node
public void traverse() {
// There are n keys and n+1 children, traverse through n keys
// and first n children
int i = 0;
for (i = 0; i < this.n; i++) {
// If this is not leaf, then before printing key[i],
// traverse the subtree rooted with child C[i].
if (this.leaf == false) {
C[i].traverse();
}
Console.Write(keys[i] + " ");
}
// Print the subtree rooted with last child
if (leaf == false)
C[i].traverse();
}
// A function to search a key in the subtree rooted with this node.
public BTreeNode search(int k) { // returns NULL if k is not present.
// Find the first key greater than or equal to k
int i = 0;
while (i < n && k > keys[i])
i++;
// If the found key is equal to k, return this node
if (keys[i] == k)
return this;
// If the key is not found here and this is a leaf node
if (leaf == true)
return null;
// Go to the appropriate child
return C[i].search(k);
}
}
| cc0-1.0 | C# | |
fbafb2f81fc75e0b97479690e25859264bc9a64d | Add ApplicationConfiguration class stub | appharbor/appharbor-cli | src/AppHarbor/ApplicationConfiguration.cs | src/AppHarbor/ApplicationConfiguration.cs | namespace AppHarbor
{
public class ApplicationConfiguration
{
}
}
| mit | C# | |
82bb7f163c08d888eb953ac825b29c2f1c6bb5ad | Add forgotten file. | jeongroseok/magecrawl,AndrewBaker/magecrawl | Trunk/GameEngine/MapObjects/TreasureChest.cs | Trunk/GameEngine/MapObjects/TreasureChest.cs | using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using Magecrawl.GameEngine.Interfaces;
using Magecrawl.GameEngine.SaveLoad;
using Magecrawl.Utilities;
using Magecrawl.GameEngine.Items;
namespace Magecrawl.GameEngine.MapObjects
{
internal sealed class TreasureChest : OperableMapObject
{
private Point m_position;
public TreasureChest()
: this(Point.Invalid)
{
}
public TreasureChest(Point position)
{
m_position = position;
}
public override MapObjectType Type
{
get
{
return MapObjectType.TreasureChest;
}
}
public override Point Position
{
get
{
return m_position;
}
}
public override bool IsSolid
{
get
{
return true;
}
}
public override bool CanOperate
{
get
{
return true;
}
}
public override void Operate()
{
// Remove me
CoreGameEngine.Instance.Map.RemoveMapItem(this);
Item newItem = CoreGameEngine.Instance.ItemFactory.CreateItem("Wooden Sword");
CoreGameEngine.Instance.Map.AddItem(new Pair<Items.Item, Point>(newItem, Position));
}
#region SaveLoad
public override void ReadXml(XmlReader reader)
{
m_position = m_position.ReadXml(reader);
}
public override void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Type", "TreasureChest");
m_position.WriteToXml(writer, "Position");
}
#endregion
}
}
| bsd-2-clause | C# | |
11e1a79e717218a73ca9ad25a3b929d1efa1fbb3 | Create CutTheSticks.cs | costincaraivan/hackerrank,costincaraivan/hackerrank | algorithms/implementation/C#/CutTheSticks.cs | algorithms/implementation/C#/CutTheSticks.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
int positiveMin(int[] array)
{
if (array == null || array.Length == 0)
{
return Int32.MinValue;
}
var min = Int32.MaxValue;
foreach(var element in array)
{
if (min > element && element > 0)
{
min = element;
}
}
return min;
}
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp,Int32.Parse);
var count = arr.Length;
while (count != 0)
{
var solution = new Solution();
var min = solution.positiveMin(arr);
var shortened = 0;
for(var index = 0; index < arr.Length; index++)
{
if (arr[index] > 0)
{
if (arr[index] - min <= 0)
{
count -= 1;
}
shortened += 1;
}
arr[index] -= min;
}
Console.WriteLine(shortened);
}
}
}
| mit | C# | |
9b2f9be43fb38308702eafcaea4f37b2aec2472a | add variables/global | lvermeulen/BuildMaster.Net | src/BuildMaster.Net/Variables/Global/BuildMasterClient.cs | src/BuildMaster.Net/Variables/Global/BuildMasterClient.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using BuildMaster.Net.Common.Models;
using Flurl.Http;
// ReSharper disable CheckNamespace
namespace BuildMaster.Net
{
public partial class BuildMasterClient
{
public async Task<IEnumerable<Variable>> GetAllGlobalConfigurationVariables()
{
var response = await GetVariablesApiClient("global")
.GetJsonAsync<IEnumerable<Variable>>();
return response; //TODO: inline
}
public async Task<bool> SetAllGlobalConfigurationVariables(IEnumerable<Variable> variables)
{
var response = await GetVariablesApiClient("global")
.PutJsonAsync(variables);
return response.IsSuccessStatusCode;
}
public async Task<Variable> GetSingleGlobalConfigurationVariable(string variableName)
{
var response = await GetVariablesApiClient($"global/{variableName}")
.GetJsonAsync<Variable>();
return response; //TODO: inline
}
public async Task<bool> SetSingleGlobalConfigurationVariable(Variable variable)
{
var response = await GetVariablesApiClient($"global/{variable?.Name}")
.PutJsonAsync(variable);
return response.IsSuccessStatusCode;
}
public async Task<bool> DeleteSingleGlobalConfigurationVariable(string variableName)
{
var response = await GetVariablesApiClient($"global/{variableName}")
.DeleteAsync();
return response.IsSuccessStatusCode;
}
}
}
| mit | C# | |
cf418a8097fc00b3068ef7f81b494580ecf3e9e8 | Add error handling to default template | JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS | src/Umbraco.Web.UI/Views/Partials/BlockList/Default.cshtml | src/Umbraco.Web.UI/Views/Partials/BlockList/Default.cshtml | @inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
@foreach (var layout in Model.Layout)
{
if (layout?.Udi == null) { continue; }
var data = layout.Data;
try
{
@Html.Partial("BlockList/Components/" + data.ContentType.Alias, (data, layout.Settings))
}
catch (Exception ex)
{
global::Umbraco.Core.Composing.Current.Logger.Error(typeof(BlockListModel), ex, "Could not display block list component for content type {0}", data?.ContentType?.Alias);
}
}
</div>
| @inherits UmbracoViewPage<BlockListModel>
@using Umbraco.Core.Models.Blocks
@{
if (Model?.Layout == null || !Model.Layout.Any()) { return; }
}
<div class="umb-block-list">
@foreach (var layout in Model.Layout)
{
if (layout?.Udi == null) { continue; }
var data = layout.Data;
@Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout)
}
</div>
| mit | C# |
98bb734522d28712045702ba124a614341049ded | Add class; unfinished | whampson/cascara,whampson/bft-spec | Cascara/Src/CascaraObject.cs | Cascara/Src/CascaraObject.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace WHampson.Cascara
{
internal class CascaraObjectFactory
{
public static CascaraObject Create(Statement expr)
{
return new CascaraObject();
}
}
public class CascaraObject
{
// TODO: object factory based on expression
internal CascaraObject()
{
}
}
}
| mit | C# | |
d9e1e01df13bed68556bb7e5b62ad310c89778ea | Set the course directory as Content (for MSBuild) | riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy | src/DotvvmAcademy.CourseFormat/MarkdownStepInfo.cs | src/DotvvmAcademy.CourseFormat/MarkdownStepInfo.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace DotvvmAcademy.CourseFormat
{
public class MarkdownStepInfo
{
public string Path { get; }
public string Moniker { get; }
public string Name { get; }
public string CodeTaskPath { get; }
}
}
| apache-2.0 | C# | |
e5e7a0755d000dd95f21a820c895c2be1aafdd29 | Create Program.cs | Zedohsix/SharpFind | SharpFind/Program.cs | SharpFind/Program.cs | using System;
using System.Windows.Forms;
namespace SharpFind
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Frm_Main());
}
}
}
| mit | C# | |
4d7e1263fc28ae5f1a1c48fdd636f65fcad3c847 | Add CounterWarpper to use in separate thread | witoong623/TirkxDownloader,witoong623/TirkxDownloader | Framework/CounterWarpper.cs | Framework/CounterWarpper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TirkxDownloader.Framework
{
public class CounterWarpper
{
private int counter;
public int Counter { get { return counter; } }
public void Increase()
{
Interlocked.Increment(ref counter);
}
public void Decrease()
{
Interlocked.Decrement(ref counter);
}
}
}
| mit | C# | |
5466af5017a5cf2de5aba7ea403627cb44763e68 | remove whitespace from end of package descriptions, which added new lines when the summary includes a paragraph. Do not merge. | xorware/android_build,ND-3500/platform_manifest,RR-msm7x30/platform_manifest,xorware/android_build,pranav01/platform_manifest,xorware/android_build,knone1/platform_manifest,hagar006/platform_manifest,fallouttester/platform_manifest,see4ri/lolili,Hybrid-Power/startsync,xorware/android_build,xorware/android_build | tools/droiddoc/templates/packages.cs | tools/droiddoc/templates/packages.cs | <?cs include:"doctype.cs" ?>
<?cs include:"macros.cs" ?>
<html>
<?cs include:"head_tag.cs" ?>
<body class="gc-documentation">
<?cs include:"header.cs" ?>
<div class="g-unit" id="doc-content">
<div id="jd-header">
<h1><?cs var:page.title ?></h1>
</div>
<div id="jd-content">
<div class="jd-descr">
<p><?cs call:tag_list(root.descr) ?></p>
</div>
<?cs set:count = #1 ?>
<table class="jd-sumtable">
<?cs each:pkg = docs.packages ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:pkg.since ?>" >
<td class="jd-linkcol"><?cs call:package_link(pkg) ?></td>
<td class="jd-descrcol" width="100%"><?cs call:tag_list(pkg.shortDescr) ?></td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
</table>
<?cs include:"footer.cs" ?>
</div><!-- end jd-content -->
</div> <!-- end doc-content -->
<?cs include:"trailer.cs" ?>
</body>
</html>
| <?cs include:"doctype.cs" ?>
<?cs include:"macros.cs" ?>
<html>
<?cs include:"head_tag.cs" ?>
<body class="gc-documentation">
<?cs include:"header.cs" ?>
<div class="g-unit" id="doc-content">
<div id="jd-header">
<h1><?cs var:page.title ?></h1>
</div>
<div id="jd-content">
<div class="jd-descr">
<p><?cs call:tag_list(root.descr) ?></p>
</div>
<?cs set:count = #1 ?>
<table class="jd-sumtable">
<?cs each:pkg = docs.packages ?>
<tr class="<?cs if:count % #2 ?>alt-color<?cs /if ?> api apilevel-<?cs var:pkg.since ?>" >
<td class="jd-linkcol"><?cs call:package_link(pkg) ?></td>
<td class="jd-descrcol" width="100%"><?cs call:tag_list(pkg.shortDescr) ?> </td>
</tr>
<?cs set:count = count + #1 ?>
<?cs /each ?>
</table>
<?cs include:"footer.cs" ?>
</div><!-- end jd-content -->
</div> <!-- end doc-content -->
<?cs include:"trailer.cs" ?>
</body>
</html>
| apache-2.0 | C# |
440ccaeff14bc0a4a6152a0b8098afae76a78251 | Add internal key factory | dnauck/Portable.Licensing,dnauck/Portable.Licensing,dreamrain21/Portable.Licensing,dreamrain21/Portable.Licensing | src/Portable.Licensing/Security/Cryptography/KeyFactory.cs | src/Portable.Licensing/Security/Cryptography/KeyFactory.cs | //
// Copyright © 2012 - 2013 Nauck IT KG http://www.nauck-it.de
//
// Author:
// Daniel Nauck <d.nauck(at)nauck-it.de>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace Portable.Licensing.Security.Cryptography
{
internal static class KeyFactory
{
private static readonly string keyEncryptionAlgorithm = PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id;
/// <summary>
/// Encrypts and encodes the private key.
/// </summary>
/// <param name="key">The private key.</param>
/// <param name="passPhrase">The pass phrase to encrypt the private key.</param>
/// <returns>The encrypted private key.</returns>
public static string ToEncryptedPrivateKeyString(AsymmetricKeyParameter key, string passPhrase)
{
var salt = new byte[16];
var secureRandom = SecureRandom.GetInstance("SHA256PRNG");
secureRandom.NextBytes(salt);
return
Convert.ToBase64String(PrivateKeyFactory.EncryptKey(keyEncryptionAlgorithm, passPhrase.ToCharArray(),
salt, 10, key));
}
/// <summary>
/// Decrypts the provided private key.
/// </summary>
/// <param name="privateKey">The encrypted private key.</param>
/// <param name="passPhrase">The pass phrase to decrypt the private key.</param>
/// <returns>The private key.</returns>
public static AsymmetricKeyParameter FromEncryptedPrivateKeyString(string privateKey, string passPhrase)
{
return PrivateKeyFactory.DecryptKey(passPhrase.ToCharArray(), Convert.FromBase64String(privateKey));
}
/// <summary>
/// Encodes the public key into DER encoding.
/// </summary>
/// <param name="key">The public key.</param>
/// <returns>The encoded public key.</returns>
public static string ToPublicKeyString(AsymmetricKeyParameter key)
{
return
Convert.ToBase64String(
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key)
.ToAsn1Object()
.GetDerEncoded());
}
/// <summary>
/// Decoded the public key from DER encoding.
/// </summary>
/// <param name="publicKey">The encoded public key.</param>
/// <returns>The public key.</returns>
public static AsymmetricKeyParameter FromPublicKeyString(string publicKey)
{
return PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
}
}
} | mit | C# | |
669a212c46184a4c5ce8be393d32e415acdb0bc9 | Remove unused method. | duplicati/duplicati,sitofabi/duplicati,sitofabi/duplicati,sitofabi/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,sitofabi/duplicati,duplicati/duplicati,mnaiman/duplicati,sitofabi/duplicati | Duplicati/Library/Backend/HubiC/Strings.cs | Duplicati/Library/Backend/HubiC/Strings.cs | // Copyright (C) 2015, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using Duplicati.Library.Localization.Short;
namespace Duplicati.Library.Backend.Strings
{
internal static class HubiC {
public static string Description { get { return LC.L(@"This backend can read and write data to HubiC. Supported format is ""hubic://container/folder""."); } }
public static string DisplayName { get { return LC.L(@"HubiC"); } }
public static string AuthidShort { get { return LC.L(@"The authorization code"); } }
public static string AuthidLong(string url) { return LC.L(@"The authorization token retrieved from {0}", url); }
}
}
| // Copyright (C) 2015, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using Duplicati.Library.Localization.Short;
namespace Duplicati.Library.Backend.Strings
{
internal static class HubiC {
public static string Description { get { return LC.L(@"This backend can read and write data to HubiC. Supported format is ""hubic://container/folder""."); } }
public static string DisplayName { get { return LC.L(@"HubiC"); } }
public static string MissingAuthID(string url) { return LC.L(@"You need an AuthID, you can get it from: {0}", url); }
public static string AuthidShort { get { return LC.L(@"The authorization code"); } }
public static string AuthidLong(string url) { return LC.L(@"The authorization token retrieved from {0}", url); }
}
}
| lgpl-2.1 | C# |
570abf97000a3df2ac6a0a14471b1feefb1d6ba8 | Add new custom property class UScriptMapProperty for Transformers. | EliotVU/Unreal-Library | src/Core/Classes/Props/Custom/UScriptMapProperty.cs | src/Core/Classes/Props/Custom/UScriptMapProperty.cs | #if TRANSFORMERS
namespace UELib.Core
{
/// <summary>
/// ScriptMap Property
/// </summary>
[UnrealRegisterClass]
public class UScriptMapProperty : UMapProperty
{
}
}
#endif | mit | C# | |
146452fb9dd34bc26e0a10bec510cfabcb26f759 | Add Script ClickToMove | TheNoobCompany/LevelingQuestsTNB,F0rTh3H0rd3/LevelingQuestsTNB | Profiles/Quester/Scripts/ClickToMove.cs | Profiles/Quester/Scripts/ClickToMove.cs | if(!MovementManager.InMovement)
{
if (questObjective.Position.IsValid && questObjective.Position.DistanceTo(ObjectManager.Me.Position) > 5f)
{
Logging.Write("enter objectif 1");
MountTask.Mount();
System.Threading.Thread.Sleep(2000);
var listP = new List<Point>();
listP.Add(ObjectManager.Me.Position);
listP.Add(questObjective.Position);
MovementManager.Go(listP);
while(MovementManager.InMovement && questObjective.Position.DistanceTo(ObjectManager.Me.Position) > 5f)
{
System.Threading.Thread.Sleep(100);
}
MovementManager.StopMove();
}
if (questObjective.Position.DistanceTo(ObjectManager.Me.Position) <= 5f)
{
Logging.Write("Completed");
questObjective.IsObjectiveCompleted = true;
return true;
}
} | mit | C# | |
4cc262dbe1f8a7e2a72990501f2a6bad34fc094b | Add ViewModelBase class | rmc00/gsf,rmc00/gsf,GridProtectionAlliance/gsf,GridProtectionAlliance/gsf,rmc00/gsf,GridProtectionAlliance/gsf,GridProtectionAlliance/gsf,rmc00/gsf,GridProtectionAlliance/gsf,GridProtectionAlliance/gsf,GridProtectionAlliance/gsf,GridProtectionAlliance/gsf,rmc00/gsf,rmc00/gsf,rmc00/gsf | Source/Tools/COMTRADEConverter/ViewModelBase.cs | Source/Tools/COMTRADEConverter/ViewModelBase.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace COMTRADEConverter
{
class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| mit | C# | |
4fa2e52b8b843e4fb3258c37a76fa3287f29e114 | fix silly bug. Kudu scenario now working! | brendankowitz/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,Azure/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,Azure/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk | WebFrontEnd/ControllersWebApi/KuduController.cs | WebFrontEnd/ControllersWebApi/KuduController.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DaasEndpoints;
using DataAccess;
using Orchestrator;
using RunnerInterfaces;
using WebFrontEnd.Controllers;
namespace WebFrontEnd.ControllersWebApi
{
public class KuduController : ApiController
{
// Called after a new kudu site is published and we need to index it.
// Uri is for the antares site that we ping.
[HttpPost]
public FuncSubmitModel Index(string uri)
{
// At least return a URL that they can view results at.
// Useful for when debugging with Fiddler.
return IndexWorker(uri);
}
public static FuncSubmitModel IndexWorker(string uri)
{
// common case, append the expected route.
if (uri.EndsWith(".azurewebsites.net"))
{
uri += "/api/SimpleBatchIndexer";
}
// Ping orchestrator to update maps?
// Or even send a IndexRequestPayload over with the URL
var obj = new IndexUrlOperation { Url = uri } ;
return ExecutionController.RegisterFuncSubmitworker(obj);
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DaasEndpoints;
using DataAccess;
using Orchestrator;
using RunnerInterfaces;
using WebFrontEnd.Controllers;
namespace WebFrontEnd.ControllersWebApi
{
public class KuduController : ApiController
{
// Called after a new kudu site is published and we need to index it.
// Uri is for the antares site that we ping.
[HttpPost]
public void Index(string uri)
{
}
public static FuncSubmitModel IndexWorker(string uri)
{
// common case, append the expected route.
if (uri.EndsWith(".azurewebsites.net"))
{
uri += "/api/SimpleBatchIndexer";
}
// Ping orchestrator to update maps?
// Or even send a IndexRequestPayload over with the URL
var obj = new IndexUrlOperation { Url = uri } ;
return ExecutionController.RegisterFuncSubmitworker(obj);
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.