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 |
|---|---|---|---|---|---|---|---|---|
1f249bbc0f13d6347db92dec9fb96d45f93ee2c3 | Create Controls_Player_Seek_Waypoint.cs | Tech-Curriculums/101-GameDesign-2D-GameDesign-With-Unity | AngryHipsters/Controls_Player_Seek_Waypoint.cs | AngryHipsters/Controls_Player_Seek_Waypoint.cs | /**
This is a common control scheme where you click to bring a player to a point.
*/
using UnityEngine;
using System.Collections;
public class Controls : MonoBehaviour {
public float speed = 1F;
Vector2 differenceVector, touchPositionTarget;
void Start() {
touchPositionTarget.x = transform.position.x;
touchPositionTarget.y = transform.position.y;
}
void Update() {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Begin) {
//first we get the touch position (2D vector)
touchPositionTarget = Input.GetTouch(0).position;
//This actually gives screen coordinates, we want the world coords
Vector3 realWorldPos = Camera.main.ScreenToWorldPoint(touchPositionTarget);
//World coordinates have a Z, we're 2D, so we just borrow the x and the y
touchPositionTarget.x = realWorldPos.x;
touchPositionTarget.y = realWorldPos.y;
}
transform.position = Vector2.MoveTowards( transform.position, touchPositionTarget, speed * Time.deltaTime);
}
}
| mit | C# | |
bd70ee85d3bc14e91c5206b19b72dcc04d05a01c | include code behind | ngalin/Illumimateys,ngalin/Illumimateys | Kinect/ShadowWall/Recording/PointCloud.xaml.cs | Kinect/ShadowWall/Recording/PointCloud.xaml.cs | using Microsoft.Kinect;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
namespace ShadowWall.Recording
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class PointCloud : Window
{
public PointCloud()
{
InitializeComponent();
this.Loaded += PointCloud_Loaded;
this.KeyDown += PointCloud_KeyDown;
this.MouseWheel += PointCloud_MouseWheel;
}
public int WallWidth { get { return 180; } }
public int WallHeight { get { return 120; } }
public int Distance { get { return 2000; } }
private void PointCloud_Loaded(object sender, RoutedEventArgs e)
{
var points = Serializer.LoadPoint();
foreach (var point in points)
{
this.DrawPoint(point.X, point.Y, point.Z, point.R, point.G, point.B);
}
}
#region 3D
private void PointCloud_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Up:
RotateX.Angle += 10;
break;
case Key.Down:
RotateX.Angle -= 10;
break;
case Key.Left:
RotateY.Angle -= 10;
break;
case Key.Right:
RotateY.Angle += 10;
break;
case Key.W:
Camera.Position = new Point3D(Camera.Position.X, Camera.Position.Y - 50, Camera.Position.Z);
break;
case Key.S:
Camera.Position = new Point3D(Camera.Position.X, Camera.Position.Y + 50, Camera.Position.Z);
break;
case Key.A:
Camera.Position = new Point3D(Camera.Position.X + 50, Camera.Position.Y, Camera.Position.Z);
break;
case Key.D:
Camera.Position = new Point3D(Camera.Position.X - 50, Camera.Position.Y - 50, Camera.Position.Z);
break;
default:
break;
}
}
private void PointCloud_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Delta > 0)
{
Camera.Position = new Point3D(Camera.Position.X + 50, Camera.Position.Y - 50, Camera.Position.Z - 50);
}
else
{
Camera.Position = new Point3D(Camera.Position.X - 50, Camera.Position.Y + 50, Camera.Position.Z + 50);
}
}
private void DrawPoint(float x, float y, float z, int r, int g, int b)
{
var count = 0;
var color = new Color() { A = (byte)255, R = (byte)r, G = (byte)g, B = (byte)b };
var geometry = new MeshGeometry3D();
geometry.Positions.Add(new Point3D(x - 0.5, y - 0.5, z + 0.5));
geometry.Positions.Add(new Point3D(x + 0.5, y + 0.5, z + 0.5));
geometry.Positions.Add(new Point3D(x - 0.5, y + 0.5, z + 0.5));
geometry.TriangleIndices.Add(0 + count);
geometry.TriangleIndices.Add(1 + count);
geometry.TriangleIndices.Add(2 + count);
ModelGroup.Children.Add(new GeometryModel3D(geometry, new DiffuseMaterial(new SolidColorBrush(color))) { Transform = GeometryModel.Transform });
this.Flush();
}
private void Flush()
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
}
#endregion
}
}
| mit | C# | |
9f6418f080edd23f626215ec35ae1c6ef5273681 | Add missing file | jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl | MatterControlLib/SlicerConfiguration/UIFields/SliceEngineField.cs | MatterControlLib/SlicerConfiguration/UIFields/SliceEngineField.cs | /*
Copyright (c) 2019, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.PrinterControls.PrinterConnections;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class SliceEngineField : UIField
{
private DropDownList dropdownList;
private ThemeConfig theme;
private PrinterConfig printer;
public SliceEngineField(PrinterConfig printer, ThemeConfig theme)
{
this.theme = theme;
this.printer = printer;
}
public new string Name { get; set; }
public override void Initialize(int tabIndex)
{
EventHandler unregisterEvents = null;
var panel = new FlowLayoutWidget();
dropdownList = new MHDropDownList("None".Localize(), theme, maxHeight: 200)
{
ToolTipText = this.HelpText,
TabIndex = tabIndex,
Name = "slice_engine Field",
// Prevent droplist interaction when connected
Enabled = !printer.Connection.Printing,
};
dropdownList.Click += (s, e) =>
{
// TODO: why doesn't this blow up without runonidle?
RebuildMenuItems();
};
RebuildMenuItems();
// Prevent droplist interaction when connected
void CommunicationStateChanged(object s, EventArgs e)
{
dropdownList.Enabled = !printer.Connection.Printing;
if (printer.Connection.ComPort != dropdownList.SelectedLabel)
{
dropdownList.SelectedLabel = printer.Connection.ComPort;
}
}
printer.Connection.CommunicationStateChanged += CommunicationStateChanged;
dropdownList.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged;
// Release event listener on close
dropdownList.Closed += (s, e) =>
{
unregisterEvents?.Invoke(null, null);
};
var configureIcon = new IconButton(AggContext.StaticData.LoadIcon("fa-cog_16.png", theme.InvertIcons), theme)
{
VAnchor = VAnchor.Center,
Margin = theme.ButtonSpacing,
ToolTipText = "Port Wizard".Localize()
};
configureIcon.Click += (s, e) =>
{
DialogWindow.Show(new SetupStepComPortOne(printer));
};
panel.AddChild(configureIcon);
panel.AddChild(dropdownList);
this.Content = panel;
}
protected override void OnValueChanged(FieldChangedEventArgs fieldChangedEventArgs)
{
dropdownList.SelectedLabel = this.Value;
base.OnValueChanged(fieldChangedEventArgs);
}
private void RebuildMenuItems()
{
dropdownList.MenuItems.Clear();
foreach (var sliceEngine in PrinterSettings.SliceEngines)
{
// Add each serial port to the dropdown list
MenuItem newItem = dropdownList.AddItem(sliceEngine.Key);
// When the given menu item is selected, save its value back into settings
newItem.Selected += (sender, e) =>
{
if (sender is MenuItem menuItem)
{
if (PrinterSettings.SliceEngines.TryGetValue(menuItem.Text, out IObjectSlicer slicer))
{
printer.Settings.Slicer = slicer;
}
this.SetValue(
menuItem.Text,
userInitiated: true);
}
};
}
// Set control text
dropdownList.SelectedLabel = this.Value;
}
}
}
| bsd-2-clause | C# | |
384734e8fb60203a1fff27c1591d3031e68e1a1d | Add constant time functions and functions for generating random bytes | ektrah/nsec | src/Experimental/CryptographicUtilities.cs | src/Experimental/CryptographicUtilities.cs | using System;
using System.Runtime.CompilerServices;
namespace NSec.Experimental
{
public static class CryptographicUtilities
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FillRandomBytes(Span<byte> data)
{
System.Security.Cryptography.RandomNumberGenerator.Fill(data);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)
{
return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(left, right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ZeroMemory(Span<byte> buffer)
{
System.Security.Cryptography.CryptographicOperations.ZeroMemory(buffer);
}
}
}
| mit | C# | |
061c86fb026ed25a5f7cb32243731321bac5f2c8 | Add unit tests | dsbenghe/Novell.Directory.Ldap.NETStandard,dsbenghe/Novell.Directory.Ldap.NETStandard | test/Novell.Directory.Ldap.NETStandard.UnitTests/StringExtensionTests.cs | test/Novell.Directory.Ldap.NETStandard.UnitTests/StringExtensionTests.cs | using Novell.Directory.Ldap.Utilclass;
using System;
using System.Collections.Generic;
using Xunit;
namespace Novell.Directory.Ldap.NETStandard.UnitTests
{
public class StringExtensionTests
{
[Theory]
[MemberData(nameof(DataSuccess))]
public void StartsWithStringAtOffset_Success(string baseString, string searchString, int offset)
{
Assert.Equal(baseString.StartsWithStringAtOffset(searchString, offset), baseString.Substring(offset).StartsWith(searchString));
}
public static IEnumerable<object[]> DataSuccess =>
new List<object[]>
{
// Empty strings
new object[] { "", "", 0 },
new object[] { "", "test", 0 },
new object[] { "test", "", 0 },
new object[] { "test", "", 4 },
// Complete valid range
new object[] { "abcd", "ab", 0 },
new object[] { "abcd", "ab", 1 },
new object[] { "abcd", "ab", 2 },
new object[] { "abcd", "ab", 4 },
// same length
new object[] { "abcd", "abcd", 0 },
new object[] { "abcd", "abcd", 1 },
// Searchstring longer than baseString
new object[] { "ab", "abcd", 0 },
// Unicode
new object[] { "大象牙膏", "象牙", 0 },
new object[] { "大象牙膏", "象牙", 1 },
new object[] { "大象牙膏", "象牙", 2 },
new object[] { "大象牙膏", "象牙", 3 },
new object[] { "大象牙膏", "象牙", 4 },
new object[] { "зубная паста слона", "аста", 8 }
};
[Theory]
[MemberData(nameof(DataException))]
public void StartsWithStringAtOffset_Exception(string baseString, string searchString, int offset)
{
var substringStartsWithException = Assert.ThrowsAny<Exception>(() => baseString.Substring(offset).StartsWith(searchString));
var startsWithStringAtOffsetException = Assert.ThrowsAny<Exception>(() => baseString.StartsWithStringAtOffset(searchString, offset));
// Same exception type?
Assert.IsType(substringStartsWithException.GetType(), startsWithStringAtOffsetException);
}
public static IEnumerable<object[]> DataException =>
new List<object[]>
{
// Null Argument
new object[] {"abcd", null, 0},
// Invalid offset
new object[] { "abcd", "abcd", 5 },
new object[] { "", "abcd", 1 },
new object[] { "abcd", "ab", 5 },
new object[] { "abcd", "ab", -1 },
new object[] { "大象牙膏", "象牙", 5 },
};
}
}
| mit | C# | |
e74f9024836b56b4485d724d867fa1f71ea0a5b6 | Add playfield test scene | peppy/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game.Rulesets.Taiko.Tests/Skinning/TestSceneTaikoPlayfield.cs | osu.Game.Rulesets.Taiko.Tests/Skinning/TestSceneTaikoPlayfield.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Taiko.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Taiko.Tests.Skinning
{
public class TestSceneTaikoPlayfield : TaikoSkinnableTestScene
{
[Cached(typeof(IScrollingInfo))]
private ScrollingTestContainer.TestScrollingInfo info = new ScrollingTestContainer.TestScrollingInfo
{
Direction = { Value = ScrollingDirection.Left },
TimeRange = { Value = 5000 },
};
public TestSceneTaikoPlayfield()
{
AddStep("Load playfield", () => SetContents(() => new TaikoPlayfield(new ControlPointInfo())
{
Height = 0.4f,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
}));
}
}
}
| mit | C# | |
4b0a5b9bb455ecc32adf39c44b0963a43e8909e3 | add test | existall/Shepherd | src/tests/ExistsForAll.Shepherd.SimpleInjector.UnitTests/CollectionRegistrationBehaviorTests.cs | src/tests/ExistsForAll.Shepherd.SimpleInjector.UnitTests/CollectionRegistrationBehaviorTests.cs | using System;
using ExistsForAll.Shepherd.SimpleInjector.RegistrationActions;
using Xunit;
using static ExistsForAll.Shepherd.SimpleInjector.UnitTests.TestUtils;
namespace ExistsForAll.Shepherd.SimpleInjector.UnitTests
{
public class CollectionRegistrationBehaviorTests
{
[Fact]
public void ShouldRegister_WhenHaveLessThanTwoImpl_ShouldReturnFalse()
{
var sut = BuildSut();
var descriptor = BuildDescriptor(GetType<Interface>());
var result = sut.ShouldRegister(descriptor);
Assert.False(result);
}
[Fact]
public void ShouldRegister_WhenHaveMoreThanOneImpl_ShouldReturnFalse()
{
var sut = BuildSut();
var descriptor = BuildDescriptor(GetType<Interface>(), GetType<Interface1>());
var result = sut.ShouldRegister(descriptor);
Assert.True(result);
}
private IServiceDescriptor BuildDescriptor(Type type, params Type[] types)
{
return BuildServiceDescriptor(GetType<IInterface>(), type, types);
}
private static CollectionRegistrationBehavior BuildSut()
{
return new CollectionRegistrationBehavior();
}
private interface IInterface
{
}
private class Interface : IInterface
{
}
private class Interface1 : IInterface
{
}
}
} | mit | C# | |
1d71fc032b9e28ffdcf34e829583f232517fcbd2 | add CacheItemPolicy for backwards compat | alastairtree/LazyCache,alastairtree/LazyCache | LazyCache/CacheItemPolicy.cs | LazyCache/CacheItemPolicy.cs | using System;
using System.Linq;
using Microsoft.Extensions.Caching.Memory;
namespace LazyCache
{
[Obsolete(
"CacheItemPolicy was part of System.Runtime.Caching which is no longer used by LazyCache. " +
"This class is a fake used to maintain backward compatibility and will be removed in a later version."+
"Change to MemoryCacheEntryOptions instead")]
public class CacheItemPolicy : MemoryCacheEntryOptions
{
public PostEvictionCallbackRegistration RemovedCallback => PostEvictionCallbacks.FirstOrDefault();
}
} | mit | C# | |
7898ba4ad8bf6ffdd23a5f359f5ea49d9dc4338a | Add new configuration for ServiceContainer | phaetto/serviceable-objects | Examples/TestHttpCompositionConsoleApp/ConfigurationSources/ServiceContainerConfigurationSource.cs | Examples/TestHttpCompositionConsoleApp/ConfigurationSources/ServiceContainerConfigurationSource.cs | namespace TestHttpCompositionConsoleApp.ConfigurationSources
{
using System;
using Newtonsoft.Json;
using Serviceable.Objects.Composition.Graph;
using Serviceable.Objects.Composition.Graph.Stages.Configuration;
using Serviceable.Objects.Composition.Service;
using Serviceable.Objects.IO.NamedPipes.Server;
using Serviceable.Objects.IO.NamedPipes.Server.Configuration;
using Serviceable.Objects.Remote.Composition.ServiceContainer.Configuration;
public sealed class ServiceContainerConfigurationSource : IConfigurationSource
{
public string GetConfigurationValueForKey(IService service, GraphContext graphContext, GraphNodeContext graphNodeContext, Type type)
{
switch (type)
{
case var t when t == typeof(NamedPipeServerContext):
return JsonConvert.SerializeObject(new NamedPipeServerConfiguration
{
PipeName = "testpipe"
});
case var t when t == typeof(ServiceContainerContextConfiguration):
return JsonConvert.SerializeObject(new ServiceContainerContextConfiguration
{
ContainerName = "container-X",
OrchestratorName = "orchestrator-X",
});
default:
throw new InvalidOperationException($"Type {type.FullName} is not supported.");
}
}
}
}
| mit | C# | |
ee2cc1c2126a0aa147bdc412f053929d83401426 | Add AssignmentMinFlow.cs | or-tools/or-tools,google/or-tools,google/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools,google/or-tools,or-tools/or-tools,google/or-tools,google/or-tools,or-tools/or-tools,or-tools/or-tools | ortools/graph/samples/AssignmentMinFlow.cs | ortools/graph/samples/AssignmentMinFlow.cs | // Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START program]
// [START import]
using System;
using Google.OrTools.Graph;
// [END import]
public class AssignmentMinFlow
{
static void Main()
{
// [START solver]
// Instantiate a SimpleMinCostFlow solver.
MinCostFlow minCostFlow = new MinCostFlow();
// [END solver]
// [START data]
// Define four parallel arrays: sources, destinations, capacities, and unit costs
// between each pair.
int[] startNodes = {
0, 0, 0, 0,
1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,
5, 6, 7, 8};
int[] endNodes = {
1, 2, 3, 4,
5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8,
9, 9, 9, 9};
int[] capacities = {
1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1};
int[] unitCosts = {
0, 0, 0, 0,
90, 76, 75, 70, 35, 85, 55, 65, 125, 95, 90, 105, 45, 110, 95, 115,
0, 0, 0, 0};
int source = 0;
int sink = 9;
// Define an array of supplies at each node.
int[] supplies = {4, 0, 0, 0, 0, 0, 0, 0, 0, -4};
// [END data]
// [START constraints]
// Add each arc.
for (int i = 0; i < startNodes.Length; ++i)
{
int arc =
minCostFlow.AddArcWithCapacityAndUnitCost(startNodes[i], endNodes[i], capacities[i], unitCosts[i]);
if (arc != i)
throw new Exception("Internal error");
}
// Add node supplies.
for (int i = 0; i < supplies.Length; ++i)
{
minCostFlow.SetNodeSupply(i, supplies[i]);
}
// [END constraints]
// [START solve]
// Find the min cost flow.
MinCostFlow.Status status = minCostFlow.Solve();
// [END solve]
// [START print_solution]
if (status == MinCostFlow.Status.OPTIMAL)
{
Console.WriteLine("Total cost: " + minCostFlow.OptimalCost());
Console.WriteLine("");
for (int i = 0; i < minCostFlow.NumArcs(); ++i)
{
// Can ignore arcs leading out of source or into sink.
if (minCostFlow.Tail(i) != source && minCostFlow.Head(i) != sink) {
// Arcs in the solution have a flow value of 1. Their start and end nodes
// give an assignment of worker to task.
if (minCostFlow.Flow(i) > 0) {
Console.WriteLine("Worker " + minCostFlow.Tail(i) +
" assigned to task " + minCostFlow.Head(i) +
" Cost: " + minCostFlow.UnitCost(i));
}
}
}
}
else
{
Console.WriteLine("Solving the min cost flow problem failed.");
Console.WriteLine("Solver status: " + status);
}
// [END print_solution]
}
}
// [END program]
| apache-2.0 | C# | |
424462cc0cc61a17c75a83c57abb85763ceeb85d | Split operator draft. | Kostassoid/Nerve,Kostassoid/Nerve | src/main/Nerve-Core/Linking/Operators/SplitOperator.cs | src/main/Nerve-Core/Linking/Operators/SplitOperator.cs | // Copyright 2014 https://github.com/Kostassoid/Nerve
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Kostassoid.Nerve.Core.Linking.Operators
{
using System;
using System.Collections.Generic;
using Signal;
using Tools;
internal class SplitOperator<TIn, TOut> : AbstractOperator<TIn, TOut>
where TIn : class
where TOut : class
{
private readonly Func<TIn, IEnumerable<TOut>> _splitFunc;
public SplitOperator(ILink link, Func<TIn, IEnumerable<TOut>> splitFunc) : base(link)
{
_splitFunc = splitFunc;
}
public override void InternalProcess(ISignal<TIn> signal)
{
_splitFunc(signal.Body)
.ForEach(b => Next.Process(new Signal<TOut>(b, signal.StackTrace)));
}
}
} | apache-2.0 | C# | |
70c0d315ee5a614c081c6a37edf970fd39db9c25 | Add GenericShallowCopy utility to support MemberwiseClone() into an existing object. | zhukaixy/open3mod,zhukaixy/open3mod,dayo7116/open3mod,acgessler/open3mod,acgessler/open3mod,dayo7116/open3mod | open3mod/GenericShallowCopy.cs | open3mod/GenericShallowCopy.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
namespace open3mod
{
// Adapted from http://csharptest.net/372/how-to-implement-a-generic-shallow-clone-for-an-object-in-c/.
class GenericShallowCopy
{
/// <summary>
/// Shallow copy |instance| to |copy|. Use with care.
///
/// (This covers the case where we want to shallow copy into an existing object,
/// which is not handled by Object.MemberwiseCopy).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="copy"></param>
/// <param name="instance"></param>
/// <returns></returns>
public static void Copy<T>(T copy, T instance)
{
var type = instance.GetType();
var fields = new List<MemberInfo>();
if (type.GetCustomAttributes(typeof(SerializableAttribute), false).Length == 0)
{
var t = type;
while (t != typeof(Object))
{
Debug.Assert(t != null, "t != null");
fields.AddRange(
t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.DeclaredOnly));
t = t.BaseType;
}
}
else
{
fields.AddRange(FormatterServices.GetSerializableMembers(instance.GetType()));
}
var values = FormatterServices.GetObjectData(instance, fields.ToArray());
FormatterServices.PopulateObjectMembers(copy, fields.ToArray(), values);
}
}
}
| bsd-3-clause | C# | |
f85d8af6288cd3f4c83a0e45dd17e17cc64b09c5 | Add skeleton class | fvanroie/PS_OPNsense | Classes/Relayd.cs | Classes/Relayd.cs | using System;
using System.Management.Automation;
namespace OPNsense.Rlayd {
public class Host {
#region Parameters
#endregion Parameters
public Host () {
}
public Host (
) {
}
}
}
namespace OPNsense.Rlayd {
public class Protocol {
#region Parameters
#endregion Parameters
public Protocol () {
}
public Protocol (
) {
}
}
}
namespace OPNsense.Rlayd {
public class Table {
#region Parameters
#endregion Parameters
public Table () {
}
public Table (
) {
}
}
}
namespace OPNsense.Rlayd {
public class TableCheck {
#region Parameters
#endregion Parameters
public TableCheck () {
}
public TableCheck (
) {
}
}
}
namespace OPNsense.Rlayd {
public class VirtualServer {
#region Parameters
#endregion Parameters
public VirtualServer () {
}
public VirtualServer (
) {
}
}
}
| mit | C# | |
812a75fd50ed8f751f3b596a0a96ce29d0975b3d | Create EnumExtensions.cs | strvmarv/Extensions | EnumExtensions.cs | EnumExtensions.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Extensions
{
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
var attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null) return attr.Description;
}
}
return null;
}
}
}
| mit | C# | |
9edc37dd22dc35093f747ea71334ecae684e4168 | Simplify code. | vslsnap/roslyn,eriawan/roslyn,abock/roslyn,akrisiun/roslyn,jmarolf/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ljw1004/roslyn,tvand7093/roslyn,AmadeusW/roslyn,nguerrera/roslyn,jkotas/roslyn,lorcanmooney/roslyn,heejaechang/roslyn,tvand7093/roslyn,heejaechang/roslyn,KevinRansom/roslyn,bkoelman/roslyn,AmadeusW/roslyn,xoofx/roslyn,KevinRansom/roslyn,weltkante/roslyn,eriawan/roslyn,brettfo/roslyn,nguerrera/roslyn,drognanar/roslyn,dotnet/roslyn,KiloBravoLima/roslyn,AnthonyDGreen/roslyn,khyperia/roslyn,brettfo/roslyn,MattWindsor91/roslyn,AArnott/roslyn,pdelvo/roslyn,jhendrixMSFT/roslyn,AnthonyDGreen/roslyn,tvand7093/roslyn,aelij/roslyn,ErikSchierboom/roslyn,genlu/roslyn,jamesqo/roslyn,OmarTawfik/roslyn,swaroop-sridhar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,stephentoub/roslyn,amcasey/roslyn,dotnet/roslyn,bartdesmet/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,srivatsn/roslyn,AlekseyTs/roslyn,aelij/roslyn,Pvlerick/roslyn,Giftednewt/roslyn,KevinRansom/roslyn,mattwar/roslyn,sharwell/roslyn,Giftednewt/roslyn,aelij/roslyn,VSadov/roslyn,budcribar/roslyn,amcasey/roslyn,bbarry/roslyn,zooba/roslyn,natidea/roslyn,KirillOsenkov/roslyn,tmat/roslyn,tmeschter/roslyn,orthoxerox/roslyn,dpoeschl/roslyn,srivatsn/roslyn,jkotas/roslyn,wvdd007/roslyn,khyperia/roslyn,panopticoncentral/roslyn,Giftednewt/roslyn,yeaicc/roslyn,cston/roslyn,DustinCampbell/roslyn,balajikris/roslyn,reaction1989/roslyn,agocke/roslyn,kelltrick/roslyn,KiloBravoLima/roslyn,diryboy/roslyn,yeaicc/roslyn,a-ctor/roslyn,dpoeschl/roslyn,jmarolf/roslyn,vslsnap/roslyn,sharwell/roslyn,MatthieuMEZIL/roslyn,agocke/roslyn,davkean/roslyn,lorcanmooney/roslyn,weltkante/roslyn,tmat/roslyn,Pvlerick/roslyn,mavasani/roslyn,gafter/roslyn,mgoertz-msft/roslyn,robinsedlaczek/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,abock/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,TyOverby/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,srivatsn/roslyn,mavasani/roslyn,drognanar/roslyn,shyamnamboodiripad/roslyn,KevinH-MS/roslyn,ljw1004/roslyn,MattWindsor91/roslyn,physhi/roslyn,mmitche/roslyn,tannergooding/roslyn,orthoxerox/roslyn,jeffanders/roslyn,mattwar/roslyn,CaptainHayashi/roslyn,Pvlerick/roslyn,xasx/roslyn,cston/roslyn,natidea/roslyn,orthoxerox/roslyn,xoofx/roslyn,pdelvo/roslyn,paulvanbrenk/roslyn,KevinH-MS/roslyn,robinsedlaczek/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,davkean/roslyn,jeffanders/roslyn,akrisiun/roslyn,Hosch250/roslyn,jasonmalinowski/roslyn,kelltrick/roslyn,balajikris/roslyn,genlu/roslyn,lorcanmooney/roslyn,jcouv/roslyn,akrisiun/roslyn,tmat/roslyn,MatthieuMEZIL/roslyn,swaroop-sridhar/roslyn,MattWindsor91/roslyn,panopticoncentral/roslyn,xoofx/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,eriawan/roslyn,brettfo/roslyn,DustinCampbell/roslyn,budcribar/roslyn,davkean/roslyn,drognanar/roslyn,jcouv/roslyn,heejaechang/roslyn,gafter/roslyn,mattscheffer/roslyn,CyrusNajmabadi/roslyn,VSadov/roslyn,genlu/roslyn,wvdd007/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,jkotas/roslyn,gafter/roslyn,jeffanders/roslyn,yeaicc/roslyn,khyperia/roslyn,mattscheffer/roslyn,paulvanbrenk/roslyn,jmarolf/roslyn,AmadeusW/roslyn,bkoelman/roslyn,KirillOsenkov/roslyn,KiloBravoLima/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,xasx/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,CaptainHayashi/roslyn,CaptainHayashi/roslyn,Shiney/roslyn,kelltrick/roslyn,xasx/roslyn,Shiney/roslyn,AArnott/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,AArnott/roslyn,Hosch250/roslyn,paulvanbrenk/roslyn,a-ctor/roslyn,wvdd007/roslyn,jamesqo/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,jcouv/roslyn,MatthieuMEZIL/roslyn,bartdesmet/roslyn,vslsnap/roslyn,DustinCampbell/roslyn,balajikris/roslyn,amcasey/roslyn,mgoertz-msft/roslyn,jhendrixMSFT/roslyn,stephentoub/roslyn,mavasani/roslyn,dpoeschl/roslyn,OmarTawfik/roslyn,Shiney/roslyn,diryboy/roslyn,jamesqo/roslyn,jhendrixMSFT/roslyn,CyrusNajmabadi/roslyn,MattWindsor91/roslyn,zooba/roslyn,mattscheffer/roslyn,TyOverby/roslyn,diryboy/roslyn,pdelvo/roslyn,KevinH-MS/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,a-ctor/roslyn,bkoelman/roslyn,natidea/roslyn,zooba/roslyn,VSadov/roslyn,abock/roslyn,mmitche/roslyn,Hosch250/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,agocke/roslyn,robinsedlaczek/roslyn,AnthonyDGreen/roslyn,tmeschter/roslyn,reaction1989/roslyn,mattwar/roslyn,cston/roslyn,bbarry/roslyn,budcribar/roslyn,bbarry/roslyn,ljw1004/roslyn,MichalStrehovsky/roslyn | src/EditorFeatures/Core/Implementation/FindReferences/DefinitionLocation.NonNavigatingDefinitionLocation.cs | src/EditorFeatures/Core/Implementation/FindReferences/DefinitionLocation.NonNavigatingDefinitionLocation.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Editor.Implementation.FindReferences
{
internal partial class DefinitionLocation
{
/// <summary>
/// Implementation of a <see cref="DefinitionLocation"/> used for definitions
/// that cannot be navigated to. For example, C# and VB namespaces cannot be
/// navigated to.
/// </summary>
private sealed class NonNavigatingDefinitionLocation : DefinitionLocation
{
private readonly ImmutableArray<TaggedText> _originationParts;
public NonNavigatingDefinitionLocation(ImmutableArray<TaggedText> originationParts)
{
_originationParts = originationParts;
}
public override ImmutableArray<TaggedText> OriginationParts => _originationParts;
public override bool CanNavigateTo() => false;
public override bool TryNavigateTo() => false;
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Editor.Implementation.FindReferences
{
internal partial class DefinitionLocation
{
/// <summary>
/// Implementation of a <see cref="DefinitionLocation"/> used for definitions
/// that cannot be navigated to. For example, C# and VB namespaces cannot be
/// navigated to.
/// </summary>
private sealed class NonNavigatingDefinitionLocation : DefinitionLocation
{
private readonly ImmutableArray<TaggedText> _originationParts;
public NonNavigatingDefinitionLocation(ImmutableArray<TaggedText> originationParts)
{
_originationParts = originationParts;
}
public override ImmutableArray<TaggedText> OriginationParts => _originationParts;
public override bool CanNavigateTo()
{
return false;
}
public override bool TryNavigateTo()
{
return false;
}
}
}
}
| apache-2.0 | C# |
b2adc82a0549fb0e677b5e85311f12b10bb2c2a8 | Add a class to perform basic vector operations (addition, subtraction, scaling) for the optimization needs. | geoem/MSolve,geoem/MSolve | ISAAR.MSolve.Analyzers/Optimization/Commons/VectorOperations.cs | ISAAR.MSolve.Analyzers/Optimization/Commons/VectorOperations.cs | using System;
namespace ISAAR.MSolve.Analyzers.Optimization.Commons
{
public static class VectorOperations
{
public static double[] Add(double[] v1, double[] v2)
{
CheckDimensions(v1, v2);
double[] result = new double[v1.Length];
for (int i = 0; i < v1.Length; i++)
{
result[i] = v1[i] + v2[i];
}
return result;
}
public static double[] Scale(double scalar, double[] vector)
{
double[] result = new double[vector.Length];
for (int i = 0; i < vector.Length; i++)
{
result[i] = scalar * vector[i];
}
return result;
}
public static double[] Subtract(double[] v1, double[] v2)
{
CheckDimensions(v1, v2);
double[] result = new double[v1.Length];
for (int i = 0; i < v1.Length; i++)
{
result[i] = v1[i] - v2[i];
}
return result;
}
private static void CheckDimensions(double[] v1, double[] v2)
{
if (v1.Length != v2.Length)
{
throw new ArgumentException("Vectors must have equal lengths!");
}
}
}
}
| apache-2.0 | C# | |
da940fb7f8cae1806fbddb0c03f6aded1696948f | Create DNSflush.cs | bkief/DNSFlusher | DNSflush.cs | DNSflush.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace DNSFlusher
{
class DNSFlush
{
[DllImport("dnsapi.dll",EntryPoint="DnsFlushResolverCache")]
private static extern UInt32 DnsFlushResolverCache ();
public static void Flush() //This can be named whatever name you want and is the function you will call
{
UInt32 result = DnsFlushResolverCache();
System.Console.WriteLine(result);
}
}
}
| mit | C# | |
de91a0daa4f50bbc6aca8f651e3d8b59a6e20f7f | Create Problem6.cs | neilopet/projecteuler_cs | Problem6.cs | Problem6.cs | /*
* Problem #6
* The sum of the squares of the first ten natural numbers is,
* 1^2 + 2^2 + ... + 10^2 = 385
* The square of the sum of the first ten natural numbers is,
* (1 + 2 + ... + 10)^2 = 55^2 = 3025
* Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
* Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
using System;
using System.Collections.Generic;
public class Problem6
{
public void Main()
{
Int64 sum_of_squares = 0;
Int64 sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
sum_of_squares += (i*i);
}
Console.WriteLine( (sum * sum) - sum_of_squares );
}
}
| mit | C# | |
601a0a4b2822cd877129b835af594a49ada2ba0d | Add interface for common properties | lukecahill/NutritionTracker | food_tracker/IListItems.cs | food_tracker/IListItems.cs | namespace food_tracker {
public interface IListItems {
double calories { get; set; }
double amount { get; set; }
double fats { get; set; }
double saturatedFat { get; set; }
double carbohydrates { get; set; }
double sugar { get; set; }
double protein { get; set; }
double salt { get; set; }
double fibre { get; set; }
string name { get; set; }
int nutritionId { get; set; }
}
}
| mit | C# | |
08bf1eb01ba88d3054c6ba7ce9b4bf9a5d601996 | Create Log.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D/Log.cs | src/Draw2D/Log.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Draw2D
{
public static class Log
{
public static void WriteLine(string message)
{
Console.WriteLine(message);
}
}
}
| mit | C# | |
065cc9f83584cb1f3e38324fd6fd5bd1cdb0712c | Update Use.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | svg/Svg.Skia/Elements/Use.cs | svg/Svg.Skia/Elements/Use.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.
//
// Parts of this source file are adapted from the https://github.com/vvvv/SVG
using System;
using System.Reflection;
using SkiaSharp;
using Svg;
namespace Svg.Skia
{
internal struct Use
{
public SKMatrix matrix;
public Use(SvgUse svgUse, SvgVisualElement svgVisualElement)
{
matrix = SvgHelper.GetSKMatrix(svgUse.Transforms);
float x = svgUse.X.ToDeviceValue(null, UnitRenderingType.Horizontal, svgUse);
float y = svgUse.Y.ToDeviceValue(null, UnitRenderingType.Vertical, svgUse);
var skMatrixTranslateXY = SKMatrix.MakeTranslation(x, y);
SKMatrix.Concat(ref matrix, ref matrix, ref skMatrixTranslateXY);
var ew = svgUse.Width.ToDeviceValue(null, UnitRenderingType.Horizontal, svgUse);
var eh = svgUse.Height.ToDeviceValue(null, UnitRenderingType.Vertical, svgUse);
if (ew > 0 && eh > 0)
{
var _attributes = svgVisualElement.GetType().GetField("_attributes", BindingFlags.NonPublic | BindingFlags.Instance);
if (_attributes != null)
{
var attributes = _attributes.GetValue(svgVisualElement) as SvgAttributeCollection;
if (attributes != null)
{
var viewBox = attributes.GetAttribute<SvgViewBox>("viewBox");
//var viewBox = svgVisualElement.Attributes.GetAttribute<SvgViewBox>("viewBox");
if (viewBox != SvgViewBox.Empty && Math.Abs(ew - viewBox.Width) > float.Epsilon && Math.Abs(eh - viewBox.Height) > float.Epsilon)
{
var sw = ew / viewBox.Width;
var sh = eh / viewBox.Height;
var skMatrixTranslateSWSH = SKMatrix.MakeTranslation(sw, sh);
SKMatrix.Concat(ref matrix, ref matrix, ref skMatrixTranslateSWSH);
}
}
}
//else
//{
// throw new Exception("Can not get 'use' referenced element transform.");
//}
}
}
}
}
| // 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.
//
// Parts of this source file are adapted from the https://github.com/vvvv/SVG
using SkiaSharp;
using Svg;
namespace Svg.Skia
{
internal struct Use
{
public SKMatrix matrix;
public Use(SvgUse svgUse)
{
matrix = SvgHelper.GetSKMatrix(svgUse.Transforms);
}
}
}
| mit | C# |
990c0ebd6009e192145c60343cda24a91d73af0f | add ResponseTF.cs | ferventdesert/Hawk,zsewqsc/Hawk | Hawk.ETL/Plugins/Transformers/ResponseTF.cs | Hawk.ETL/Plugins/Transformers/ResponseTF.cs | using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Controls.WpfPropertyGrid.Attributes;
using Hawk.Core.Connectors;
using Hawk.Core.Utils;
using Hawk.Core.Utils.Plugins;
using Hawk.ETL.Crawlers;
using Hawk.ETL.Interfaces;
using Hawk.ETL.Plugins.Generators;
using Hawk.ETL.Process;
using HtmlAgilityPack;
namespace Hawk.ETL.Plugins.Transformers
{
[XFrmWork("获取请求详情", "使用网页采集器获取网页数据,拖入的列需要为超链接")]
public class ResponseTF : TransformerBase
{
protected readonly BuffHelper<HtmlDocument> buffHelper = new BuffHelper<HtmlDocument>(50);
protected readonly IProcessManager processManager;
private string _crawlerSelector;
private BfsGE generator;
private bool isfirst;
public ResponseTF()
{
processManager = MainDescription.MainFrm.PluginDictionary["模块管理"] as IProcessManager;
// var defaultcraw = processManager.CurrentProcessCollections.FirstOrDefault(d => d is SmartCrawler);
OneOutput = false;
//if (defaultcraw != null) CrawlerSelector = defaultcraw.Name;
PropertyChanged += (s, e) => { buffHelper.Clear(); };
}
private HttpHelper helper=new HttpHelper();
public override object TransformData(IFreeDocument datas)
{
HttpStatusCode code;
WebHeaderCollection responseHeader;
var http = helper.GetHtml(crawler.Http,out responseHeader, out code, datas[Column].ToString());
var keys = HeaderFilter.Split(' ');
foreach (var key in keys)
{
if (responseHeader.AllKeys.Contains(key))
datas.SetValue(key, responseHeader[key]);
}
return null;
}
[LocalizedDisplayName("爬虫选择")]
[LocalizedDescription("填写采集器或模块的名称")]
public string CrawlerSelector
{
get { return _crawlerSelector; }
set
{
if (_crawlerSelector != value)
{
buffHelper?.Clear();
}
_crawlerSelector = value;
}
}
[LocalizedCategory("头数据")]
public virtual string HeaderFilter { get; set; }
protected SmartCrawler crawler { get; set; }
public override bool Init(IEnumerable<IFreeDocument> datas)
{
crawler =
processManager.CurrentProcessCollections.FirstOrDefault(d => d.Name == CrawlerSelector) as SmartCrawler;
if (crawler != null)
{
IsMultiYield = crawler?.IsMultiData == ListType.List;
}
else
{
var task = processManager.CurrentProject.Tasks.FirstOrDefault(d => d.Name == CrawlerSelector);
if (task == null)
return false;
ControlExtended.UIInvoke(() => { task.Load(false); });
crawler =
processManager.CurrentProcessCollections.FirstOrDefault(d => d.Name == CrawlerSelector) as
SmartCrawler;
}
return crawler != null && base.Init(datas);
}
}
} | apache-2.0 | C# | |
3eaebfef265db9ee2e737c5e814a4bcc416eb34b | fix namespace | MetacoSA/NBitcoin,bitcoinbrisbane/NBitcoin,stratisproject/NStratis,you21979/NBitcoin,dangershony/NStratis,HermanSchoenfeld/NBitcoin,NicolasDorier/NBitcoin,lontivero/NBitcoin,thepunctuatedhorizon/BrickCoinAlpha.0.0.1,MetacoSA/NBitcoin | NBitcoin/Protocol/Payloads/RejectPayload.cs | NBitcoin/Protocol/Payloads/RejectPayload.cs | using NBitcoin.DataEncoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.Protocol
{
public enum RejectCode : byte
{
Malformed = 0x01,
Invalid = 0x10,
Obsolete = 0x11,
Duplicate = 0x12,
NonStandard = 0x40,
Dust = 0x41,
Insufficientfee = 0x42,
Checkpoint = 0x43
}
[Payload("reject")]
public class RejectPayload : Payload
{
VarString _Message= new VarString();
public string Message
{
get
{
return Encoders.ASCII.EncodeData(_Message.GetString(true));
}
set
{
_Message = new VarString(Encoders.ASCII.DecodeData(value));
}
}
byte _Code;
public RejectCode Code
{
get
{
return (RejectCode)_Code;
}
set
{
_Code = (byte)value;
}
}
VarString _Reason= new VarString();
public string Reason
{
get
{
return Encoders.ASCII.EncodeData(_Reason.GetString(true));
}
set
{
_Reason = new VarString(Encoders.ASCII.DecodeData(value));
}
}
public override void ReadWriteCore(BitcoinStream stream)
{
stream.ReadWrite(ref _Message);
stream.ReadWrite(ref _Code);
stream.ReadWrite(ref _Reason);
}
}
}
| using NBitcoin.DataEncoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.Protocol.Payloads
{
public enum RejectCode : byte
{
Malformed = 0x01,
Invalid = 0x10,
Obsolete = 0x11,
Duplicate = 0x12,
NonStandard = 0x40,
Dust = 0x41,
Insufficientfee = 0x42,
Checkpoint = 0x43
}
[Payload("reject")]
public class RejectPayload : Payload
{
VarString _Message= new VarString();
public string Message
{
get
{
return Encoders.ASCII.EncodeData(_Message.GetString(true));
}
set
{
_Message = new VarString(Encoders.ASCII.DecodeData(value));
}
}
byte _Code;
public RejectCode Code
{
get
{
return (RejectCode)_Code;
}
set
{
_Code = (byte)value;
}
}
VarString _Reason= new VarString();
public string Reason
{
get
{
return Encoders.ASCII.EncodeData(_Reason.GetString(true));
}
set
{
_Reason = new VarString(Encoders.ASCII.DecodeData(value));
}
}
public override void ReadWriteCore(BitcoinStream stream)
{
stream.ReadWrite(ref _Message);
stream.ReadWrite(ref _Code);
stream.ReadWrite(ref _Reason);
}
}
}
| mit | C# |
ed1d50222ee2f0932ed35f50c3f99cb001264434 | Add DocumentDb configuration | kotorihq/kotori-core | KotoriCore/Configuration/DocumentDb.cs | KotoriCore/Configuration/DocumentDb.cs | namespace KotoriCore.Configuration
{
/// <summary>
/// Document Db connection string.
/// </summary>
public class DocumentDb
{
/// <summary>
/// Gets or sets the end point.
/// </summary>
/// <value>The end point.</value>
public string EndPoint { get; set; }
/// <summary>
/// Gets or sets the authorization key.
/// </summary>
/// <value>The authorization key.</value>
public string AuthorizationKey { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
/// <value>The database.</value>
public string Database { get; set; }
/// <summary>
/// Gets or sets the collection.
/// </summary>
/// <value>The collection.</value>
public string Collection { get; set; }
}
}
| mit | C# | |
b3139fe4eed37407967c0a039c6f50ba2ddb3f46 | Adjust size of disable-able widget | jlewin/MatterControl,tellingmachine/MatterControl,CodeMangler/MatterControl,ddpruitt/MatterControl,ddpruitt/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,MatterHackers/MatterControl,tellingmachine/MatterControl,rytz/MatterControl,ddpruitt/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,MatterHackers/MatterControl,MatterHackers/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,rytz/MatterControl,CodeMangler/MatterControl,jlewin/MatterControl,rytz/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,CodeMangler/MatterControl,mmoening/MatterControl,jlewin/MatterControl | CustomWidgets/DisableableWidget.cs | CustomWidgets/DisableableWidget.cs | using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.MatterControl.CustomWidgets
{
public class DisableableWidget : GuiWidget
{
public GuiWidget disableOverlay;
public DisableableWidget()
{
HAnchor = Agg.UI.HAnchor.ParentLeftRight;
VAnchor = Agg.UI.VAnchor.FitToChildren;
this.Margin = new BorderDouble(3);
disableOverlay = new GuiWidget(HAnchor.ParentLeftRight, VAnchor.ParentBottomTop);
disableOverlay.Visible = false;
base.AddChild(disableOverlay);
}
public enum EnableLevel { Disabled, ConfigOnly, Enabled };
public void SetEnableLevel(EnableLevel enabledLevel)
{
disableOverlay.BackgroundColor = new RGBA_Bytes(ActiveTheme.Instance.TertiaryBackgroundColor, 160);
switch (enabledLevel)
{
case EnableLevel.Disabled:
disableOverlay.Margin = new BorderDouble(0);
disableOverlay.Visible = true;
break;
case EnableLevel.ConfigOnly:
disableOverlay.Margin = new BorderDouble(0, 0, 0, 26);
disableOverlay.Visible = true;
break;
case EnableLevel.Enabled:
disableOverlay.Visible = false;
break;
}
}
public override void AddChild(GuiWidget childToAdd, int indexInChildrenList = -1)
{
if (indexInChildrenList == -1)
{
// put it under the disableOverlay
base.AddChild(childToAdd, Children.Count - 1);
}
else
{
base.AddChild(childToAdd, indexInChildrenList);
}
}
}
}
| using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatterHackers.MatterControl.CustomWidgets
{
public class DisableableWidget : GuiWidget
{
public GuiWidget disableOverlay;
public DisableableWidget()
{
HAnchor = Agg.UI.HAnchor.ParentLeftRight;
VAnchor = Agg.UI.VAnchor.FitToChildren;
this.Margin = new BorderDouble(3);
disableOverlay = new GuiWidget(HAnchor.ParentLeftRight, VAnchor.ParentBottomTop);
disableOverlay.Visible = false;
base.AddChild(disableOverlay);
}
public enum EnableLevel { Disabled, ConfigOnly, Enabled };
public void SetEnableLevel(EnableLevel enabledLevel)
{
disableOverlay.BackgroundColor = new RGBA_Bytes(ActiveTheme.Instance.TertiaryBackgroundColor, 160);
switch (enabledLevel)
{
case EnableLevel.Disabled:
disableOverlay.Margin = new BorderDouble(0);
disableOverlay.Visible = true;
break;
case EnableLevel.ConfigOnly:
disableOverlay.Margin = new BorderDouble(0, 0, 0, 20);
disableOverlay.Visible = true;
break;
case EnableLevel.Enabled:
disableOverlay.Visible = false;
break;
}
}
public override void AddChild(GuiWidget childToAdd, int indexInChildrenList = -1)
{
if (indexInChildrenList == -1)
{
// put it under the disableOverlay
base.AddChild(childToAdd, Children.Count - 1);
}
else
{
base.AddChild(childToAdd, indexInChildrenList);
}
}
}
}
| bsd-2-clause | C# |
9882c808042b77126a93c97e5d4f3b7ea39e3738 | Add test for helper equality comparer too | EamonNerbonne/ValueUtils,EamonNerbonne/ValueUtils,EamonNerbonne/ValueUtils | ValueUtilsTest/FieldwiseEqualityComparerTest.cs | ValueUtilsTest/FieldwiseEqualityComparerTest.cs | using System.Collections.Generic;
using ExpressionToCodeLib;
using ValueUtils;
using Xunit;
namespace ValueUtilsTest
{
public sealed class FieldwiseEqualityComparerTest
{
static readonly IEqualityComparer<SampleStruct> eqStruct = FieldwiseEqualityComparer<SampleStruct>.Instance;
static readonly IEqualityComparer<SampleClass> eqClass = FieldwiseEqualityComparer<SampleClass>.Instance;
[Fact]
public void IdenticalValuesAreEqual()
=> PAssert.That(() => eqStruct.Equals(new SampleStruct(1, 2, "3", 4), new SampleStruct(1, 2, "3", 4)));
[Fact]
public void IdenticalValuesHaveEqualHashCode()
// ReSharper disable once EqualExpressionComparison
=> PAssert.That(() => eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 4)) == eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 4)));
[Fact]
public void IdenticallyValuedClassesHaveEqualHashCodeAndAreEqual()
// ReSharper disable once EqualExpressionComparison
{
var objA = new SampleClass { AnEnum = SampleEnum.P, NullableField = 4, PlainStruct = { Bla = 2 } };
var objB = new SampleClass { AnEnum = SampleEnum.P, NullableField = 4, PlainStruct = { Bla = 2 } };
PAssert.That(() => objA != objB && eqClass.Equals(objA, objB) && eqClass.GetHashCode(objA) == eqClass.GetHashCode(objB));
}
[Fact]
public void OneChangedMemberCausesInequality()
{
PAssert.That(() => !eqStruct.Equals(new SampleStruct(1, 2, "3", 4), new SampleStruct(11, 2, "3", 4)));
PAssert.That(() => !eqStruct.Equals(new SampleStruct(1, 2, "3", 4), new SampleStruct(1, 12, "3", 4)));
PAssert.That(() => !eqStruct.Equals(new SampleStruct(1, 2, "3", 4), new SampleStruct(1, 2, "13", 4)));
PAssert.That(() => !eqStruct.Equals(new SampleStruct(1, 2, "3", 4), new SampleStruct(1, 2, "3", 14)));
}
[Fact]
public void OneChangedMemberCausesHashCodeInequality()
{
PAssert.That(() => eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 4)) != eqStruct.GetHashCode(new SampleStruct(11, 2, "3", 4)));
PAssert.That(() => eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 4)) != eqStruct.GetHashCode(new SampleStruct(1, 12, "3", 4)));
PAssert.That(() => eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 4)) != eqStruct.GetHashCode(new SampleStruct(1, 2, "13", 4)));
PAssert.That(() => eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 4)) != eqStruct.GetHashCode(new SampleStruct(1, 2, "3", 14)));
}
[Fact]
public void CanCheckEqualityWithNull()
{
PAssert.That(() => !eqClass.Equals(new SampleClass(), null));
PAssert.That(() => !eqClass.Equals(null, new SampleClass()));
}
}
}
| apache-2.0 | C# | |
1e5114cd7b200fa4d17085f19ea3c875b4da0852 | Add PrimaryScheduleName config option | vbfox/Opserver,wuanunet/Opserver,IDisposable/Opserver,Janiels/Opserver,Janiels/Opserver,GABeech/Opserver,GABeech/Opserver,a9261/Opserver,volkd/Opserver,maurobennici/Opserver,hotrannam/Opserver,mqbk/Opserver,18098924759/Opserver,maurobennici/Opserver,jeddytier4/Opserver,hotrannam/Opserver,manesiotise/Opserver,opserver/Opserver,rducom/Opserver,mqbk/Opserver,vebin/Opserver,volkd/Opserver,michaelholzheimer/Opserver,huoxudong125/Opserver,18098924759/Opserver,huoxudong125/Opserver,dteg/Opserver,jeddytier4/Opserver,IDisposable/Opserver,VictoriaD/Opserver,geffzhang/Opserver,wuanunet/Opserver,baflynn/Opserver,a9261/Opserver,VictoriaD/Opserver,opserver/Opserver,dteg/Opserver,vbfox/Opserver,rducom/Opserver,vebin/Opserver,opserver/Opserver,geffzhang/Opserver,manesiotise/Opserver,manesiotise/Opserver,michaelholzheimer/Opserver,baflynn/Opserver | Opserver.Core/Settings/PagerDutySettings.cs | Opserver.Core/Settings/PagerDutySettings.cs | using System.Collections.Generic;
namespace StackExchange.Opserver
{
public class PagerDutySettings : Settings<PagerDutySettings>
{
public override bool Enabled
{
get { return APIKey.HasValue(); }
}
public string APIKey { get; set; }
public string APIBaseUrl { get; set; }
public List<EmailMapping> UserNameMap { get; set; }
public int OnCallToShow { get; set; }
public int DaysToCache { get; set; }
public string HeaderHtml { get; set; }
public string PrimaryScheduleName { get; set; }
public PagerDutySettings()
{
// Defaults
OnCallToShow = 2;
DaysToCache = 60;
}
}
public class EmailMapping
{
public string OpServerName { get; set; }
public string EmailUser { get; set; }
}
}
| using System.Collections.Generic;
namespace StackExchange.Opserver
{
public class PagerDutySettings : Settings<PagerDutySettings>
{
public override bool Enabled
{
get { return APIKey.HasValue(); }
}
public string APIKey { get; set; }
public string APIBaseUrl { get; set; }
public List<EmailMapping> UserNameMap { get; set; }
public int OnCallToShow { get; set; }
public int DaysToCache { get; set; }
public string HeaderHtml { get; set; }
public PagerDutySettings()
{
// Defaults
OnCallToShow = 2;
DaysToCache = 60;
}
}
public class EmailMapping
{
public string OpServerName { get; set; }
public string EmailUser { get; set; }
}
}
| mit | C# |
457766740dc15c67a800fb143b8bb377f3b5894f | Add extension to handle MPMediaItem | mike-rowley/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,martijn00/XamarinMediaManager | MediaManager/Platforms/Ios/Media/MPMediaItemExtensions.cs | MediaManager/Platforms/Ios/Media/MPMediaItemExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using CoreGraphics;
using MediaManager.Library;
using MediaPlayer;
namespace MediaManager.Platforms.Ios.Media
{
public static class MPMediaItemExtensions
{
public static IMediaItem ToMediaItem(this MPMediaItem item)
{
var output = new MediaItem
{
MediaType = MediaType.Audio,
Album = item.AlbumTitle,
Artist = item.Artist,
Compilation = null,
Composer = item.Composer,
Duration = TimeSpan.FromSeconds(item.PlaybackDuration),
Genre = item.Genre,
Title = item.Title,
AlbumArtist = item.AlbumArtist,
DiscNumber = item.DiscNumber,
MediaUri = item.AssetURL.ToString(),
NumTracks = item.AlbumTrackCount,
UserRating = item.Rating,
Id = item.PersistentID.ToString()
};
if (item.ReleaseDate != null)
output.Date = (DateTime)item.ReleaseDate;
if (item.Artwork != null)
output.Image = item.Artwork.ImageWithSize(new CGSize(300, 300));
if (output.Date != null)
output.Year = output.Date.Year;
return output;
}
public static IEnumerable<IMediaItem> ToMediaItems(this IEnumerable<MPMediaItem> items)
{
return items
.Where(i => i.AssetURL != null && i.IsCloudItem == false && i.HasProtectedAsset == false)
.Select(i => i.ToMediaItem());
}
}
}
| mit | C# | |
822f3a6788755a3accd82277b51c81b325b90613 | create future branch which bases on SuperSocket 1.5 | wangzheng888520/SuperWebSocket,v-rawang/SuperWebSocket,jmptrader/SuperWebSocket,wangzheng888520/SuperWebSocket,zhangwei900808/SuperWebSocket,jmptrader/SuperWebSocket,v-rawang/SuperWebSocket,v-rawang/SuperWebSocket,jogibear9988/SuperWebSocket,zhangwei900808/SuperWebSocket,jogibear9988/SuperWebSocket,kerryjiang/SuperWebSocket,v-rawang/SuperWebSocket,kerryjiang/SuperWebSocket | future/SuperWebSocket/Extensions.cs | future/SuperWebSocket/Extensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SuperWebSocket
{
public static partial class Extensions
{
private readonly static char[] m_CrCf;
static Extensions()
{
m_CrCf = "\r\n".ToArray();
}
public static void AppendFormatWithCrCf(this StringBuilder builder, string format, object arg)
{
builder.AppendFormat(format, arg);
builder.Append(m_CrCf);
}
public static void AppendFormatWithCrCf(this StringBuilder builder, string format, params object[] args)
{
builder.AppendFormat(format, args);
builder.Append(m_CrCf);
}
public static void AppendWithCrCf(this StringBuilder builder, string content)
{
builder.Append(content);
builder.Append(m_CrCf);
}
public static void AppendWithCrCf(this StringBuilder builder)
{
builder.Append(m_CrCf);
}
}
}
| apache-2.0 | C# | |
5149e3bdad0f09446abc8d8184631e0f4a759366 | Add TeamUpdateService with events and not yet finished TeamUpdate handler. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | src/NadekoBot/Modules/Forum/Services/TeamUpdateService.cs | src/NadekoBot/Modules/Forum/Services/TeamUpdateService.cs | using Discord.WebSocket;
using GommeHDnetForumAPI.DataModels;
using GommeHDnetForumAPI.DataModels.Collections;
using GommeHDnetForumAPI.DataModels.Entities;
using Mitternacht.Services;
using Mitternacht.Services.Impl;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Mitternacht.Modules.Forum.Services
{
public class TeamUpdateService : INService
{
private readonly DiscordSocketClient _client;
private readonly DbService _db;
private readonly ForumService _fs;
private readonly StringService _ss;
private UserCollection _staff;
private readonly Task _teamUpdateTask;
public event Func<UserInfo[], Task> TeamRankAdded = ui => Task.CompletedTask;
public event Func<UserInfo[], Task> TeamRankChanged = ui => Task.CompletedTask;
public event Func<UserInfo[], Task> TeamRankRemoved = ui => Task.CompletedTask;
public TeamUpdateService(DiscordSocketClient client, DbService db, ForumService fs, StringService ss)
{
_client = client;
_db = db;
_fs = fs;
_ss = ss;
_staff = new UserCollection();
_teamUpdateTask = Task.Run(async () =>
{
while (true)
{
await DoTeamUpdate();
await Task.Delay(30 * 1000);
}
});
}
public async Task DoTeamUpdate()
{
if (_fs.Forum == null) return;
var staff = await _fs.Forum.GetMembersList(MembersListType.Staff).ConfigureAwait(false);
var rankAdded = staff.Where(ui => staff.All(ui2 => ui2.Id != ui.Id)).ToArray();
var rankChanged = _staff.Where(ui => staff.Any(ui2 => ui2.Id == ui.Id)).ToArray();
var rankRemoved = _staff.Where(ui => staff.All(ui2 => ui2.Id != ui.Id)).ToArray();
await TeamRankAdded.Invoke(rankAdded).ConfigureAwait(false);
await TeamRankChanged.Invoke(rankChanged).ConfigureAwait(false);
await TeamRankRemoved.Invoke(rankRemoved).ConfigureAwait(false);
using (var uow = _db.UnitOfWork)
{
foreach (var (guildId, tuChId, tuMPrefix) in uow.GuildConfigs.GetAll().Where(gc => gc.TeamUpdateChannelId.HasValue).Select(gc => (GuildId: gc.GuildId, TeamUpdateChannelId: gc.TeamUpdateChannelId.Value, TeamUpdateMessagePrefix: gc.TeamUpdateMessagePrefix)))
{
var guild = _client.GetGuild(guildId);
if (guild == null) continue;
var tuCh = guild.GetTextChannel(tuChId);
if (tuCh == null) continue;
var prefix = string.IsNullOrWhiteSpace(tuMPrefix) ? "" : tuMPrefix;
}
}
_staff = staff;
}
private string GetText(string key, ulong? guildId, params string[] replacements)
=> _ss.GetText(key, guildId, "forum", replacements);
}
}
| mit | C# | |
ab59ee7ba9ceec96330bb5d92d858e5fe86954bc | Create Reverse.cs | SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming | Kattis-Solutions/Reverse.cs | Kattis-Solutions/Reverse.cs | using System;
namespace Reverse
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for(int i = 0; i < n; i++) { arr[i] = int.Parse(Console.ReadLine()); }
for(int i = n - 1; i >= 0; i--) { Console.WriteLine(arr[i]); }
}
}
}
| mit | C# | |
ff224b1577001c444fd6431eec42b31514f715f1 | Solve Average 1 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/1005/1005.cs | solutions/uri/1005/1005.cs | using System;
using System.Collections.Generic;
class Solution {
static void Main() {
double a, b;
string val;
val = Console.ReadLine();
a = Convert.ToDouble(val);
val = Console.ReadLine();
b = Convert.ToDouble(val);
Console.Write(
"MEDIA = {0:F5}{1}",
(a * 3.5 + b * 7.5) / 11.0,
Environment.NewLine
);
}
}
| mit | C# | |
84551162dcf9c8c37a0f0b0bcd2ac1e90cb8b271 | Create Problem120.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem120.cs | Problems/Problem120.cs | using System;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem120
{
private int r(int a, int n)
{
// ( (a-1)^n + (a+1)^n ) % a*a
// = ( ((a-1)^n) % a*a + ((a+1)^n) % a*a ) % a*a
int sq_a = a * a;
return ((int)BigInteger.ModPow(a - 1, n, sq_a) + (int)BigInteger.ModPow(a + 1, n, sq_a)) % (sq_a);
}
public void Run()
{
BigInteger sum = 0;
int max_r, current_r;
for (int a = 3; a <= 1000; a++)
{
max_r = int.MinValue;
for (int n = 3; n <= 3*a; n++)
{
current_r = r(a, n);
max_r = Math.Max(max_r, current_r);
}
//Console.WriteLine("r_max(" + a.ToString() + ")= " + max_r.ToString());
sum += max_r;
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
| mit | C# | |
bab5ca7821a907c4613833d4f7cb975915db1ac5 | add tests for OptionExtensions | OlegKleyman/AlphaDev,OlegKleyman/AlphaDev,OlegKleyman/AlphaDev | tests/unit/AlphaDev.Core.Tests.Unit/Extensions/OptionExtensionTests.cs | tests/unit/AlphaDev.Core.Tests.Unit/Extensions/OptionExtensionTests.cs | using AlphaDev.Core.Extensions;
using FluentAssertions;
using Optional;
using Xunit;
namespace AlphaDev.Core.Tests.Unit.Extensions
{
public class OptionExtensionTests
{
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public void MapToActionOnSingleValuedOptionWithNoActionParametersShouldExecuteActionWhenSome(bool some, bool expected)
{
var option = default(object).SomeWhen(o => some);
var flag = false;
option.MapToAction(() => flag = true);
flag.Should().Be(expected);
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public void MapToActionOnWithExceptionValuedOptionWithNoActionParametersShouldExecuteActionWhenSome(bool some, bool expected)
{
var option = default(object).SomeWhen(o => some, default(object));
var flag = false;
option.MapToAction(() => flag = true);
flag.Should().Be(expected);
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public void MapToActionOnSingleValuedOptionWithValueActionParameterShouldExecuteActionWhenSome(bool some, bool expected)
{
var option = default(object).SomeWhen(o => some);
var flag = false;
option.MapToAction(x => flag = true);
flag.Should().Be(expected);
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public void MapToActionOnWithExceptionValuedOptionWithValueActionParameterShouldExecuteActionWhenSome(bool some, bool expected)
{
var option = default(object).SomeWhen(o => some, default(object));
var flag = false;
option.MapToAction(x => flag = true);
flag.Should().Be(expected);
}
[Fact]
public void MapToActionOnSingleValuedOptionWithNoActionParametersShouldReturnOption()
{
var option = default(object).Some();
option.MapToAction(() => { }).Should().Be(option);
}
[Fact]
public void MapToActionOnSingleValuedOptionWithValueActionParameterShouldReturnOption()
{
var option = default(object).Some();
option.MapToAction(x => { }).Should().Be(option);
}
[Fact]
public void MapToActionOnWithExceptionWithExceptionValuedOptionWithNoActionParametersShouldReturnOption()
{
var option = default(object).Some().WithException(default(object));
option.MapToAction(() => { }).Should().Be(option);
}
[Fact]
public void MapToActionOnWithExceptionWithExceptionValuedOptionWithValueActionParameterShouldReturnOption()
{
var option = default(object).Some().WithException(default(object));
option.MapToAction(x => { }).Should().Be(option);
}
}
}
| unlicense | C# | |
0b01bce34d7cedd2ea50ada3038e9a33c7549ac6 | Add DirectiveTests | Carbon/Css | src/Carbon.Css.Tests/DirectiveTests.cs | src/Carbon.Css.Tests/DirectiveTests.cs | using Xunit;
namespace Carbon.Css.Tests
{
public class DirectiveTests
{
[Fact]
public void ParsePartial()
{
var sheet = StyleSheet.Parse(@"
//= partial
div { color: blue; }
"); // Prevents standalone compilation
Assert.Equal("div { color: blue; }", sheet.ToString());
}
}
} | mit | C# | |
c970db8640e4320ae860785abb3617dba42b7671 | Create MyFunctions.cs | Excel-DNA/IntelliSense | CustomAddin/MyFunctions.cs | CustomAddin/MyFunctions.cs | using System;
using ExcelDna.Integration;
namespace ExcelDna.CustomAddin
{
public class MyFunctions
{
[ExcelFunction(Description = "A useful test function that multiply two numbers, and returns the product.")]
public static double MultiplyThem(
[ExcelArgument(Name = "Augend", Description = "is the first number, to which will be multiplied")] double v1,
[ExcelArgument(Name = "Addend", Description = "is the second number that will be multiplied")] double v2)
{
return v1 * v2;
}
}
}
| mit | C# | |
cfe2e378af6484b2889b4648bca6c02ac054ee28 | Update NUnit runner. | Redth/Cake.FileHelpers,Redth/Cake.FileHelpers | build.cake | build.cake | #tool nuget:?package=NUnit.Runners&version=3.6.0
var sln = "./Cake.FileHelpers.sln";
var nuspec = "./Cake.FileHelpers.nuspec";
var version = Argument ("version", "1.0.0.0");
var target = Argument ("target", "lib");
var configuration = Argument("configuration", "Release");
Task ("lib").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = configuration);
});
Task ("nuget").IsDependentOn ("unit-tests").Does (() =>
{
CreateDirectory ("./nupkg/");
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./nupkg/",
Version = version,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task ("push").IsDependentOn ("nuget").Does (() =>
{
// Get the newest (by last write time) to publish
var newestNupkg = GetFiles ("nupkg/*.nupkg")
.OrderBy (f => new System.IO.FileInfo (f.FullPath).LastWriteTimeUtc)
.LastOrDefault ();
var apiKey = TransformTextFile ("./.nugetapikey").ToString ();
NuGetPush (newestNupkg, new NuGetPushSettings {
Verbosity = NuGetVerbosity.Detailed,
ApiKey = apiKey
});
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
DeleteFiles ("./**/*.apk");
});
Task("unit-tests").IsDependentOn("lib").Does(() =>
{
NUnit3("./**/bin/"+ configuration + "/*.Tests.dll");
});
Task ("Default")
.IsDependentOn ("nuget");
RunTarget (target);
| #tool nuget:?package=NUnit.Runners&version=2.6.4
var sln = "./Cake.FileHelpers.sln";
var nuspec = "./Cake.FileHelpers.nuspec";
var version = Argument ("version", "1.0.0.0");
var target = Argument ("target", "lib");
var configuration = Argument("configuration", "Release");
Task ("lib").Does (() =>
{
NuGetRestore (sln);
DotNetBuild (sln, c => c.Configuration = configuration);
});
Task ("nuget").IsDependentOn ("unit-tests").Does (() =>
{
CreateDirectory ("./nupkg/");
NuGetPack (nuspec, new NuGetPackSettings {
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./nupkg/",
Version = version,
// NuGet messes up path on mac, so let's add ./ in front again
BasePath = "././",
});
});
Task ("push").IsDependentOn ("nuget").Does (() =>
{
// Get the newest (by last write time) to publish
var newestNupkg = GetFiles ("nupkg/*.nupkg")
.OrderBy (f => new System.IO.FileInfo (f.FullPath).LastWriteTimeUtc)
.LastOrDefault ();
var apiKey = TransformTextFile ("./.nugetapikey").ToString ();
NuGetPush (newestNupkg, new NuGetPushSettings {
Verbosity = NuGetVerbosity.Detailed,
ApiKey = apiKey
});
});
Task ("clean").Does (() =>
{
CleanDirectories ("./**/bin");
CleanDirectories ("./**/obj");
CleanDirectories ("./**/Components");
CleanDirectories ("./**/tools");
DeleteFiles ("./**/*.apk");
});
Task("unit-tests").IsDependentOn("lib").Does(() =>
{
NUnit("./**/bin/"+ configuration + "/*.Tests.dll");
});
Task ("Default")
.IsDependentOn ("nuget");
RunTarget (target); | apache-2.0 | C# |
09e7048803df43c3f5f210e79f0989f8bc22a6bd | Fix #5 | uheerme/core,uheerme/core,uheerme/core | Samesound.Services/MusicService.cs | Samesound.Services/MusicService.cs | using Samesound.Core;
using Samesound.Data;
using Samesound.Services.Infrastructure;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace Samesound.Services
{
public class MusicService : Service<Music>
{
public MusicService(SamesoundContext db) : base(db) { }
public virtual async Task<ICollection<Music>> Paginate(int skip, int take)
{
return await Db.Musics
.OrderBy(m => m.Id)
.Skip(skip)
.Take(take)
.ToListAsync();
}
}
}
| mit | C# | |
cb4f760205dbcc878e35ec6595bde5ce6c3057a2 | change command line name of IISFtpInstaller | Lone-Coder/letsencrypt-win-simple | letsencrypt-win-simple/Plugins/InstallationPlugins/IISFtpInstaller.cs | letsencrypt-win-simple/Plugins/InstallationPlugins/IISFtpInstaller.cs | using PKISharp.WACS.Clients;
using PKISharp.WACS.Plugins.Base;
using PKISharp.WACS.Plugins.Interfaces;
using PKISharp.WACS.Services;
using System;
using static PKISharp.WACS.Clients.IISClient;
namespace PKISharp.WACS.Plugins.InstallationPlugins
{
class IISFtpInstallerFactory : BaseInstallationPluginFactory<IISFtpInstaller>
{
private IISClient _iisClient;
public IISFtpInstallerFactory(ILogService log, IISClient iisClient) :
base(log, "iisftp", "Create or update ftps bindings in IIS")
{
_iisClient = iisClient;
}
public override bool CanInstall(ScheduledRenewal renewal) => _iisClient.Version.Major > 8;
public override void Aquire(ScheduledRenewal renewal, IOptionsService optionsService, IInputService inputService, RunLevel runLevel)
{
var chosen = inputService.ChooseFromList("Choose ftp site to bind the certificate to",
_iisClient.FtpSites,
x => new Choice<long>(x.Id) { Description = x.Name, Command = x.Id.ToString() },
false);
renewal.Binding.InstallationSiteId = chosen;
}
public override void Default(ScheduledRenewal renewal, IOptionsService optionsService)
{
var installationSiteId = optionsService.TryGetLong(nameof(optionsService.Options.InstallationSiteId), optionsService.Options.InstallationSiteId);
if (installationSiteId != null)
{
var site = _iisClient.GetFtpSite(installationSiteId.Value); // Throws exception when not found
renewal.Binding.InstallationSiteId = site.Id;
}
else
{
throw new Exception($"Missing parameter --{nameof(optionsService.Options.InstallationSiteId).ToLower()}");
}
}
}
class IISFtpInstaller : IInstallationPlugin
{
private ScheduledRenewal _renewal;
private IISClient _iisClient;
public IISFtpInstaller(ScheduledRenewal renewal, IISClient iisClient)
{
_iisClient = iisClient;
_renewal = renewal;
}
void IInstallationPlugin.Install(CertificateInfo newCertificate, CertificateInfo oldCertificate)
{
_iisClient.UpdateFtpSite(_renewal.Binding, SSLFlags.None, newCertificate, oldCertificate);
}
}
}
| apache-2.0 | C# | |
b343a1a0145bf7e81c797a31c53ad490aff3f451 | Add missing file | Ninputer/VBF | src/Compilers/Compilers.Parsers.Combinators/ConvertHelper.cs | src/Compilers/Compilers.Parsers.Combinators/ConvertHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace VBF.Compilers.Parsers.Combinators
{
class ConvertHelper<TFrom, TTo>
{
private static Func<TFrom, TTo> s_CastFunc;
static ConvertHelper()
{
var source = Expression.Parameter(typeof(TFrom), "source");
s_CastFunc = Expression.Lambda<Func<TFrom, TTo>>(Expression.Convert(source, typeof(TTo)), source).Compile();
}
public static TTo Convert(TFrom source)
{
return s_CastFunc(source);
}
}
}
| apache-2.0 | C# | |
4737fcd53fb6a863a234fc1a9befabc141352f68 | Add comments | shyamnamboodiripad/roslyn,gafter/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,weltkante/roslyn,physhi/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,eriawan/roslyn,heejaechang/roslyn,bartdesmet/roslyn,tmat/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,wvdd007/roslyn,gafter/roslyn,panopticoncentral/roslyn,eriawan/roslyn,wvdd007/roslyn,bartdesmet/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,diryboy/roslyn,diryboy/roslyn,stephentoub/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,physhi/roslyn,weltkante/roslyn,sharwell/roslyn,physhi/roslyn,panopticoncentral/roslyn,tmat/roslyn,dotnet/roslyn,tannergooding/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,dotnet/roslyn,AlekseyTs/roslyn,weltkante/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,gafter/roslyn,AlekseyTs/roslyn,dotnet/roslyn,wvdd007/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn | src/Features/Core/Portable/Diagnostics/IDiagnosticService.cs | src/Features/Core/Portable/Diagnostics/IDiagnosticService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Aggregates events from various diagnostic sources.
/// </summary>
internal interface IDiagnosticService
{
/// <summary>
/// Event to get notified as new diagnostics are discovered by IDiagnosticUpdateSource
///
/// Notifications for this event are serialized to preserve order.
/// However, individual event notifications may occur on any thread.
/// </summary>
event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated;
/// <summary>
/// Get current diagnostics stored in IDiagnosticUpdateSource.
/// </summary>
/// <param name="forPullDiagnostics">If the caller of this method will be using the diagnostics for pull or push
/// diagnostic purposes. The <see cref="IDiagnosticService"/> only provides diagnostics for either push or pull
/// purposes (but not both). If the caller's desired purpose doesn't match the service's setting, then this
/// will return nothing, otherwise it will return the requested diagnostics.</param>
ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, bool forPullDiagnostics, CancellationToken cancellationToken);
/// <summary>
/// Get current buckets stored our diagnostics are grouped into. Specific buckets can be retrieved by calling
/// <see cref="IDiagnosticServiceExtensions.GetDiagnostics(IDiagnosticService, DiagnosticBucket, bool, bool, CancellationToken)"/>.
/// </summary>
/// <param name="forPullDiagnostics">If the caller of this method will be using the diagnostics for pull or push
/// diagnostic purposes. The <see cref="IDiagnosticService"/> only provides diagnostics for either push or pull
/// purposes (but not both). If the caller's desired purpose doesn't match the service's setting, then this
/// will return nothing, otherwise it will return the requested buckets.</param>
ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, bool forPullDiagnostics, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Aggregates events from various diagnostic sources.
/// </summary>
internal interface IDiagnosticService
{
/// <summary>
/// Event to get notified as new diagnostics are discovered by IDiagnosticUpdateSource
///
/// Notifications for this event are serialized to preserve order.
/// However, individual event notifications may occur on any thread.
/// </summary>
event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated;
/// <summary>
/// Get current diagnostics stored in IDiagnosticUpdateSource
/// </summary>
ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, bool forPullDiagnostics, CancellationToken cancellationToken);
/// <summary>
/// Get current buckets stored our diagnostics are grouped into. Specific buckets can be retrieved by calling
/// <see cref="IDiagnosticServiceExtensions.GetDiagnostics(IDiagnosticService, DiagnosticBucket, bool, bool, CancellationToken)"/>.
/// </summary>
ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, bool forPullDiagnostics, CancellationToken cancellationToken);
}
}
| mit | C# |
7ea5d9faad7382f7538f7618e51484afc1da091a | Add IRulesContainer | peasy/Peasy.NET,ahanusa/Peasy.NET,ahanusa/facile.net | src/Peasy/Peasy/IRulesContainer.cs | src/Peasy/Peasy/IRulesContainer.cs | using System.Collections.Generic;
namespace Peasy
{
public interface IRulesContainer
{
List<IRule[]> Rules { get; }
}
}
| mit | C# | |
04b7a8b0c19bf1d63ee3bb9ee842f61d0c56c0b5 | Add UT | AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia | tests/Avalonia.Markup.Xaml.UnitTests/SetterTests.cs | tests/Avalonia.Markup.Xaml.UnitTests/SetterTests.cs | using System.Linq;
using Avalonia.Data;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests
{
public class SetterTests : XamlTestBase
{
[Fact]
public void Setter_Should_Work_Outside_Of_Style_With_SetterTargetType_Attribute()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper))
{
var xaml = @"
<Animation xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:SetterTargetType='Avalonia.Controls.Button'>
<KeyFrame>
<Setter Property='Content' Value='{Binding}'/>
</KeyFrame>
</Animation>";
var animation = (Animation.Animation)AvaloniaRuntimeXamlLoader.Load(xaml);
var setter = (Setter)animation.Children[0].Setters[0];
Assert.IsType<Binding>(setter.Value);
}
}
}
}
| mit | C# | |
768fecb4cf6975cc99ba0a23bad0dabf6f3f3383 | Add various System.Drawing.Rectangle extensions | Xeeynamo/KingdomHearts | OpenKh.Common/RectangleExtensions.cs | OpenKh.Common/RectangleExtensions.cs | using System;
using System.Drawing;
namespace OpenKh.Common
{
public static class RectangleExtensions
{
public static Rectangle FlipX(this Rectangle rectangle) =>
Rectangle.FromLTRB(rectangle.Right, rectangle.Top, rectangle.Left, rectangle.Bottom);
public static Rectangle FlipY(this Rectangle rectangle) =>
Rectangle.FromLTRB(rectangle.Left, rectangle.Bottom, rectangle.Right, rectangle.Top);
public static Rectangle GetVisibility(this Rectangle rectangle)
{
if (rectangle.Width == 0 || rectangle.Height == 0)
return Rectangle.Empty;
if (rectangle.Width < 0) rectangle = rectangle.FlipX();
if (rectangle.Height < 0) rectangle = rectangle.FlipY();
return rectangle;
}
public static Rectangle Union(this Rectangle rect, Rectangle rectangle)
{
rect = rect.GetVisibility();
rectangle = rectangle.GetVisibility();
if (rect.IsEmpty) return rectangle;
if (rectangle.IsEmpty) return rect;
return Rectangle.FromLTRB(
Math.Min(rect.Left, rectangle.Left),
Math.Min(rect.Top, rectangle.Top),
Math.Max(rect.Right, rectangle.Right),
Math.Max(rect.Bottom, rectangle.Bottom));
}
public static Rectangle Traslate(this Rectangle rect, int x, int y) =>
new Rectangle(rect.X + x, rect.Y + y, rect.Width, rect.Height);
public static Rectangle Multiply(this Rectangle rect, float x, float y) =>
Rectangle.FromLTRB(
(int)Math.Round(rect.Left * x),
(int)Math.Round(rect.Top * y),
(int)Math.Round(rect.Right * x),
(int)Math.Round(rect.Bottom * y));
public static RectangleF ToRectangleF(this Rectangle rectangle) =>
new RectangleF(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
}
}
| mit | C# | |
834542894d31764ccdfb91253f4dd92856bae130 | Add field id tests. | StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis | service/DotNetApis.Cecil.UnitTests/IdFieldTests.cs | service/DotNetApis.Cecil.UnitTests/IdFieldTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using static Utility;
namespace DotNetApis.Cecil.UnitTests
{
public class IdFieldTests
{
[Fact]
public void Basic_InTopLevelType()
{
var code = @"public class SampleClass { public int SampleField; }";
var assembly = Compile(code).Dll;
var type = assembly.Modules.SelectMany(x => x.Types).Single(x => x.Name == "SampleClass");
var field = type.Fields.Single(x => x.Name == "SampleField");
Assert.Equal("F:SampleClass.SampleField", field.XmldocIdentifier());
Assert.Equal("SampleClass/SampleField", field.DnaId());
field.MemberFriendlyName().AssertEqual("SampleField", "SampleClass.SampleField", "SampleClass.SampleField");
}
[Fact]
public void Basic_InNamespacedType()
{
var code = @"namespace MyNamespace { public class SampleClass { public int SampleField; } }";
var assembly = Compile(code).Dll;
var type = assembly.Modules.SelectMany(x => x.Types).Single(x => x.Name == "SampleClass");
var field = type.Fields.Single(x => x.Name == "SampleField");
Assert.Equal("F:MyNamespace.SampleClass.SampleField", field.XmldocIdentifier());
Assert.Equal("MyNamespace.SampleClass/SampleField", field.DnaId());
field.MemberFriendlyName().AssertEqual("SampleField", "SampleClass.SampleField", "MyNamespace.SampleClass.SampleField");
}
[Fact]
public void Nested()
{
var code = @"public class OuterClass { public class SampleClass { public int SampleField; } }";
var assembly = Compile(code).Dll;
var outer = assembly.Modules.SelectMany(x => x.Types).Single(x => x.Name == "OuterClass");
var type = outer.NestedTypes.Single(x => x.Name == "SampleClass");
var field = type.Fields.Single(x => x.Name == "SampleField");
Assert.Equal("F:OuterClass.SampleClass.SampleField", field.XmldocIdentifier());
Assert.Equal("OuterClass/SampleClass/SampleField", field.DnaId());
field.MemberFriendlyName().AssertEqual("SampleField", "OuterClass.SampleClass.SampleField", "OuterClass.SampleClass.SampleField");
}
[Fact]
public void Nested_InNamespace()
{
var code = @"namespace Ns { public class OuterClass { public class SampleClass { public int SampleField; } } }";
var assembly = Compile(code).Dll;
var outer = assembly.Modules.SelectMany(x => x.Types).Single(x => x.Name == "OuterClass");
var type = outer.NestedTypes.Single(x => x.Name == "SampleClass");
var field = type.Fields.Single(x => x.Name == "SampleField");
Assert.Equal("F:Ns.OuterClass.SampleClass.SampleField", field.XmldocIdentifier());
Assert.Equal("Ns.OuterClass/SampleClass/SampleField", field.DnaId());
field.MemberFriendlyName().AssertEqual("SampleField", "OuterClass.SampleClass.SampleField", "Ns.OuterClass.SampleClass.SampleField");
}
[Fact]
public void Nested_GenericParametersOnDeclaringType()
{
var code = @"public class SampleClass<TFirst> { public int SampleField; }";
var assembly = Compile(code).Dll;
var type = assembly.Modules.SelectMany(x => x.Types).Single(x => x.Name == "SampleClass`1");
var field = type.Fields.Single(x => x.Name == "SampleField");
Assert.Equal("F:SampleClass`1.SampleField", field.XmldocIdentifier());
Assert.Equal("SampleClass'1/SampleField", field.DnaId());
field.MemberFriendlyName().AssertEqual("SampleField", "SampleClass<TFirst>.SampleField", "SampleClass<TFirst>.SampleField");
}
}
}
| mit | C# | |
75293af818c9d1a56c6ee5877839214ea63b5e52 | Mark Program as static as brough to my attention by @zippy1981 | mengruxing/audio-switcher,davkean/audio-switcher,paulcbetts/audio-switcher | src/AudioSwitcher/Program.cs | src/AudioSwitcher/Program.cs | // -----------------------------------------------------------------------
// Copyright (c) David Kean.
// -----------------------------------------------------------------------
using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using AudioSwitcher.ApplicationModel;
namespace AudioSwitcher
{
internal static class Program
{
[STAThread]
public static void Main()
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
using (CompositionContainer container = new CompositionContainer(catalog))
{
IApplication application = container.GetExportedValue<IApplication>();
application.Start();
}
}
}
} | // -----------------------------------------------------------------------
// Copyright (c) David Kean.
// -----------------------------------------------------------------------
using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using AudioSwitcher.ApplicationModel;
namespace AudioSwitcher
{
internal class Program
{
[STAThread]
public static void Main()
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
using (CompositionContainer container = new CompositionContainer(catalog))
{
IApplication application = container.GetExportedValue<IApplication>();
application.Start();
}
}
}
} | mit | C# |
c3b11da2a6ac9f9851a96cfd2da4eb817f7a6412 | Add big-endian converter | mstrother/BmpListener | src/BmpListener/BigEndian.cs | src/BmpListener/BigEndian.cs | using System;
namespace BmpListener
{
public static class BigEndian
{
public static short ToInt16(ArraySegment<byte> data, int offset)
{
offset += data.Offset;
return (short)((data.Array[offset++] << 8) | (data.Array[offset++]));
}
public static ushort ToUInt16(ArraySegment<byte> data, int offset)
{
offset += data.Offset;
return (ushort)((data.Array[offset++] << 8) | data.Array[offset++]);
}
public static int ToInt32(ArraySegment<byte> data, int offset)
{
offset += data.Offset;
return (data.Array[offset++] << 24) | (data.Array[offset++] << 16)
| (data.Array[offset++] << 8) | data.Array[offset++];
}
public static uint ToUInt32(ArraySegment<byte> data, int offset)
{
offset += data.Offset;
return (uint)((data.Array[offset++] << 24) | (data.Array[offset++] << 16)
| (data.Array[offset++] << 8) | data.Array[offset++]);
}
public static long ToInt64(ArraySegment<byte> data, int offset)
{
offset += data.Offset;
return (data.Array[offset++] << 56) | (data.Array[offset++] << 48)
| (data.Array[offset++] << 40) | (data.Array[offset++] << 32)
| (data.Array[offset++] << 24) | (data.Array[offset++] << 16)
| (data.Array[offset++] << 8) | data.Array[offset++];
}
public static ulong ToUInt64(ArraySegment<byte> data, int offset)
{
offset += data.Offset;
return (ulong)((data.Array[offset++] << 56) | (data.Array[offset++] << 48)
| (data.Array[offset++] << 40) | (data.Array[offset++] << 32)
| (data.Array[offset++] << 24) | (data.Array[offset++] << 16)
| (data.Array[offset++] << 8) | data.Array[offset++]);
}
}
}
| mit | C# | |
692187e0cbb463c49fb975f087a7ad85b60a954b | Add Color | praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui | Ooui/Color.cs | Ooui/Color.cs | using System;
namespace Ooui
{
public struct Color
{
public byte R, G, B, A;
public double Red {
get => R / 255.0;
set => R = value >= 1.0 ? (byte)255 : ((value <= 0.0) ? (byte)0 : (byte)(value * 255.0 + 0.5));
}
public double Green {
get => G / 255.0;
set => G = value >= 1.0 ? (byte)255 : ((value <= 0.0) ? (byte)0 : (byte)(value * 255.0 + 0.5));
}
public double Blue {
get => B / 255.0;
set => B = value >= 1.0 ? (byte)255 : ((value <= 0.0) ? (byte)0 : (byte)(value * 255.0 + 0.5));
}
public double Alpha {
get => A / 255.0;
set => A = value >= 1.0 ? (byte)255 : ((value <= 0.0) ? (byte)0 : (byte)(value * 255.0 + 0.5));
}
}
}
| mit | C# | |
1a053480f7b03dc75e42a8547aa322b990685e01 | Add Upsert | rapidcore/rapidcore,rapidcore/rapidcore | src/google-cloud/test-functional/Datastore/DatastoreConnection/UpsertTests.cs | src/google-cloud/test-functional/Datastore/DatastoreConnection/UpsertTests.cs | using Xunit;
namespace functionaltests.Datastore.DatastoreConnection
{
public class UpsertTests : DatastoreConnectionTestBase
{
[Fact]
public async void Upsert_without_kind()
{
EnsureEmptyKind("TheUpserter");
var poco = new TheUpserter
{
Id = 666,
String = "Miav",
X = 333
};
await connection.UpsertAsync(poco);
var firstAll = GetAll("TheUpserter");
Assert.Equal(1, firstAll.Count);
Assert.Equal(666, firstAll[0].Key.Path[0].Id);
Assert.Equal("Miav", firstAll[0]["String"].StringValue);
Assert.Equal(333, firstAll[0]["X"].IntegerValue);
poco.X = 999;
await connection.UpsertAsync(poco);
var secondAll = GetAll("TheUpserter");
Assert.Equal(1, secondAll.Count);
Assert.Equal(666, secondAll[0].Key.Path[0].Id);
Assert.Equal("Miav", secondAll[0]["String"].StringValue);
Assert.Equal(999, secondAll[0]["X"].IntegerValue);
}
[Fact]
public async void Upsert_with_kind()
{
EnsureEmptyKind("KittensAreEvil");
var poco = new TheUpserter
{
Id = 666,
String = "Miav",
X = 333
};
await connection.UpsertAsync(poco, "KittensAreEvil");
var firstAll = GetAll("KittensAreEvil");
Assert.Equal(1, firstAll.Count);
Assert.Equal(666, firstAll[0].Key.Path[0].Id);
Assert.Equal("Miav", firstAll[0]["String"].StringValue);
Assert.Equal(333, firstAll[0]["X"].IntegerValue);
poco.X = 999;
await connection.UpsertAsync(poco, "KittensAreEvil");
var secondAll = GetAll("KittensAreEvil");
Assert.Equal(1, secondAll.Count);
Assert.Equal(666, secondAll[0].Key.Path[0].Id);
Assert.Equal("Miav", secondAll[0]["String"].StringValue);
Assert.Equal(999, secondAll[0]["X"].IntegerValue);
}
#region POCOs
public class TheUpserter
{
public int Id { get; set; }
public string String { get; set; }
public int X { get; set; }
}
#endregion
}
} | mit | C# | |
e46ad49a2a00b82d0bf37f21cd62aac709d8b15d | Add DiplomContextExtensions to Seed data | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.DataLayer/DiplomContextExtensions.cs | src/Diploms.DataLayer/DiplomContextExtensions.cs | using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Diploms.Core;
namespace Diploms.DataLayer
{
public static class DiplomContentSystemExtensions
{
public static void EnsureSeedData(this DiplomContext context)
{
if (context.AllMigrationsApplied())
{
if (!context.Roles.Any())
{
context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher);
context.SaveChanges();
}
}
}
private static bool AllMigrationsApplied(this DiplomContext context)
{
var applied = context.GetService<IHistoryRepository>()
.GetAppliedMigrations()
.Select(m => m.MigrationId);
var total = context.GetService<IMigrationsAssembly>()
.Migrations
.Select(m => m.Key);
return !total.Except(applied).Any();
}
}
} | mit | C# | |
954b76415dd9c061defd72500e5615fea3636fef | Add a simple debug query | RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake | src/Snowflake.Support.GraphQLFrameworkQueries/Queries/Debug/EchoQueries.cs | src/Snowflake.Support.GraphQLFrameworkQueries/Queries/Debug/EchoQueries.cs | using HotChocolate.Types;
using System;
using System.Collections.Generic;
using System.Text;
namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Debug
{
public class EchoQueries
: ObjectTypeExtension
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor
.Name("Query");
descriptor.Field("DEBUG__HelloWorld")
.Resolver("Hello World");
}
}
}
| mpl-2.0 | C# | |
96db24f548d5c2da73ab733f79035a9c2a7b33c3 | add framework characterization tests | maxhauser/semver | Semver.Test/FrameworkCharacterizationTests.cs | Semver.Test/FrameworkCharacterizationTests.cs | using System;
using System.Globalization;
using Xunit;
namespace Semver.Test
{
/// <summary>
/// These tests serve to verify or clarify the behavior of standard .NET framework
/// types which <see cref="SemVersion"/> is modeled on. This helps to ensure the
/// behavior is consistent with that of the .NET framework types.
/// </summary>
public class FrameworkCharacterizationTests
{
[Fact]
public void IntTryParseOfNullReturnsFalse()
{
Assert.False(int.TryParse(null, out _));
}
[Fact]
public void IntTryParseOfInvalidNumberStyleThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(
() => int.TryParse("45", InvalidNumberStyle, CultureInfo.InvariantCulture, out _));
Assert.Equal(InvalidNumberStyleMessage, ex.Message);
}
[Fact]
public void IntParseOfNullAndInvalidNumberStyleThrowsInvalidNumberStyleArgumentException()
{
var ex = Assert.Throws<ArgumentException>(
() => int.Parse(null, InvalidNumberStyle, CultureInfo.InvariantCulture));
Assert.Equal(InvalidNumberStyleMessage, ex.Message);
}
private const string InvalidNumberStyleMessage = "An undefined NumberStyles value is being used.\r\nParameter name: style";
private const NumberStyles InvalidNumberStyle = (NumberStyles)int.MaxValue;
}
}
| mit | C# | |
715bd29aff07f36c19d72a6c79b9d7eb4879af18 | Add support Patch for collections. #2 | Marusyk/Simple.HttpPatch,Marusyk/Simple.HttpPatch | src/Simple.HttpPatch/PatchCollection.cs | src/Simple.HttpPatch/PatchCollection.cs | using System;
using System.Collections.Generic;
namespace Simple.HttpPatch
{
public class PatchCollection<TModel> : List<Patch<TModel>> where TModel : class, new()
{
public void Apply(IList<TModel> deltas)
{
if (deltas == null)
{
throw new ArgumentNullException(nameof(deltas));
}
for (int i = 0; i < deltas.Count; i++)
{
this[i].Apply(deltas[i]);
}
}
}
}
| mit | C# | |
50173754c5de997e3a71cdec268faccebe9df89a | Add keywords of the Print Schema Keywords v1.1 | kei10in/KipSharp | Kip/PrintSchemaKeywordsV11.cs | Kip/PrintSchemaKeywordsV11.cs | using System.Xml.Linq;
namespace Kip
{
public static class Pskv11
{
public static readonly XNamespace Namespace = "http://schemas.microsoft.com/windows/2013/05/printing/printschemakeywordsv11";
public static readonly XName JobPasscode = Namespace + "JobPasscode";
public static readonly XName JobPasscodeString = Namespace + "JobPasscodeString";
public static readonly XName JobImageFormat = Namespace + "JobImageFormat";
public static readonly XName Jpeg = Namespace + "Jpeg";
public static readonly XName PNG = Namespace + "PNG";
}
}
| mit | C# | |
1a21857176d59bb2f8ddf13b329ff8c0a56c7f5c | Add EmptyArray | AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/Abstractions | src/AspectCore.Lite.Abstractions/Common/EmptyArray.cs | src/AspectCore.Lite.Abstractions/Common/EmptyArray.cs | namespace AspectCore.Lite.Abstractions.Common
{
public static class EmptyArray<T>
{
public static readonly T[] Vaule = new T[0];
}
}
| mit | C# | |
8a42830bfc73f703d6c79d153a47ea11e9cbed0e | Add class to avoid byte[] creation | diadoc/diadocsdk-csharp,halex2005/diadocsdk-csharp,halex2005/diadocsdk-csharp,diadoc/diadocsdk-csharp | src/Com/ComBytes.cs | src/Com/ComBytes.cs | using System.IO;
using System.Runtime.InteropServices;
namespace Diadoc.Api.Com
{
[ComVisible(true)]
[Guid("AC96A3DD-E099-44CC-ABD5-11C303307159")]
public interface IComBytes
{
byte[] Bytes { get; set; }
void ReadFromFile(string path);
void SaveToFile(string path);
}
[ComVisible(true)]
[ProgId("Diadoc.Api.ComBytes")]
[Guid("97D998E3-E603-4450-A027-EA774091BE72")]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IComBytes))]
public class ComBytes : SafeComObject, IComBytes
{
public byte[] Bytes { get; set; }
public void ReadFromFile(string path)
{
Bytes = File.ReadAllBytes(path);
}
public void SaveToFile(string path)
{
if (Bytes != null)
{
File.WriteAllBytes(path, Bytes);
}
}
}
} | mit | C# | |
3de477457e247c37267ba9f871ea67fd7833cdb6 | Add MapReduceJob | tristanles/mapreduce-dojo-csharp | MapReduceDojo/MapReduceJob.cs | MapReduceDojo/MapReduceJob.cs | using System;
using System.Collections.Generic;
namespace MapReduceDojo
{
public class MapReduceJob<T> : IEmitter<T> {
private enum Phase {Map, Reduce}
private Phase _phase;
private readonly IMapperReducer<T> _mapperReducer;
private readonly IDictionary<String, T> _finalResults = new Dictionary<String, T>();
private readonly IDictionary<String, List<T>> _results = new Dictionary<String, List<T>>();
public MapReduceJob(IMapperReducer<T> mapperReducer, IDataSource dataSource)
{
_mapperReducer = mapperReducer;
Map(dataSource);
Reduce();
Print();
}
private void Map(IDataSource dataSource)
{
_phase = Phase.Map;
IEnumerator<String> enumerator = dataSource.GetIterator();
while(enumerator.MoveNext())
{
_mapperReducer.Map(this, enumerator.Current);
}
}
private void Reduce()
{
_phase = Phase.Reduce;
foreach (KeyValuePair<String, List<T>> mapResult in _results)
{
_mapperReducer.Reduce(this, mapResult.Key, mapResult.Value);
}
}
public void Emit(String key, T value)
{
switch (_phase)
{
case Phase.Map : AddResult(key, value); return;
case Phase.Reduce: _finalResults.Add(key, value); break;
}
}
public IDictionary<String, T> GetResults()
{
return _finalResults;
}
private void AddResult(String key, T value)
{
List<T> values = _results[key] ?? new List<T>();
values.Add(value);
_results.Add(key, values);
}
private void Print()
{
Console.WriteLine(_finalResults);
}
}
}
| mit | C# | |
a33c1096a79e6787c68e0bde67393f93cc68acd5 | Add generation of KML file to maps menu | ShammyLevva/FTAnalyzer,ShammyLevva/FTAnalyzer,ShammyLevva/FTAnalyzer | FTAnalyser/Mapping/GoogleAPIKey.cs | FTAnalyser/Mapping/GoogleAPIKey.cs | using FTAnalyzer.Utilities;
using System;
namespace FTAnalyzer.Mapping
{
static class GoogleAPIKey
{
static string APIkeyValue = string.Empty;
public static string KeyValue
{
get
{
if (string.IsNullOrEmpty(APIkeyValue))
{
try
{
if (string.IsNullOrEmpty(Properties.MappingSettings.Default.GoogleAPI))
APIkeyValue = "AIzaSyDJCForfeivoVF03Sr04rN9MMulO6KwA_M";
else
{
APIkeyValue = Properties.MappingSettings.Default.GoogleAPI;
UIHelpers.ShowMessage("Using your private Google API Key.\nPlease observe monthly usage limits to avoid a large bill from Google.");
}
}
catch (Exception)
{
APIkeyValue = "AIzaSyDJCForfeivoVF03Sr04rN9MMulO6KwA_M";
}
}
return APIkeyValue;
}
}
}
} | apache-2.0 | C# | |
7debe85437a264bc86f99048d173c95c3d2d2a41 | add type helper (in preperation for linq provider) | YoloDev/elephanet,YoloDev/elephanet,jmkelly/elephanet,jmkelly/elephanet | Elephanet/TypeHelper.cs | Elephanet/TypeHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Elephanet
{
internal static class TypeSystem
{
internal static Type GetElementType(Type seqType)
{
Type ienum = FindIEnumerable(seqType);
if (ienum == null) return seqType;
return ienum.GetGenericArguments()[0];
}
private static Type FindIEnumerable(Type seqType)
{
if (seqType == null || seqType == typeof(string))
return null;
if (seqType.IsArray)
return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
if (seqType.IsGenericType)
{
foreach (Type arg in seqType.GetGenericArguments())
{
Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
if (ienum.IsAssignableFrom(seqType))
{
return ienum;
}
}
}
Type[] ifaces = seqType.GetInterfaces();
if (ifaces != null && ifaces.Length > 0)
{
foreach (Type iface in ifaces)
{
Type ienum = FindIEnumerable(iface);
if (ienum != null) return ienum;
}
}
if (seqType.BaseType != null && seqType.BaseType != typeof(object))
{
return FindIEnumerable(seqType.BaseType);
}
return null;
}
}
}
| mit | C# | |
3346fcb5b6cf015f49cdadab18ce666b52a59e4f | Add PredicateBuilder | YeastFx/Yeast | src/Yeast.Data/PredicateBuilder.cs | src/Yeast.Data/PredicateBuilder.cs | using System;
using System.Linq;
using System.Linq.Expressions;
namespace Yeast.Data
{
/// <summary>
/// Helper class to combine predicates
/// </summary>
public static class PredicateBuilder
{
/// <summary>
/// True predicate
/// </summary>
/// <typeparam name="T">Predicate's target type</typeparam>
/// <returns>Always true predicate</returns>
public static Expression<Func<T, bool>> True<T>() { return f => true; }
/// <summary>
/// False predicate
/// </summary>
/// <typeparam name="T">Predicate's target type</typeparam>
/// <returns>Always false predicate</returns>
public static Expression<Func<T, bool>> False<T>() { return f => false; }
/// <summary>
/// Combines two predicates with a logical OR operator
/// </summary>
/// <typeparam name="T">Predicate's target type</typeparam>
/// <param name="expr1">First predicate</param>
/// <param name="expr2">Second predicate</param>
/// <returns>Combined predicate</returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
/// <summary>
/// Combines two predicates with a logical AND operator
/// </summary>
/// <typeparam name="T">Predicate's target type</typeparam>
/// <param name="expr1">First predicate</param>
/// <param name="expr2">Second predicate</param>
/// <returns>Combined predicate</returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}
| mit | C# | |
ad22c1194dd30c7adff2ddb97c1df339d86e1f81 | Create singleton | tenevdev/design-patterns | SingletonPattern/ChocolateFactory/ChocolateBoiler.cs | SingletonPattern/ChocolateFactory/ChocolateBoiler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonPattern.ChocolateFactory
{
public sealed class ChocolateBoiler
{
private static readonly ChocolateBoiler _instance = new ChocolateBoiler();
public static ChocolateBoiler Instance
{
get
{
return ChocolateBoiler._instance;
}
}
private ChocolateBoiler()
{
}
}
}
| mit | C# | |
6075910c6988380b0e2f2c9d1efd56bece04cb9b | Create scanner.cs | EverGen1/Ever,EverGen1/Ever,EverGen1/Ever | scanner.cs | scanner.cs | using Collections = http://
| mit | C# | |
b98d5ee5c0ad97b0c0eb4aae0f650cc7bc9c8264 | Make SerializationType internal | ilkerhalil/dnlib,Arthur2e5/dnlib,ZixiangBoy/dnlib,0xd4d/dnlib,yck1509/dnlib,jorik041/dnlib,kiootic/dnlib,modulexcite/dnlib,picrap/dnlib | src/DotNet/SerializationType.cs | src/DotNet/SerializationType.cs | namespace dot10.DotNet {
/// <summary>
/// See CorSerializationType/CorHdr.h
/// </summary>
enum SerializationType : byte {
/// <summary></summary>
Undefined = 0,
/// <summary>System.Boolean</summary>
Boolean = ElementType.Boolean,
/// <summary>System.Char</summary>
Char = ElementType.Char,
/// <summary>System.SByte</summary>
I1 = ElementType.I1,
/// <summary>System.Byte</summary>
U1 = ElementType.U1,
/// <summary>System.Int16</summary>
I2 = ElementType.I2,
/// <summary>System.UInt16</summary>
U2 = ElementType.U2,
/// <summary>System.Int32</summary>
I4 = ElementType.I4,
/// <summary>System.UInt32</summary>
U4 = ElementType.U4,
/// <summary>System.Int64</summary>
I8 = ElementType.I8,
/// <summary>System.UInt64</summary>
U8 = ElementType.U8,
/// <summary>System.Single</summary>
R4 = ElementType.R4,
/// <summary>System.Double</summary>
R8 = ElementType.R8,
/// <summary>System.String</summary>
String = ElementType.String,
/// <summary>Single-dimension, zero lower bound array ([])</summary>
SZArray = ElementType.SZArray,
/// <summary>System.Type</summary>
Type = 0x50,
/// <summary>Boxed value type</summary>
TaggedObject= 0x51,
/// <summary>A field</summary>
Field = 0x53,
/// <summary>A property</summary>
Property = 0x54,
/// <summary>An enum</summary>
Enum = 0x55,
}
}
| namespace dot10.DotNet {
/// <summary>
/// See CorSerializationType/CorHdr.h
/// </summary>
public enum SerializationType : byte {
/// <summary></summary>
Undefined = 0,
/// <summary>System.Boolean</summary>
Boolean = ElementType.Boolean,
/// <summary>System.Char</summary>
Char = ElementType.Char,
/// <summary>System.SByte</summary>
I1 = ElementType.I1,
/// <summary>System.Byte</summary>
U1 = ElementType.U1,
/// <summary>System.Int16</summary>
I2 = ElementType.I2,
/// <summary>System.UInt16</summary>
U2 = ElementType.U2,
/// <summary>System.Int32</summary>
I4 = ElementType.I4,
/// <summary>System.UInt32</summary>
U4 = ElementType.U4,
/// <summary>System.Int64</summary>
I8 = ElementType.I8,
/// <summary>System.UInt64</summary>
U8 = ElementType.U8,
/// <summary>System.Single</summary>
R4 = ElementType.R4,
/// <summary>System.Double</summary>
R8 = ElementType.R8,
/// <summary>System.String</summary>
String = ElementType.String,
/// <summary>Single-dimension, zero lower bound array ([])</summary>
SZArray = ElementType.SZArray,
/// <summary>System.Type</summary>
Type = 0x50,
/// <summary>Boxed value type</summary>
TaggedObject= 0x51,
/// <summary>A field</summary>
Field = 0x53,
/// <summary>A property</summary>
Property = 0x54,
/// <summary>An enum</summary>
Enum = 0x55,
}
}
| mit | C# |
2d2714d8e8bb11671caf5220e11220101a2db634 | Create ComObjectModel.cs | Excel-DNA/Samples | Misc/ComObjectModel.cs | Misc/ComObjectModel.cs | // Shows how to get hold of the Excel COM Application object
// Install the 'ExcelDna.Interop' package from NuGet, or reference the two assemblies:
// * Microsoft.Office.Interop.Excel.dll
// * Office.dll
using ExcelDna.Integration;
using Microsoft.Office.Interop.Excel;
public class TestCommands
{
// Defines a macro that uses the COM object model to add a diamond shape to the active sheet.
[ExcelCommand(ShortCut = "^D")] // Ctrl+Shift+D
public static void AddDiamond()
{
Application xlApp = (Application)ExcelDnaUtil.Application;
string version = xlApp.Version;
Worksheet ws = xlApp.ActiveSheet as Worksheet; // Need to change type - it might be a Chart, then ws would be null
Shape diamond = ws.Shapes.AddShape(Microsoft.Office.Core.MsoAutoShapeType.msoShapeDiamond, 10, 10, 100, 100);
diamond.Fill.BackColor.RGB = (int)XlRgbColor.rgbSlateBlue;
}
}
| mit | C# | |
b8699d8a6a6592ea7e047c5b9d2dd6c1f38358f4 | Create ColorHelper.cs | drawcode/labs-unity | utility/ColorHelper.cs | utility/ColorHelper.cs | using System;
using System.Collections;
using System.Collections.Generic;
using Engine.Utility;
using UnityEngine;
public class ColorItem {
public float r = 0f;
public float g = 0f;
public float b = 0f;
public float a = 0f;
public ColorItem() {
}
public ColorItem(float r, float g, float b) {
Set(r, g, b, 255);
}
public ColorItem(float r, float g, float b, float a) {
Set(r, g, b, a);
}
public void Set(float rTo, float gTo, float bTo, float aTo) {
r = rTo;
g = gTo;
b = bTo;
a = aTo;
}
public void Set(List<double> color) {
if(color == null) {
return;
}
if(color.Count > 0)
r = (float)color[0];
if(color.Count > 1)
g = (float)color[1];
if(color.Count > 2)
b = (float)color[2];
if(color.Count > 3)
a = (float)color[3];
}
public Color GetColor(List<double> color) {
if(color == null) {
return Color.white;
}
Set(color);
return GetColor();
}
public Color GetColor() {
return new Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}
}
public static class ColorHelper {
public static Color FromRGB(List<double> color) {
return new ColorItem().GetColor(color);
}
public static Color FromRGB(float r, float g, float b) {
return new Color(r / 255.0f, g / 255.0f, b / 255.0f);
}
public static Color FromRGB(float r, float g, float b, float a) {
return new Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 1.0f);
}
// Note that Color32 and Color implictly convert to each other. You may pass a Color object to this method without first casting it.
public static string ToHex(Color32 color) {
string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2");
return hex;
}
public static Color FromHex(string hex) {
byte r = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
byte g = byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
byte b = byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
return new Color32(r, g, b, 255);
}
}
| mit | C# | |
dd2cd17bf8e588f75b28908dab2b8d67db3772e0 | Create index.cshtml | KovalNikita/apmathcloud | SITE/index.cshtml | SITE/index.cshtml | @{
var totalMessage = "";
if(IsPost)
{
var num1 = Request["text1"];
var num2 = Request["text2"];
var total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
<html>
<body style="background-color: beige; font-family: Verdana, Arial;">
<form action="" method="post">
<p><label for="text1">First Number:</label><br>
<input type="text" name="text1" /></p>
<p><label for="text2">Second Number:</label><br>
<input type="text" name="text2" /></p>
<p><input type="submit" value=" Add " /></p>
</form>
<p>@totalMessage</p>
</body>
</html>
| mit | C# | |
e346098b4aa63527e72ab9af325b307e09ca5331 | Create SafeCrakingAIO.cs | Zephyr-Koo/sololearn-challenge | SafeCrakingAIO.cs | SafeCrakingAIO.cs | using System;
using System.Collections.Generic;
using System.Linq;
// https://www.sololearn.com/Discuss/687526/?ref=app
namespace SoloLearn
{
class Program
{
static readonly int[] CODE_SHEET = new int[] { 11, 13, 8, 10, 12, 16 };
static readonly int[] KNOWN_SAFE_PASS = new int[] { 4, 6, 8 };
static void Main(string[] zephyr_koo)
{
int csCursor = 0;
int ksCursor = 0;
int matchCount = 1;
int commonDifference = CODE_SHEET[csCursor++] - KNOWN_SAFE_PASS[ksCursor++];
do
{
int currentDifference = CODE_SHEET[csCursor] - KNOWN_SAFE_PASS[ksCursor];
if (currentDifference == commonDifference)
{
ksCursor++;
matchCount++;
}
else
{
matchCount = 1;
csCursor -= ksCursor - 1;
ksCursor = 0;
commonDifference = CODE_SHEET[csCursor] - KNOWN_SAFE_PASS[ksCursor++];
}
if (matchCount == KNOWN_SAFE_PASS.Length) break;
csCursor++;
} while (csCursor < CODE_SHEET.Length);
Console.WriteLine($"Yay! The safe pass is { string.Join(" ", CODE_SHEET.Select(p => p - commonDifference)) } with offset { commonDifference }.");
}
}
}
| apache-2.0 | C# | |
8f4d4cb23f76e717c6356823c7ac58631f2be3d7 | Move a small part of current | arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS | src/Umbraco.Abstractions/Composing/Current.cs | src/Umbraco.Abstractions/Composing/Current.cs | using System;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Composing
{
/// <summary>
/// Provides a static service locator for most singletons.
/// </summary>
/// <remarks>
/// <para>This class is initialized with the container in UmbracoApplicationBase,
/// right after the container is created in UmbracoApplicationBase.HandleApplicationStart.</para>
/// <para>Obviously, this is a service locator, which some may consider an anti-pattern. And yet,
/// practically, it works.</para>
/// </remarks>
public static class CurrentCore
{
private static IFactory _factory;
private static ILogger _logger;
private static IProfiler _profiler;
private static IProfilingLogger _profilingLogger;
/// <summary>
/// Gets or sets the factory.
/// </summary>
public static IFactory Factory
{
get
{
if (_factory == null) throw new InvalidOperationException("No factory has been set.");
return _factory;
}
set
{
if (_factory != null) throw new InvalidOperationException("A factory has already been set.");
// if (_configs != null) throw new InvalidOperationException("Configs are unlocked.");
_factory = value;
}
}
internal static bool HasFactory => _factory != null;
#region Getters
public static ILogger Logger
=> _logger ?? (_logger = _factory?.TryGetInstance<ILogger>() ?? throw new Exception("TODO Fix")); //?? new DebugDiagnosticsLogger(new MessageTemplates()));
public static IProfiler Profiler
=> _profiler ?? (_profiler = _factory?.TryGetInstance<IProfiler>()
?? new LogProfiler(Logger));
public static IProfilingLogger ProfilingLogger
=> _profilingLogger ?? (_profilingLogger = _factory?.TryGetInstance<IProfilingLogger>())
?? new ProfilingLogger(Logger, Profiler);
#endregion
}
}
| mit | C# | |
ea8210aa6dbc9689104b3a8ca3706f2240fe6c70 | Create PulsarTopic for consistency working with Pulsar topics | JasperFx/jasper,JasperFx/jasper,JasperFx/jasper | src/Jasper.Pulsar/PulsarTopic.cs | src/Jasper.Pulsar/PulsarTopic.cs | using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace Jasper.Pulsar
{
public struct PulsarTopic
{
public string Persistence { get; }
public string Tenant { get; }
public string Namespace { get; }
public string TopicName { get; }
public bool IsForReply { get; }
private const string PulsarTopicRegex = @"(non-persistent|persistent)://([-A-Za-z0-9]*)/([-A-Za-z0-9]*)/([-A-Za-z0-9]*)(/for-reply)?";
private const string InvalidTopicFormatMessage =
"Invalid Pulsar topic. Expecting format of \"{persistent|non-persistent}://tenant/namespace/topic\" (can append \"/for-reply\" for Jasper functionality. It will not be included in communication w/ Pulsar)";
public PulsarTopic(Uri topic) : this(topic?.ToString())
{
}
public PulsarTopic(string topic)
{
MatchCollection match = Regex.Matches(topic, PulsarTopicRegex, RegexOptions.Compiled);
if (!match.Any())
throw new ArgumentException(InvalidTopicFormatMessage, nameof(topic));
Persistence = match[0].Groups[1].Captures[0].Value;
Tenant = match[0].Groups[2].Captures[0].Value;
Namespace = match[0].Groups[3].Captures[0].Value;
TopicName = match[0].Groups[4].Captures[0].Value;
IsForReply = match[0].Groups.Count == 6;
}
public static implicit operator string(PulsarTopic topic) => topic.ToString();
public static implicit operator PulsarTopic(string topic) => new PulsarTopic(topic);
public static implicit operator PulsarTopic(Uri topic) => new PulsarTopic(topic);
public override string ToString() => $"{Persistence}://{Tenant}/{Namespace}/{TopicName}";
public Uri ToJasperUri(bool forReply) => new Uri($"{this}{(forReply ? "/for-reply" : string.Empty)}");
}
}
| mit | C# | |
c46dc2b3b75b4bee65ef919fcb335f8ddf3820d4 | add missing page model | myty/muse,myty/muse,myty/muse | src/MyTy.Blog.Web/Models/Page.cs | src/MyTy.Blog.Web/Models/Page.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyTy.Blog.Web.Models
{
public class Page
{
public string FileLocation { get; set; }
public string Href { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
public string HeaderBackgroundImage { get; set; }
public DateTime Date { get; set; }
public string Content { get; set; }
public string Layout { get; set; }
}
} | mit | C# | |
5376ef4ac7fdba1af55ad4f99adc6dfa23fbb456 | Create Index.cshtml | CarmelSchvartzman/MVC_WebGrid_Admin,CarmelSoftware/MVC_WebGrid_Admin | Index.cshtml | Index.cshtml | @model IEnumerable<ERASE_BL.Blog>
@{
ViewBag.Title = "Index";
WebGrid grid = new WebGrid(Model, new[] { "Title", "Text", "DatePosted", "MainPicture", "Blogger" },
rowsPerPage:2,ajaxUpdateContainerId:"GridDiv");
IEnumerable<WebGridColumn> oColumns = new[] {
grid.Column("ID",format:(item) => item.GetSelectLink(item.BlogID.ToString()) ) ,
grid.Column("Title",format:@<a href='/Blog/Details/@item.BlogID'><b>@item.Title</b></a>),
grid.Column("DatePosted","DatePosted", (item) => String.Format("{0:dd/MM/yyyy}", item.DatePosted != null ? item.DatePosted : DateTime.Now )),
grid.Column("Picture",format:(item) =>
{ return new MvcHtmlString("<a href='/Blog/Details/" + item.BlogID +
"'><img src='/Images/"+item.MainPicture+"' style='width:100px;height:100px;'></img></a>");
})
};
if (User.IsInRole("Admin"))
{
oColumns = oColumns.Concat(new[] {grid.Column(
format:@<div class="ActionsTH">
@Html.ActionLink("Edit", "Edit", new { id=item.BlogID })
@Html.ActionLink("Details", "Details", new { id=item.BlogID })
@Html.ActionLink("Delete", "Delete", new { id=item.BlogID })
</div>) });
}
}
<h2>Index</h2>
<div id="GridDiv">
@grid.GetHtml(tableStyle:"webgrid-tableStyle",headerStyle:"webgrid-headerStyle",footerStyle:"webgrid-footerStyle",alternatingRowStyle:"webgrid-alternatingRowStyle",columns: oColumns) </div>
<p>
<input type="button" value="Create New" onclick="javascript:location='/Blog/Create'" class="btn btn-default"/>
</p>
| mit | C# | |
d43a1d4a68b4b9f642f331f38415c50b8a49134a | Create StackCall.cs | secabstraction/PowerWalker | StackCall.cs | StackCall.cs | using System;
using PowerWalker.Natives;
using System.Collections.Generic;
namespace PowerWalker
{
public class StackCall
{
public ulong Offset { get; private set; }
public ulong ReturnAddress { get; private set; }
public string Symbol { get; private set; }
public string SymbolFile { get; private set; }
public StackCall(IntPtr hProcess, ulong AddrPC, ulong AddrReturn)
{
System.Text.StringBuilder ReturnedString = new System.Text.StringBuilder(256);
IntPtr PcOffset = (IntPtr)Functions.UlongToLong(AddrPC);
Psapi.GetMappedFileNameW(hProcess, PcOffset, ReturnedString, (uint)ReturnedString.Capacity);
SymbolFile = ReturnedString.ToString();
IMAGEHLP_SYMBOL64 PcSymbol = Functions.GetSymbolFromAddress(hProcess, AddrPC);
Symbol = new string(PcSymbol.Name);
Offset = AddrPC;
ReturnAddress = AddrReturn;
}
}
}
| bsd-3-clause | C# | |
3a492142b0b740ca7bf48c487803720959f806ec | Create Diag.cs | Xeeynamo/KingdomHearts | OpenKh.Kh2/Jiminy/Diag.cs | OpenKh.Kh2/Jiminy/Diag.cs | using System;
using System.Collections.Generic;
using System.Text;
using Xe.BinaryMapper;
namespace OpenKh.Kh2.Jiminy
{
public class Diag
{
public const int MagicCode = 0x49444D4A;
public class Flag
{
[Data] public ushort Id { get; set; }
[Data] public ushort Unk02 { get; set; }
[Data] public byte World { get; set; }
[Data] public byte Room { get; set; }
[Data] public byte Unk06 { get; set; }
[Data] public byte Padding { get; set; }
[Data] public int Unk08 { get; set; }
}
//z_un_002a18d0
}
}
| mit | C# | |
de0a076eb6ce9835810a13977319413c4e41ac1f | Add model class for mod presets | peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu | osu.Game/Rulesets/Mods/ModPreset.cs | osu.Game/Rulesets/Mods/ModPreset.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
namespace osu.Game.Rulesets.Mods
{
/// <summary>
/// A mod preset is a named collection of configured mods.
/// Presets are presented to the user in the mod select overlay for convenience.
/// </summary>
public class ModPreset
{
/// <summary>
/// The ruleset that the preset is valid for.
/// </summary>
public RulesetInfo RulesetInfo { get; set; } = null!;
/// <summary>
/// The name of the mod preset.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// The description of the mod preset.
/// </summary>
public string Description { get; set; } = string.Empty;
/// <summary>
/// The set of configured mods that are part of the preset.
/// </summary>
public ICollection<Mod> Mods { get; set; } = Array.Empty<Mod>();
}
}
| mit | C# | |
8dfa193e5eae915a6eb5f0ef5750d921cc367dad | Add a Panel class, to make drawing rectangles easy. | dneelyep/MonoGameUtils | MonoGameUtils/GameComponents/Panel.cs | MonoGameUtils/GameComponents/Panel.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.GameComponents
{
/// <summary>
/// A solid-color rectangle that can be drawn on-screen.
/// </summary>
internal class Panel : DrawableGameComponent
{
#region "Properties"
public Rectangle Bounds { get; set; }
#endregion
private readonly Color BACKGROUND_COLOR;
private Texture2D Texture { get; set; }
private SpriteBatch mSpriteBatch;
public Panel(Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch, Game game) : base(game)
{
Bounds = bounds;
BACKGROUND_COLOR = backgroundColor;
mSpriteBatch = spriteBatch;
}
public override void Initialize()
{
Texture = new Texture2D(Game.GraphicsDevice, 1, 1);
Texture.SetData<Color>(new Color[] { BACKGROUND_COLOR } );
base.Initialize();
}
public override void Draw(GameTime gameTime)
{
mSpriteBatch.Draw(Texture, Bounds, BACKGROUND_COLOR);
base.Draw(gameTime);
}
}
}
| mit | C# | |
2f7b51978f174236bc61ec09b2cac94dbada9820 | Add exception type for native call failures. | CoraleStudios/Colore,danpierce1/Colore,Sharparam/Colore,WolfspiritM/Colore | Colore/Razer/NativeCallException.cs | Colore/Razer/NativeCallException.cs | // ---------------------------------------------------------------------------------------
// <copyright file="NativeCallException.cs" company="">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees
// and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility
// for any harm caused, direct or indirect, to any Razer peripherals
// via the use of Colore.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Colore.Razer
{
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
public class NativeCallException : ColoreException
{
private readonly string _function;
private readonly Result _result;
public NativeCallException(string function, Result result)
: base(
string.Format(
CultureInfo.InvariantCulture,
"Call to native Chroma API function {0} failed with error: {1}",
function,
result),
new Win32Exception(result))
{
_function = function;
_result = result;
}
protected NativeCallException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public string Function { get { return _function; } }
public Result Result { get { return _result; } }
}
}
| mit | C# | |
5e1f31100e8dbb42414dc513418261a684cfab04 | add missing file | SabotageAndi/ELMAR | net.the-engineers.elmar/elmar.droid/Events/ShutdownReceiver.cs | net.the-engineers.elmar/elmar.droid/Events/ShutdownReceiver.cs | using Android.App;
using Android.Content;
using elmar.droid.Common;
namespace elmar.droid.Events
{
[BroadcastReceiver]
[IntentFilter(new []{Intent.ActionShutdown})]
public class ShutdownReceiver : StandardBroadcastReceiver
{
protected override EventType EventType => EventType.DeviceShutDown;
}
} | agpl-3.0 | C# | |
4241ee7191bf54149727eb0478ddea9e1c482d0e | create customer entity | kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground,kidchenko/playground | DDD/DDD.Domain/Entities/Customer.cs | DDD/DDD.Domain/Entities/Customer.cs | using System;
namespace DDD.Domain.Entities
{
public class Customer
{
private const int YEARS_FOR_CUSTOMER_VIP = 5;
public Customer()
{
Created = DateTime.Now;
Active = true;
}
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
protected DateTime Created { get; private set; }
public bool Active { get; private set; }
public static bool IsCustomerVip(Customer customer)
{
return customer.Active && DateTime.Now.Year - customer.Created.Year >= YEARS_FOR_CUSTOMER_VIP;
}
public bool IsCustomerVip()
{
return IsCustomerVip(this);
}
}
}
| mit | C# | |
5e800e3b70cd18d584889d9f213885ce7e18d6be | add utility script to control time of multiple alembic stream in one place | unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter | AlembicImporter/Assets/AlembicImporter/Scripts/AlembicStreamSync.cs | AlembicImporter/Assets/AlembicImporter/Scripts/AlembicStreamSync.cs | using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class AlembicStreamSync : MonoBehaviour
{
public float m_time;
[Serializable]
public class SyncItem
{
public GameObject stream;
public bool sync = true;
}
[CustomPropertyDrawer(typeof(SyncItem))]
public class SyncItemDrawer : PropertyDrawer
{
override public void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), new GUIContent(label.text.Replace("Element", "Stream")));
// reset indent level
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
Rect chkr = new Rect(position.x, position.y, 10, position.height);
Rect fldr = new Rect(position.x + 15, position.y, position.width - 15, position.height);
EditorGUI.PropertyField(chkr, property.FindPropertyRelative("sync"), GUIContent.none);
EditorGUI.PropertyField(fldr, property.FindPropertyRelative("stream"), GUIContent.none);
// restore indent level
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
}
public SyncItem[] m_streams;
float m_time_prev;
float m_time_eps = 0.001f;
void Start()
{
m_time = 0.0f;
m_time_prev = 0.0f;
}
void Update()
{
m_time += Time.deltaTime;
if (Math.Abs(m_time - m_time_prev) > m_time_eps)
{
foreach (SyncItem si in m_streams)
{
if (si.stream == null || si.sync == false)
{
continue;
}
AlembicStream abcstream = si.stream.GetComponent<AlembicStream>();
if (abcstream != null)
{
abcstream.m_time = m_time;
}
}
}
m_time_prev = m_time;
}
}
| mit | C# | |
9989074bc1956c656c53665cda80e89e21fbc89a | Verify preorder - wrong | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | LeetCode/bootleg/verify_preorder.cs | LeetCode/bootleg/verify_preorder.cs | // http://lcoj.tk/problems/verify-preorder-serialization-of-a-binary-tree-dietpepsi-review/
//
// Given a string of comma separated values,
// verify whether it is a correct preorder traversal serialization of a binary tree.
// Find an algorithm without reconstructing the tree.
//
// A value in the string is either an integer or a character '#' representing null pointer.
//
// A correct serialization will contain all the numbers and null pointers in the binary tree.
using System;
using System.Collections.Generic;
static class Program
{
static bool ValidTree(this String a)
{
var s = new Stack<String>();
foreach (var c in a.Split(new [] { ',' }))
{
if (c == "#")
{
if (s.Count == 0)
{
return false;
}
s.Pop();
}
else
{
s.Push(c);
s.Push(c);
}
}
return s.Count == 0;
}
static void Main()
{
foreach (var x in new [] {
"9,3,4,#,#,1,#,#,2,#,6,#,#",
"1,#",
"9,#,#,1"
})
{
Console.WriteLine("{0} - {1}", x, x.ValidTree());
}
}
}
| mit | C# | |
6c628342ea8bb67157cc4bc6afa4041f64fcf340 | Add version helper to simplify creating a version list | Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector | KenticoInspector.Core/Helpers/VersionHelper.cs | KenticoInspector.Core/Helpers/VersionHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace KenticoInspector.Core.Helpers
{
public class VersionHelper
{
public static IList<Version> GetVersionList(params string[] versions)
{
return versions.Select(x => GetVersionFromShortString(x)).ToList();
}
public static Version GetVersionFromShortString(string version)
{
var expandedVersionString = ExpandVersionString(version);
return new Version(expandedVersionString);
}
public static string ExpandVersionString(string version)
{
var periodCount = version.Count(x => x == '.');
for (int i = 0; i < 2; i++)
{
version += ".0";
}
return version;
}
}
}
| mit | C# | |
ce4f8d0347d0092667a52faa0ec8ecc065aecdc0 | Add AbstractJoinOperation class. | ayende/rhino-etl,teodimache/rhino-etl,vebin/rhino-etl,regisbsb/rhino-etl,pushrbx/rhino-etl,hibernating-rhinos/rhino-etl,koulkov/rhino-etl,IntelliTect/rhino-etl,RudyCo/rhino-etl | Rhino.Etl.Core/Operations/AbstractJoinOperation.cs | Rhino.Etl.Core/Operations/AbstractJoinOperation.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rhino.Etl.Core.Operations
{
/// <summary>
/// Perform a join between two sources.
/// </summary>
public abstract class AbstractJoinOperation : AbstractOperation
{
/// <summary>
/// The left process
/// </summary>
protected readonly PartialProcessOperation left = new PartialProcessOperation();
/// <summary>
/// The rigth process
/// </summary>
protected readonly PartialProcessOperation right = new PartialProcessOperation();
/// <summary>
/// Is left registered?
/// </summary>
protected bool leftRegistered = false;
/// <summary>
/// Initializes this instance.
/// </summary>
protected virtual void Initialize()
{
}
/// <summary>
/// Called when a row on the right side was filtered by
/// the join condition, allow a derived class to perform
/// logic associated to that, such as logging
/// </summary>
protected virtual void RightOrphanRow(Row row)
{
}
/// <summary>
/// Called when a row on the left side was filtered by
/// the join condition, allow a derived class to perform
/// logic associated to that, such as logging
/// </summary>
/// <param name="row">The row.</param>
protected virtual void LeftOrphanRow(Row row)
{
}
/// <summary>
/// Check left/right branches are not null
/// </summary>
protected void PrepareForJoin()
{
Initialize();
Guard.Against(left == null, "Left branch of a join cannot be null");
Guard.Against(right == null, "Right branch of a join cannot be null");
}
/// <summary>
/// Initializes this instance
/// </summary>
/// <param name="pipelineExecuter">The current pipeline executer.</param>
public override void PrepareForExecution(IPipelineExecuter pipelineExecuter)
{
left.PrepareForExecution(pipelineExecuter);
right.PrepareForExecution(pipelineExecuter);
}
/// <summary>
/// Gets all errors that occured when running this operation
/// </summary>
/// <returns></returns>
public override IEnumerable<Exception> GetAllErrors()
{
foreach (Exception error in left.GetAllErrors())
{
yield return error;
}
foreach (Exception error in right.GetAllErrors())
{
yield return error;
}
foreach (Exception error in Errors)
{
yield return error;
}
}
/// <summary>
/// Merges the two rows into a single row
/// </summary>
/// <param name="leftRow">The left row.</param>
/// <param name="rightRow">The right row.</param>
/// <returns></returns>
protected abstract Row MergeRows(Row leftRow, Row rightRow);
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
left.Dispose();
right.Dispose();
}
}
} | bsd-3-clause | C# | |
27264d1793380fed98fe9014513228cf99f7597f | Add CreateGenericInstance Type extension method to help building models | zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder,danlister/Zbu.ModelsBuilder | Zbu.ModelsBuilder/TypeExtensions.cs | Zbu.ModelsBuilder/TypeExtensions.cs | using System;
namespace Zbu.ModelsBuilder
{
public static class TypeExtensions
{
/// <summary>
/// Creates a generic instance of a generic type with the proper actual type of an object.
/// </summary>
/// <param name="genericType">A generic type such as <c>Something{}</c></param>
/// <param name="typeParmObj">An object whose type is used as generic type param.</param>
/// <param name="ctorArgs">Arguments for the constructor.</param>
/// <returns>A generic instance of the generic type with the proper type.</returns>
/// <remarks>Usage... typeof (Something{}).CreateGenericInstance(object1, object2, object3) will return
/// a Something{Type1} if object1.GetType() is Type1.</remarks>
public static object CreateGenericInstance(this Type genericType, object typeParmObj, params object[] ctorArgs)
{
var type = genericType.MakeGenericType(typeParmObj.GetType());
return Activator.CreateInstance(type, ctorArgs);
}
}
}
| mit | C# | |
90312b75c2d9887760495d3b5b8e2ab961de416c | make it build | Norgg/Principia,pleroy/Principia,eggrobin/Principia,pleroy/Principia,mockingbirdnest/Principia,eggrobin/Principia,Norgg/Principia,mockingbirdnest/Principia,pleroy/Principia,pleroy/Principia,Norgg/Principia,eggrobin/Principia,mockingbirdnest/Principia,Norgg/Principia,mockingbirdnest/Principia | ksp_plugin_adapter/boxed.cs | ksp_plugin_adapter/boxed.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace principia {
namespace ksp_plugin_adapter {
// Strongly-typed boxing. This is used for marshaling optional parameters,
// since custom marshalers are only allowed on classes, strings, arrays, and
// boxed value types, so that |T?| cannot be marshaled, and |object| is not
// statically typed.
internal class Boxed<T> where T : struct {
public static implicit operator Boxed<T>(T all) {
return new Boxed<T>(all);
}
public T all { get; private set; }
private Boxed(T all) {
this.all = all;
}
}
} // namespace ksp_plugin_adapter
} // namespace principia
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace principia {
namespace ksp_plugin_adapter {
// Strongly-typed boxing. This is used for marshaling optional parameters,
// since custom marshalers are only allowed on classes, strings, arrays, and
// boxed value types, so that |T?| cannot be marshaled, and |object| is not
// statically typed.
internal class Boxed<T> where T : struct {
public static implicit operator Boxed<T>(T all) {
return new Boxed<T>(all);
}
public T all { get; }
private Boxed(T all) {
this.all = all;
}
}
} // namespace ksp_plugin_adapter
} // namespace principia
| mit | C# |
255f7b7b532a25276272331a4e224c9389a6931a | Add failing test scene | smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu | osu.Game.Tests/Skins/TestSceneSkinProvidingContainer.cs | osu.Game.Tests/Skins/TestSceneSkinProvidingContainer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Skins
{
public class TestSceneSkinProvidingContainer : OsuTestScene
{
/// <summary>
/// Ensures that the first inserted skin after resetting (via source change)
/// is always prioritised over others when providing the same resource.
/// </summary>
[Test]
public void TestPriorityPreservation()
{
TestSkinProvidingContainer provider = null;
TestSkin mostPrioritisedSource = null;
AddStep("setup sources", () =>
{
var sources = new List<TestSkin>();
for (int i = 0; i < 10; i++)
sources.Add(new TestSkin());
mostPrioritisedSource = sources.First();
Child = provider = new TestSkinProvidingContainer(sources);
});
AddAssert("texture provided by expected skin", () =>
{
return provider.FindProvider(s => s.GetTexture(TestSkin.TEXTURE_NAME) != null) == mostPrioritisedSource;
});
AddStep("trigger source change", () => provider.TriggerSourceChanged());
AddAssert("texture still provided by expected skin", () =>
{
return provider.FindProvider(s => s.GetTexture(TestSkin.TEXTURE_NAME) != null) == mostPrioritisedSource;
});
}
private class TestSkinProvidingContainer : SkinProvidingContainer
{
private readonly IEnumerable<ISkin> sources;
public TestSkinProvidingContainer(IEnumerable<ISkin> sources)
{
this.sources = sources;
}
public new void TriggerSourceChanged() => base.TriggerSourceChanged();
protected override void OnSourceChanged()
{
ResetSources();
sources.ForEach(AddSource);
}
}
private class TestSkin : ISkin
{
public const string TEXTURE_NAME = "virtual-texture";
public Drawable GetDrawableComponent(ISkinComponent component) => throw new System.NotImplementedException();
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT)
{
if (componentName == TEXTURE_NAME)
return Texture.WhitePixel;
return null;
}
public ISample GetSample(ISampleInfo sampleInfo) => throw new System.NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new System.NotImplementedException();
}
}
}
| mit | C# | |
f6c00f804ab2df377ceed834ff17e96261ee18ab | Create QType.cs | QetriX/CS | QetriX/libs/QType.cs | QetriX/libs/QType.cs | namespace com.qetrix.libs
{
/* Copyright (c) QetriX.com. Licensed under MIT License, see /LICENSE.txt file.
* 16.01.09 | QType
*/
using System;
using com.qetrix.libs;
/// <summary>
/// Description of QType.
/// </summary>
public class QType
{
// Class data
protected Integer t_pk = null; // Primary Key, null = new (not in DS yet)
protected string tg_fk; // Lang key for name
protected Integer tt_fk = null; // Parent type
protected int tmo = 1; // Max occurences in class. -1 = is ent, 127 = unlimited.
protected int toc = 0; // Order in class
protected string tds; // DataStore: engine.particletable OR engine.table.column
protected ValueType tvt = ValueType.anything; // Value type
protected string tvu = null; // Value unit (SI, if possible)
protected Integer tvn = null; // Min value (num) / min length (str)
protected Integer tvx = null; // Max value (num) / max length (str)
protected Integer tvp = null; // Value precision
protected string tvv = null; // Value validation
protected int tvm = 3; // Value mode (R/O, req, unique...)
protected RelationType trt = RelationType.none; // Relation type
protected OrderType tot = OrderType.none; // Order type
protected int tod = 1; // Default order for new particle
public Integer id()
{
return this.t_pk;
}
public string name()
{
return this.tg_fk;
}
public QType name(string value)
{
this.tg_fk = value;
return this;
}
public QType valueType(ValueType value)
{
this.tvt = value;
return this;
}
public ValueType valueType()
{
return this.tvt;
}
#region ENUMs
public enum ValueType {
none = 0,
system = 1,
anythingTN = 2,
wikiText = 3,
anythingN = 4,
htmlText = 5,
anything = 6,
number = 7,
yorn = 9,
url = 10,
email = 11,
geoPoint = 12,
dateTime = 13,
date = 14,
time = 15,
duration = 16,
color = 17,
password = 18
}
public enum RelationType {
none = 0,
system = 1,
searchSuggest = 2,
searchSuggestReq = 3,
searchSuggestTt = 4,
searchSuggestTtReq = 5,
suggest = 6,
suggestReq = 7,
suggestTt = 8,
suggestTtReq = 9,
table = 10,
tableReq = 11,
tableTt = 12,
tableTtReq = 13
}
public enum OrderType {
none = 0,
system = 1,
typeOrder = 2,
numericOrder = 4,
dateNoValidation = 10,
date = 12,
dateTimeNoValidation = 14,
dateTime = 16
}
#endregion
}
}
| mit | C# | |
533cfb52f9ff78d0836b8c924c4a8e5de2dc9fde | Clean up | retroburst/SpaceShooter | Assets/Scripts/DestroyByTime.cs | Assets/Scripts/DestroyByTime.cs | using UnityEngine;
using System.Collections;
/// <summary>
/// Destroy by time.
/// Destroys game objects based
/// on a given lifetime.
/// </summary>
public class DestroyByTime : MonoBehaviour
{
public float lifetime;
/// <summary>
/// Start this instance.
/// </summary>
private void Start ()
{
Destroy (gameObject, lifetime);
}
}
| mit | C# | |
bdf373cc3753336169c707d554b4857edf54e7ef | Create EnumTypeModelDescription.cs | MingLu8/Nancy.WebApi.HelpPages | src/Nancy.WebApi.HelpPages.Demo/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | src/Nancy.WebApi.HelpPages.Demo/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WebApplication1.Areas.HelpPage.ModelDescriptions
{
public class EnumTypeModelDescription : ModelDescription
{
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
public Collection<EnumValueDescription> Values { get; private set; }
}
}
| mit | C# | |
c7f288b120e2bb6240d64d25c1434377e16ff99d | Create HWD.cs | etormadiv/njRAT_0.7d_Stub_ReverseEngineering | j_csharp/OK/HWD.cs | j_csharp/OK/HWD.cs | //Reversed by Etor Madiv
public static string HWD()
{
string rootPathName;
string volumeName;
string fileSystemName;
int volumeSerialNumber;
int maximumComponentLength;
int fileSystemFlags;
try
{
rootPathName = System.String.Concat( Microsoft.VisualBasic.Interaction.Environ("SystemDrive"), "\\");
fileSystemName = volumeName = null;
fileSystemFlags = maximumComponentLength = 0;
GetVolumeInformation(
ref rootPathName,
ref volumeName,
0,
ref volumeSerialNumber,
ref maximumComponentLength,
ref fileSystemFlags,
ref fileSystemName,
0
);
return Microsoft.VisualBasic.Conversion.Hex( volumeSerialNumber );
}
catch(Exception)
{
}
return "ERR";
}
| unlicense | C# | |
675eee944fb2c19e6b62c2340d4bd145289f386b | Add a base for web forms controls | hishamco/WebForms,hishamco/WebForms | src/My.AspNetCore.WebForms/Controls/Control.cs | src/My.AspNetCore.WebForms/Controls/Control.cs | namespace My.AspNetCore.WebForms.Controls
{
public abstract class Control
{
public string Id { get; set; }
public string InnerHtml { get; protected set; }
public abstract void Render();
}
}
| mit | C# | |
6846d469bb3a6e7056068c1e224f9e6fdd87f854 | Add initial contract for message bus | mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype | src/Glimpse.Common/Broker/IMessageBus.cs | src/Glimpse.Common/Broker/IMessageBus.cs | using System;
namespace Glimpse.Broker
{
public interface IMessageBus
{
IObservable<T> Listen<T>();
IObservable<T> ListenIncludeLatest<T>();
bool IsRegistered(Type type);
}
} | mit | C# | |
67cbf14e099ec2095359d7c07fe61b828df4a6ef | Implement IEntityChangeSetReasonProvider in Abp.AspNetCore | carldai0106/aspnetboilerplate,fengyeju/aspnetboilerplate,luchaoshuai/aspnetboilerplate,AlexGeller/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,andmattia/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,andmattia/aspnetboilerplate,luchaoshuai/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,beratcarsi/aspnetboilerplate,verdentk/aspnetboilerplate,AlexGeller/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,ilyhacker/aspnetboilerplate,ilyhacker/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,beratcarsi/aspnetboilerplate,Nongzhsh/aspnetboilerplate,zclmoon/aspnetboilerplate,zclmoon/aspnetboilerplate,virtualcca/aspnetboilerplate,andmattia/aspnetboilerplate,ryancyq/aspnetboilerplate,fengyeju/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,virtualcca/aspnetboilerplate,fengyeju/aspnetboilerplate,AlexGeller/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,Nongzhsh/aspnetboilerplate,zclmoon/aspnetboilerplate | src/Abp.AspNetCore/AspNetCore/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs | src/Abp.AspNetCore/AspNetCore/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs | using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
namespace Abp.AspNetCore.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason => HttpContextAccessor.HttpContext?.Request.GetDisplayUrl();
protected IHttpContextAccessor HttpContextAccessor { get; }
public HttpRequestEntityChangeSetReasonProvider(
IHttpContextAccessor httpContextAccessor,
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
HttpContextAccessor = httpContextAccessor;
}
}
}
| mit | C# | |
a1733ef77f8ea360865e467cdd5817dd936a60c8 | Create RandomHandler.cs | LassieME/KiteBot | ConsoleApplication1/RandomHandler.cs | ConsoleApplication1/RandomHandler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KiteBot
{
public static class RandomHandler
{
//Handles the global random object
private static System.Random _random;
public static System.Random random
{
get
{
if (_random == null)
_random = new Random();
return _random;
}
}
}
}
| mit | C# | |
4587d19e4e36331ce88622182d47c00aab7f7f1e | Add TestLineChartViewModel class | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/TestLineChartViewModel.cs | WalletWasabi.Fluent/ViewModels/TestLineChartViewModel.cs | using System.Collections.Generic;
namespace WalletWasabi.Fluent.ViewModels
{
public class TestLineChartViewModel
{
public List<double> Values => new List<double>()
{
15,
22,
44,
50,
64,
68,
92,
114,
118,
142,
182,
222,
446,
548,
600
};
public List<string> Labels => new List<string>()
{
"6 days",
"4 days",
"3 days",
"1 day",
"22 hours",
"20 hours",
"18 hours",
"10 hours",
"6 hours",
"4 hours",
"2 hours",
"1 hour",
"50 min",
"30 min",
"20 min"
};
}
} | mit | C# | |
f0e65c529035511b5b43d23d3479364487982c3e | Create task_1_3_8_3.cs | AndrewTurlanov/ANdrew | task_1_3_8_3.cs | task_1_3_8_3.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
/*
Подумайте когда лучше использовать цикл for а когда while.
И приведите наилучший пример использования того и того цикла.
for - цикл, куда можем передавать параметр. Задаются начальное и конечное значение.
while - цикл пока соответствует условию. Можем не знать конечное кол-во действий в цикле
*/
int sum = 0, count = 5, start = 1;
for (int j = start; j <= count; j++)
{
sum += j;
}
Console.WriteLine("Сумма всех элементов c " + start + " до " + count + " = " + sum);
Console.WriteLine("Введите код");
string UserAge = Console.ReadLine();
int k = 1;
while (UserAge!="code")
{
Console.WriteLine("Неверный код, попытка " + k);
UserAge = Console.ReadLine();
k++;
}
}
}
}
| apache-2.0 | C# | |
633f13193985474585c88c2bee57c0d81b6b88e4 | add DisplayFPS.cs | NDark/ndinfrastructure,NDark/ndinfrastructure | Unity/NGUIUtil/DisplayFPS.cs | Unity/NGUIUtil/DisplayFPS.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisplayFPS : MonoBehaviour
{
public UILabel m_Label = null ;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if( null != m_Label )
{
if( fpsVec.Count < m_Length )
{
fpsVec.Add( Time.deltaTime ) ;
}
else
{
fpsVec[ m_Index++ ] = Time.deltaTime ;
if( m_Index >= m_Length )
{
m_Index = 0 ;
}
}
float max = float.MinValue ;
float min = float.MaxValue ;
float sum = 0.0f ;
for( int i = 0 ; i < fpsVec.Count ; ++i )
{
sum += fpsVec[ i ] ;
if( fpsVec[ i ] > max )
{
max = fpsVec[ i ] ;
}
if( fpsVec[ i ] < min )
{
min = fpsVec[ i ] ;
}
}
m_Label.text = string.Format( "avg:{0:#.##}/M:{1:#.##}/m:{2:#.##}"
, fpsVec.Count / sum
, 1.0f / min
, 1.0f / max );
}
}
int m_Length = 20 ;
int m_Index = 0 ;
List<float> fpsVec = new List<float>() ;
}
| mit | C# | |
a3cf5c3ec355e19455627b0be36497a9a04c0996 | Add c# solution TheDescent | joand/codingame,joand/codingame,joand/codingame,joand/codingame,joand/codingame,joand/codingame | easy/theDescent/src/main/cs/App.cs | easy/theDescent/src/main/cs/App.cs | using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
/**
* The while loop represents the game.
* Each iteration represents a turn of the game
* where you are given inputs (the heights of the mountains)
* and where you have to print an output (the index of the mountain to fire on)
* The inputs you are given are automatically updated according to your last actions.
**/
class Player
{
static void Main(string[] args)
{
// game loop
while (true)
{
int max = 0;
int mountainIndex = 0;
for (int i = 0; i < 8; i++)
{
int mountainH = int.Parse(Console.ReadLine()); // represents the height of one mountain.
Console.Error.WriteLine("Mountain Height: " + mountainH);
if (max < mountainH){
max = mountainH;
mountainIndex = i;
}
Console.Error.WriteLine("Max: " + max);
}
// Write an action using Console.WriteLine()
// To debug: Console.Error.WriteLine("Debug messages...");
Console.WriteLine(mountainIndex.ToString()); // The index of the mountain to fire on.
}
}
} | mit | C# | |
a05cfc92046df9a91a648133cbca1de32a095211 | Use property instead of field | KingJiangNet/boo,BitPuffin/boo,KingJiangNet/boo,BitPuffin/boo,BITechnologies/boo,hmah/boo,BillHally/boo,hmah/boo,KingJiangNet/boo,BitPuffin/boo,BitPuffin/boo,bamboo/boo,KingJiangNet/boo,KingJiangNet/boo,boo-lang/boo,BillHally/boo,drslump/boo,rmboggs/boo,drslump/boo,BITechnologies/boo,hmah/boo,bamboo/boo,KidFashion/boo,KingJiangNet/boo,BITechnologies/boo,drslump/boo,BillHally/boo,bamboo/boo,drslump/boo,rmboggs/boo,hmah/boo,KidFashion/boo,boo-lang/boo,hmah/boo,hmah/boo,rmboggs/boo,bamboo/boo,boo-lang/boo,BitPuffin/boo,BillHally/boo,bamboo/boo,KidFashion/boo,BillHally/boo,hmah/boo,KidFashion/boo,boo-lang/boo,rmboggs/boo,rmboggs/boo,bamboo/boo,BITechnologies/boo,BitPuffin/boo,drslump/boo,BitPuffin/boo,hmah/boo,boo-lang/boo,BITechnologies/boo,rmboggs/boo,hmah/boo,rmboggs/boo,KidFashion/boo,drslump/boo,boo-lang/boo,KingJiangNet/boo,BillHally/boo,boo-lang/boo,BITechnologies/boo,rmboggs/boo,bamboo/boo,drslump/boo,KidFashion/boo,BillHally/boo,KidFashion/boo,KingJiangNet/boo,BITechnologies/boo,boo-lang/boo,BITechnologies/boo,BitPuffin/boo | src/Boo.Lang/MetaAttribute.cs | src/Boo.Lang/MetaAttribute.cs | #region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang
{
using System;
[Serializable]
[AttributeUsage(AttributeTargets.Method)]
public class MetaAttribute : Attribute
{
// When true the meta-method arguments will be resolved and their ExpressionType
// bound before being passed to the meta-method.
public bool ResolveArgs { get; set; }
}
}
| #region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang
{
using System;
[Serializable]
[AttributeUsage(AttributeTargets.Method)]
public class MetaAttribute : Attribute
{
// When true the meta-method arguments will be resolved and their ExpressionType
// bound before being passed to the meta-method.
public bool ResolveArgs = false;
}
}
| bsd-3-clause | C# |
8cdcdbe04c76cad02adc604e10e6c4ec875c222e | Create DotnetSdkManager.cs | RadicalFx/Radical.Windows | targets/DotnetSdkManager.cs | targets/DotnetSdkManager.cs | using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using static SimpleExec.Command;
using Console = Colorful.Console;
class DotnetSdkManager
{
const string customSdkInstallDir = ".dotnet";
const string buildSupportDir = ".build";
string dotnetPath = null;
public string GetDotnetCliPath()
{
if (dotnetPath == null)
{
var (customSdk, sdkPath, sdkVersion) = EnsureRequiredSdkIsInstalled();
Console.WriteLine($"Build will be executed using {(customSdk ? "user defined SDK" : "default SDK")}, Version '{sdkVersion}'.{(customSdk ? $" Installed at '{sdkPath}'" : "")}");
dotnetPath = customSdk
? Path.Combine(sdkPath, "dotnet")
: "dotnet";
}
return dotnetPath;
}
(bool customSdk, string sdkPath, string sdkVersion) EnsureRequiredSdkIsInstalled()
{
var currentSdkVersion = Read("dotnet", "--version").TrimEnd(Environment.NewLine.ToCharArray());
var requiredSdkFile = Directory.EnumerateFiles(".", ".required-sdk", SearchOption.TopDirectoryOnly).SingleOrDefault();
if (string.IsNullOrWhiteSpace(requiredSdkFile))
{
Console.WriteLine("No custom SDK is required.", Color.Green);
return (false, "", currentSdkVersion);
}
var requiredSdkVersion = File.ReadAllText(requiredSdkFile).TrimEnd(Environment.NewLine.ToCharArray());
if (string.Compare(currentSdkVersion, requiredSdkVersion) == 0)
{
Console.WriteLine("Insalled SDK is the same as required one, '.required-sdk' file is not necessary. Build will use the SDK available on the machine.", Color.Yellow);
return (false, "", currentSdkVersion);
}
Console.WriteLine($"Installed SDK ({currentSdkVersion}) doesn't match required one ({requiredSdkVersion}).", Color.Yellow);
Console.WriteLine($"{requiredSdkVersion} will be installed and and used to run the build.", Color.Yellow);
var installScriptName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "dotnet-install.ps1"
: "dotnet-install.sh";
var installScriptUrl = $"https://dot.net/v1/{installScriptName}";
Console.WriteLine($"Downloading {installScriptName} script, from {installScriptUrl}.");
Directory.CreateDirectory(buildSupportDir);
new WebClient().DownloadFile(installScriptUrl, Path.Combine(buildSupportDir, installScriptName));
Console.WriteLine($"Ready to install custom SDK, version {requiredSdkVersion}.");
var installScriptLocation = Path.Combine(".", buildSupportDir, installScriptName);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Run("powershell", $@"{installScriptLocation} -Version {requiredSdkVersion} -InstallDir {customSdkInstallDir}");
}
else
{
Run("bash", $@"{installScriptLocation} --version {requiredSdkVersion} --install-dir {customSdkInstallDir}");
}
return (true, customSdkInstallDir, requiredSdkVersion);
}
}
| mit | C# | |
1d7e4ebed4261dca0c93e4654373534769c01163 | Add JWA enumeration for JWS Algorithms | thnetii/dotnet-common | src/THNETII.Security.JOSE/JsonWebSignatureAlgorithm.cs | src/THNETII.Security.JOSE/JsonWebSignatureAlgorithm.cs | using System.Runtime.Serialization;
namespace THNETII.Security.JOSE
{
/// <summary>
/// Defines the set of <c>"alg"</c> (algorithm) Header Parameter
/// values defined by this specification for use with JWS.
/// <para>Specified in <a href="https://tools.ietf.org/html/rfc7518#section-3.1">RFC 7518 - JSON Web Algorithms, Section 3.1: "alg" (Algorithm) Header Parameter Values for JWS</a>.</para>
/// </summary>
public enum JsonWebSignatureAlgorithm
{
Unknown = 0,
/// <summary>HMAC using SHA-256</summary>
[EnumMember]
HS256,
/// <summary>HMAC using SHA-384</summary>
[EnumMember]
HS384,
/// <summary>HMAC using SHA-512</summary>
[EnumMember]
HS512,
/// <summary>
/// RSASSA-PKCS1-v1_5 using
/// SHA-256
/// </summary>
[EnumMember]
RS256,
/// <summary>
/// RSASSA-PKCS1-v1_5 using
/// SHA-384
/// </summary>
[EnumMember]
RS384,
/// <summary>
/// RSASSA-PKCS1-v1_5 using
/// SHA-512
/// </summary>
[EnumMember]
RS512,
/// <summary>ECDSA using P-256 and SHA-256</summary>
[EnumMember]
ES256,
/// <summary>ECDSA using P-384 and SHA-384</summary>
[EnumMember]
ES384,
/// <summary>ECDSA using P-521 and SHA-512</summary>
[EnumMember]
ES512,
/// <summary>
/// RSASSA-PSS using SHA-256 and
/// MGF1 with SHA-256
/// </summary>
[EnumMember]
PS256,
/// <summary>
/// RSASSA-PSS using SHA-384 and
/// MGF1 with SHA-384
/// </summary>
[EnumMember]
PS384,
/// <summary>
/// RSASSA-PSS using SHA-512 and
/// MGF1 with SHA-512
/// </summary>
[EnumMember]
PS512,
/// <summary>
/// No digital signature or MAC
/// performed
/// </summary>
[EnumMember(Value = "none")]
None
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.