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
4483c3727fbb67f33c4b9c565a1f0161652fabad
Fix `ThreadsHandler` to use singular pipeline thread
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ThreadsHandler.cs
src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ThreadsHandler.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using Thread = OmniSharp.Extensions.DebugAdapter.Protocol.Models.Thread; namespace Microsoft.PowerShell.EditorServices.Handlers { internal class ThreadsHandler : IThreadsHandler { internal static Thread PipelineThread { get; } = new Thread { Id = 1, Name = "PowerShell Pipeline Thread" }; public Task<ThreadsResponse> Handle(ThreadsArguments request, CancellationToken cancellationToken) { return Task.FromResult(new ThreadsResponse { // TODO: OmniSharp supports multithreaded debugging (where // multiple threads can be debugged at once), but we don't. This // means we always need to set AllThreadsStoppped and // AllThreadsContinued in our events. But if we one day support // multithreaded debugging, we'd need a way to associate // debugged runspaces with .NET threads in a consistent way. Threads = new Container<Thread>(PipelineThread) }); } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; namespace Microsoft.PowerShell.EditorServices.Handlers { internal class ThreadsHandler : IThreadsHandler { public Task<ThreadsResponse> Handle(ThreadsArguments request, CancellationToken cancellationToken) { return Task.FromResult(new ThreadsResponse { // TODO: This is an empty container of threads...do we need to make a thread? Threads = new Container<System.Threading.Thread>() }); } } }
mit
C#
bb03d68d7461bbd26d81abebf3b546c2b4782e2c
increment version for nuget.
patHyatt/XmppBot-for-HipChat
XmppBot.Common/Properties/AssemblyInfo.cs
XmppBot.Common/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XmppBot.Common")] [assembly: AssemblyDescription("A library for making hipchat bots.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("roob and noob productions")] [assembly: AssemblyProduct("XmppBot.Common")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e03fc183-2fe0-4e7a-b231-c8e754fbbf77")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XmppBot.Common")] [assembly: AssemblyDescription("A library for making hipchat bots.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("roob and noob productions")] [assembly: AssemblyProduct("XmppBot.Common")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e03fc183-2fe0-4e7a-b231-c8e754fbbf77")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
ca68751fdcd1c3b0a01ead44e776600f0127e05b
Update test to match expectation
peppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game.Tests/Visual/Editing/TestSceneTimelineZoom.cs
osu.Game.Tests/Visual/Editing/TestSceneTimelineZoom.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Utils; namespace osu.Game.Tests.Visual.Editing { public class TestSceneTimelineZoom : TimelineTestScene { public override Drawable CreateTestComponent() => Empty(); [Test] public void TestVisibleRangeUpdatesOnZoomChange() { double initialVisibleRange = 0; AddStep("reset zoom", () => TimelineArea.Timeline.Zoom = 100); AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange); AddStep("scale zoom", () => TimelineArea.Timeline.Zoom = 200); AddAssert("range halved", () => Precision.AlmostEquals(TimelineArea.Timeline.VisibleRange, initialVisibleRange / 2, 1)); AddStep("descale zoom", () => TimelineArea.Timeline.Zoom = 50); AddAssert("range doubled", () => Precision.AlmostEquals(TimelineArea.Timeline.VisibleRange, initialVisibleRange * 2, 1)); AddStep("restore zoom", () => TimelineArea.Timeline.Zoom = 100); AddAssert("range restored", () => Precision.AlmostEquals(TimelineArea.Timeline.VisibleRange, initialVisibleRange, 1)); } [Test] public void TestVisibleRangeConstantOnSizeChange() { double initialVisibleRange = 0; AddStep("reset timeline size", () => TimelineArea.Timeline.Width = 1); AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange); AddStep("scale timeline size", () => TimelineArea.Timeline.Width = 2); AddAssert("same range", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange); AddStep("descale timeline size", () => TimelineArea.Timeline.Width = 0.5f); AddAssert("same range", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange); AddStep("restore timeline size", () => TimelineArea.Timeline.Width = 1); AddAssert("same range", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Utils; namespace osu.Game.Tests.Visual.Editing { public class TestSceneTimelineZoom : TimelineTestScene { public override Drawable CreateTestComponent() => Empty(); [Test] public void TestVisibleRangeViaZoom() { double initialVisibleRange = 0; AddStep("reset zoom", () => TimelineArea.Timeline.Zoom = 100); AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange); AddStep("scale zoom", () => TimelineArea.Timeline.Zoom = 200); AddAssert("range halved", () => Precision.AlmostEquals(TimelineArea.Timeline.VisibleRange, initialVisibleRange / 2, 1)); AddStep("descale zoom", () => TimelineArea.Timeline.Zoom = 50); AddAssert("range doubled", () => Precision.AlmostEquals(TimelineArea.Timeline.VisibleRange, initialVisibleRange * 2, 1)); AddStep("restore zoom", () => TimelineArea.Timeline.Zoom = 100); AddAssert("range restored", () => Precision.AlmostEquals(TimelineArea.Timeline.VisibleRange, initialVisibleRange, 1)); } [Test] public void TestVisibleRangeViaTimelineSize() { double initialVisibleRange = 0; AddStep("reset timeline size", () => TimelineArea.Timeline.Width = 1); AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange); AddStep("scale timeline size", () => TimelineArea.Timeline.Width = 2); AddAssert("range doubled", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange * 2); AddStep("descale timeline size", () => TimelineArea.Timeline.Width = 0.5f); AddAssert("range halved", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange / 2); AddStep("restore timeline size", () => TimelineArea.Timeline.Width = 1); AddAssert("range restored", () => TimelineArea.Timeline.VisibleRange == initialVisibleRange); } } }
mit
C#
34f34f4bece85b281212ac7f5de527bc65667ef7
reset PlayerMovement to fix merge conflict
lucasrumney94/JDPolterGhost,lucasrumney94/JDPolterGhost
JDPolterGhost/Assets/Scripts/Player/PlayerMovement.cs
JDPolterGhost/Assets/Scripts/Player/PlayerMovement.cs
using UnityEngine; using System.Collections; /// <summary> /// This script should be attached to the player, and handles all the forces applied. /// </summary> [RequireComponent(typeof(Rigidbody))] public class PlayerMovement : MonoBehaviour { public static GameObject player; public GameObject playerCamera; public bool forceMovement = false; public float speed = 5.0f; [Range(0f, 1f)] public float rotationSpeed = 0.1f; private Rigidbody playerRigidbody; private Interaction playerInteraction; void Start() { player = this.gameObject; playerCamera = GameObject.FindGameObjectWithTag(Tags.camera); playerRigidbody = GetComponent<Rigidbody>(); playerInteraction = GetComponent<Interaction>(); } /// <summary> /// Moves the player smoothly in the direction of movementVector /// </summary> /// <param name="movementVector">Direction of movement</param> public void MovePlayer(Vector3 movementVector) { if (playerInteraction.hauntingObject == false) { if (forceMovement) MoveForce(movementVector); else MoveVelocity(movementVector); if (movementVector.magnitude > 0.05f) { RotateToCamera(); } } else { playerRigidbody.velocity = Vector3.zero; } } private void MoveForce(Vector3 movementVector) { playerRigidbody.AddRelativeForce(movementVector); } private void MoveVelocity(Vector3 movementVector) { if (movementVector.magnitude > 1f) movementVector = movementVector.normalized; playerRigidbody.velocity = transform.TransformVector(movementVector) * speed; } private void RotateToCamera() { player.transform.rotation = Quaternion.Slerp(transform.rotation, playerCamera.transform.rotation, rotationSpeed); } }
using UnityEngine; using System.Collections; /// <summary> /// This script should be attached to the player, and handles all the forces applied. /// </summary> [RequireComponent(typeof(Rigidbody))] public class PlayerMovement : MonoBehaviour { public static GameObject player; public float speed = 5.0f; <<<<<<< HEAD ======= [Range(0f, 1f)] public float rotationSpeed = 0.1f; private Rigidbody playerRigidbody; private Interaction playerInteraction; >>>>>>> 7ef62bfb219949fe5f7b4fa747d48fb33275fd7a void Start() { player = this.gameObject; <<<<<<< HEAD ======= playerCamera = GameObject.FindGameObjectWithTag(Tags.camera); playerRigidbody = GetComponent<Rigidbody>(); playerInteraction = GetComponent<Interaction>(); >>>>>>> 7ef62bfb219949fe5f7b4fa747d48fb33275fd7a } /// <summary> /// Moves the player smoothly in the direction of movementVector /// </summary> /// <param name="movementVector">Direction of movement</param> public void MovePlayer(Vector3 movementVector) { <<<<<<< HEAD player.GetComponent<Rigidbody>().AddRelativeForce(movementVector); ======= if (playerInteraction.hauntingObject == false) { if (forceMovement) MoveForce(movementVector); else MoveVelocity(movementVector); if (movementVector.magnitude > 0.05f) { RotateToCamera(); } } else { playerRigidbody.velocity = Vector3.zero; } } private void MoveForce(Vector3 movementVector) { playerRigidbody.AddRelativeForce(movementVector); } private void MoveVelocity(Vector3 movementVector) { if (movementVector.magnitude > 1f) movementVector = movementVector.normalized; playerRigidbody.velocity = transform.TransformVector(movementVector) * speed; } private void RotateToCamera() { player.transform.rotation = Quaternion.Slerp(transform.rotation, playerCamera.transform.rotation, rotationSpeed); >>>>>>> 7ef62bfb219949fe5f7b4fa747d48fb33275fd7a } }
mit
C#
53baabcda59782111c115a560cba9eca030d626f
fix code analysis suppression
chunkychode/octokit.net,thedillonb/octokit.net,gdziadkiewicz/octokit.net,SamTheDev/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,dampir/octokit.net,octokit-net-test-org/octokit.net,M-Zuber/octokit.net,ivandrofly/octokit.net,shiftkey-tester/octokit.net,TattsGroup/octokit.net,M-Zuber/octokit.net,hahmed/octokit.net,Sarmad93/octokit.net,khellang/octokit.net,octokit/octokit.net,editor-tools/octokit.net,alfhenrik/octokit.net,devkhan/octokit.net,shiftkey/octokit.net,rlugojr/octokit.net,rlugojr/octokit.net,SamTheDev/octokit.net,eriawan/octokit.net,TattsGroup/octokit.net,dampir/octokit.net,chunkychode/octokit.net,adamralph/octokit.net,octokit-net-test-org/octokit.net,SmithAndr/octokit.net,thedillonb/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,devkhan/octokit.net,gdziadkiewicz/octokit.net,shiftkey/octokit.net,ivandrofly/octokit.net,SmithAndr/octokit.net,shana/octokit.net,shana/octokit.net,khellang/octokit.net,alfhenrik/octokit.net,shiftkey-tester/octokit.net,octokit/octokit.net,Sarmad93/octokit.net,hahmed/octokit.net,editor-tools/octokit.net,eriawan/octokit.net
Octokit/Models/Response/Enterprise/AdminStatsPulls.cs
Octokit/Models/Response/Enterprise/AdminStatsPulls.cs
using System.Diagnostics.CodeAnalysis; namespace Octokit { public class AdminStatsPulls { [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "unmergeable")] public AdminStatsPulls(int totalPulls, int mergedPulls, int mergeablePulls, int unmergeablePulls) { TotalPulls = totalPulls; MergedPulls = mergedPulls; MergeablePulls = mergeablePulls; UnmergeablePulls = unmergeablePulls; } public int TotalPulls { get; private set; } public int MergedPulls { get; private set; } public int MergeablePulls { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unmergeable")] public int UnmergeablePulls { get; private set; } } }
using System.Diagnostics.CodeAnalysis; namespace Octokit { public class AdminStatsPulls { [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "unmergeablePulls")] public AdminStatsPulls(int totalPulls, int mergedPulls, int mergeablePulls, int unmergeablePulls) { TotalPulls = totalPulls; MergedPulls = mergedPulls; MergeablePulls = mergeablePulls; UnmergeablePulls = unmergeablePulls; } public int TotalPulls { get; private set; } public int MergedPulls { get; private set; } public int MergeablePulls { get; private set; } public int UnmergeablePulls { get; private set; } } }
mit
C#
80459039f9d74b4d08cef1120ce421c6a66823a5
Fix automapper cast
affecto/dotnet-IdentityManagement
IdentityManagement.ApplicationServices/Mapping/RoleMapper.cs
IdentityManagement.ApplicationServices/Mapping/RoleMapper.cs
using System; using System.Collections.Generic; using System.Linq; using Affecto.IdentityManagement.ApplicationServices.Model; using Affecto.IdentityManagement.Interfaces.Model; using Affecto.Mapping.AutoMapper; using AutoMapper; namespace Affecto.IdentityManagement.ApplicationServices.Mapping { internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role> { protected override void ConfigureMaps() { Func<Querying.Data.Permission, IPermission> permissionCreator = o => new Permission(); Mapper.CreateMap<Querying.Data.Permission, IPermission>().ConvertUsing(permissionCreator); Mapper.CreateMap<Querying.Data.Permission, Permission>(); Mapper.CreateMap<Querying.Data.Role, Role>() .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<IPermission>>(c.Permissions.ToList()))); } } }
using System.Collections.Generic; using System.Linq; using Affecto.IdentityManagement.ApplicationServices.Model; using Affecto.IdentityManagement.Interfaces.Model; using Affecto.Mapping.AutoMapper; using AutoMapper; namespace Affecto.IdentityManagement.ApplicationServices.Mapping { internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role> { protected override void ConfigureMaps() { Mapper.CreateMap<Querying.Data.Permission, IPermission>().As<Permission>(); Mapper.CreateMap<Querying.Data.Permission, Permission>(); Mapper.CreateMap<Querying.Data.Role, Role>() .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<IPermission>>(c.Permissions.ToList()))); } } }
mit
C#
bfc757295ae6e040681db2ecbd7f357f5ebec758
Fix build breaking bug
MatthiWare/UpdateLib
UpdateLib/UpdateLib.Generator/Data/ListViewGenItem.cs
UpdateLib/UpdateLib.Generator/Data/ListViewGenItem.cs
/* UpdateLib - .Net auto update library * Copyright (C) 2016 - MatthiWare (Matthias Beerens) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using MatthiWare.UpdateLib.Generator.Data.FilesPage; using System; using System.Windows.Forms; namespace MatthiWare.UpdateLib.Generator.Data { public class ListViewGenItem : ListViewItem { public IGenItem Item { get; set; } public ListViewGenItem(IGenItem item) : base(item.GetListViewItems(), item.GetListViewImageKey()) { Item = item; Item.Changed += Item_Changed; } private void Item_Changed(object sender, EventArgs e) { string[] items = Item.GetListViewItems(); for (int i = 0; i < items.Length; i++) SubItems[i].Text = items[i]; ImageKey = Item.GetListViewImageKey(); } } }
/* UpdateLib - .Net auto update library * Copyright (C) 2016 - MatthiWare (Matthias Beerens) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using MatthiWare.UpdateLib.Generator.Data.FilesPage; using System.Windows.Forms; namespace MatthiWare.UpdateLib.Generator.Data { public class ListViewGenItem : ListViewItem { public IGenItem Item { get; set; } public ListViewGenItem(IGenItem item) : base(item.GetListViewItems(), item.GetListViewImageKey()) { Item = item; Item.Changed += Item_Changed; } private void Item_Changed(object sender, EventArgs e) { string[] items = Item.GetListViewItems(); for (int i = 0; i < items.Length; i++) SubItems[i].Text = items[i]; ImageKey = Item.GetListViewImageKey(); } } }
agpl-3.0
C#
0d06b698fdb595f5ed009ea07b5acf5bea8a8da9
Fix GetPixelSection test to get the pixel using the image, not the offscreen bitmap, as the offscreen bitmap does not (always) contain the entire image. Fixes #193, #190
bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto
Source/Eto.Test/Eto.Test/Sections/Drawing/GetPixelSection.cs
Source/Eto.Test/Eto.Test/Sections/Drawing/GetPixelSection.cs
using System; using System.Collections.Generic; using Eto.Forms; using Eto.Drawing; namespace Eto.Test.Sections.Drawing { public class GetPixelSection : Panel { public GetPixelSection() { var location = new Point(100, 100); var image = TestIcons.Textures(); var drawable = new Drawable(); var drawableTarget = new DrawableTarget(drawable) { UseOffScreenBitmap = true }; this.Content = drawable; EventHandler<MouseEventArgs> mouseHandler = (s, e) => { location = new Point(e.Location); ((Control)s).Invalidate(); e.Handled = true; }; drawable.MouseMove += mouseHandler; drawable.MouseDown += mouseHandler; var font = SystemFonts.Default(); drawable.BackgroundColor = Colors.Green; drawable.Paint += (s, e) => { var graphics = drawableTarget.BeginDraw(e); var imageLocation = new PointF(100, 100); graphics.DrawText(font, Colors.White, 3, 3, "Move the mouse in this area to read the pixel color."); graphics.DrawImage(image, imageLocation); var loc = location - (Point)imageLocation; loc.Restrict(new Rectangle(image.Size)); var pixelColor = image.GetPixel(loc.X, loc.Y); graphics.DrawText(font, Colors.White, 3, 20, "Color: " + pixelColor); drawableTarget.EndDraw(e); }; } } }
using System; using System.Collections.Generic; using Eto.Forms; using Eto.Drawing; namespace Eto.Test.Sections.Drawing { public class GetPixelSection : Panel { public GetPixelSection() { var location = new Point(100, 100); var image = TestIcons.Textures(); var drawable = new Drawable(); var drawableTarget = new DrawableTarget(drawable) { UseOffScreenBitmap = true }; this.Content = drawable; EventHandler<MouseEventArgs> mouseHandler = (s, e) => { location = new Point(e.Location); ((Control)s).Invalidate(); e.Handled = true; }; drawable.MouseMove += mouseHandler; drawable.MouseDown += mouseHandler; var font = SystemFonts.Default(); drawable.BackgroundColor = Colors.Green; drawable.Paint += (s, e) => { var graphics = drawableTarget.BeginDraw(e); graphics.DrawText(font, Colors.White, 3, 3, "Move the mouse in this area to read the pixel color."); graphics.DrawImage(image, new PointF(100, 100)); var pixelColor = drawableTarget.OffscreenBitmap.GetPixel(location.X, location.Y); graphics.DrawText(font, Colors.White, 3, 20, "Color: " + pixelColor); drawableTarget.EndDraw(e); }; } } }
bsd-3-clause
C#
d2b039e51a6314692ad200586d8493b4d9479c7a
Add mockability comment
DimensionDataCBUSydney/jab
jab/jab/Http/HttpClientFactory.cs
jab/jab/Http/HttpClientFactory.cs
using System; using System.Net.Http; using Jab.Interfaces; namespace Jab.Http { /// <summary> /// Extension methods for <see cref="JabTestConfiguration"/>. /// </summary> public static class JabHttpClientFactory { // TODO: How do we mock this? Should we make it a non extension method and do it the old fashioned way? /// <summary> /// Construct an <see cref="HttpClient"/> for the current <see cref="IJabTestConfiguration.BaseUrl"/>, if any. /// </summary> /// <param name="configuration"> /// The <see cref="IJabApiOperation"/> to extract the configuration from. This cannot be null. /// </param> /// <returns> /// An <see cref="HttpClient"/> initialized for the current <see cref="IJabTestConfiguration.BaseUrl"/> or null, /// if <see cref="IJabTestConfiguration.BaseUrl"/> is null. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="configuration"/> cannot be null. /// </exception> public static HttpClient GetClient(this IJabTestConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return configuration.BaseUrl != null ? new HttpClient() { BaseAddress = configuration.BaseUrl } : null; } } }
using System; using System.Net.Http; using Jab.Interfaces; namespace Jab.Http { /// <summary> /// Extension methods for <see cref="JabTestConfiguration"/>. /// </summary> public static class JabHttpClientFactory { /// <summary> /// Construct an <see cref="HttpClient"/> for the current <see cref="IJabTestConfiguration.BaseUrl"/>, if any. /// </summary> /// <param name="configuration"> /// The <see cref="IJabApiOperation"/> to extract the configuration from. This cannot be null. /// </param> /// <returns> /// An <see cref="HttpClient"/> initialized for the current <see cref="IJabTestConfiguration.BaseUrl"/> or null, /// if <see cref="IJabTestConfiguration.BaseUrl"/> is null. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="configuration"/> cannot be null. /// </exception> public static HttpClient GetClient(this IJabTestConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } return configuration.BaseUrl != null ? new HttpClient() { BaseAddress = configuration.BaseUrl } : null; } } }
apache-2.0
C#
ddf726d0854c9b89f39d12968f83519d55aeb57b
Fix PublicKey (#1174)
SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource/sonar-msbuild-runner
src/SonarScanner.MSBuild.PreProcessor/Properties/InternalsVisibleTo.cs
src/SonarScanner.MSBuild.PreProcessor/Properties/InternalsVisibleTo.cs
/* * SonarScanner for .NET * Copyright (C) 2016-2022 SonarSource SA * mailto: info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System.Runtime.CompilerServices; #if SignAssembly [assembly: InternalsVisibleTo("SonarScanner.MSBuild.PreProcessor.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010081b4345a022cc0f4b42bdc795a5a7a1623c1e58dc2246645d751ad41ba98f2749dc5c4e0da3a9e09febcb2cd5b088a0f041f8ac24b20e736d8ae523061733782f9c4cd75b44f17a63714aced0b29a59cd1ce58d8e10ccdb6012c7098c39871043b7241ac4ab9f6b34f183db716082cd57c1ff648135bece256357ba735e67dc6")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] #else [assembly: InternalsVisibleTo("SonarScanner.MSBuild.PreProcessor.Test")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] #endif
/* * SonarScanner for .NET * Copyright (C) 2016-2022 SonarSource SA * mailto: info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System.Runtime.CompilerServices; #if SignAssembly [assembly: InternalsVisibleTo("SonarScanner.MSBuild.PreProcessor.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010081b4345a022cc0f4b42bdc795a5a7a1623c1e58dc2246645d751ad41ba98f2749dc5c4e0da3a9e09febcb2cd5b088a0f041f8ac24b20e736d8ae523061733782f9c4cd75b44f17a63714aced0b29a59cd1ce58d8e10ccdb6012c7098c39871043b7241ac4ab9f6b34f183db716082cd57c1ff648135bece256357ba735e67dc6")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=002400000480000094000000060200000024000052534131000400000100010081b4345a022cc0f4b42bdc795a5a7a1623c1e58dc2246645d751ad41ba98f2749dc5c4e0da3a9e09febcb2cd5b088a0f041f8ac24b20e736d8ae523061733782f9c4cd75b44f17a63714aced0b29a59cd1ce58d8e10ccdb6012c7098c39871043b7241ac4ab9f6b34f183db716082cd57c1ff648135bece256357ba735e67dc6")] #else [assembly: InternalsVisibleTo("SonarScanner.MSBuild.PreProcessor.Test")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] #endif
mit
C#
c08d49df8a90f00a875604fa31c8f766e6065f8b
fix PalletisationStation for transport-only roles
maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp
Models/SelfOrganizingPillProduction/Modeling/PalletisationStation.cs
Models/SelfOrganizingPillProduction/Modeling/PalletisationStation.cs
using SafetySharp.Modeling; namespace SafetySharp.CaseStudies.SelfOrganizingPillProduction.Modeling { /// <summary> /// A production station that removes containers from the conveyor belt, closes, labels and stores them on pallets. /// </summary> public class PalletisationStation : Station { public readonly Fault PalletisationDefect = new PermanentFault(); public override Capability[] AvailableCapabilities { get; } = new[] { new ConsumeCapability() }; protected override void ExecuteRole(Role role) { // unless role is transport only, it will always be { ConsumeCapability } if (role.CapabilitiesToApply.Count > 0) { Container.Recipe.RemoveContainer(Container); if (Container.Recipe.ProcessingComplete) { RemoveRecipeConfigurations(Container.Recipe); } Container = null; } } [FaultEffect(Fault = nameof(PalletisationDefect))] public class PalletisationDefectEffect : PalletisationStation { public override Capability[] AvailableCapabilities => new Capability[0]; } [FaultEffect(Fault = nameof(CompleteStationFailure))] public class CompleteStationFailureEffect : PalletisationStation { public override bool IsAlive => false; public override void Update() { } } } }
using SafetySharp.Modeling; namespace SafetySharp.CaseStudies.SelfOrganizingPillProduction.Modeling { /// <summary> /// A production station that removes containers from the conveyor belt, closes, labels and stores them on pallets. /// </summary> public class PalletisationStation : Station { public readonly Fault PalletisationDefect = new PermanentFault(); public override Capability[] AvailableCapabilities { get; } = new[] { new ConsumeCapability() }; protected override void ExecuteRole(Role role) { Container.Recipe.RemoveContainer(Container); if (Container.Recipe.ProcessingComplete) { RemoveRecipeConfigurations(Container.Recipe); } Container = null; } [FaultEffect(Fault = nameof(PalletisationDefect))] public class PalletisationDefectEffect : PalletisationStation { public override Capability[] AvailableCapabilities => new Capability[0]; } [FaultEffect(Fault = nameof(CompleteStationFailure))] public class CompleteStationFailureEffect : PalletisationStation { public override bool IsAlive => false; public override void Update() { } } } }
mit
C#
19bf2020492fb6cc0a8145cf68754f175b784f52
Update AtataSettings
atata-framework/atata-sample-app-tests
src/AtataSampleApp.UITests.Components/AtataSettings.cs
src/AtataSampleApp.UITests.Components/AtataSettings.cs
using Atata; [assembly: Culture("en-us")] [assembly: VerifyTitleSettings(Format = "{0} - Atata Sample App")] // You can, for example, configure trigger to take screenshots before any click. //[assembly: Screenshot(On = TriggerEvents.BeforeClick, AppliesTo = TriggerScope.Children)]
using Atata; [assembly: Culture("en-us")] [assembly: VerifyTitleSettings(Format = "{0} - Atata Sample App")] [assembly: Screenshot(On = TriggerEvents.BeforeClick, AppliesTo = TriggerScope.Children)]
apache-2.0
C#
bb6ffdfd52423765a63eb7aa19d90b4f94f4b5b1
Fix the problem that the web request is displayed twice when -Verbosity is set to detailed.
oliver-feng/nuget,GearedToWar/NuGet2,pratikkagda/nuget,mono/nuget,oliver-feng/nuget,mrward/nuget,OneGet/nuget,mrward/nuget,akrisiun/NuGet,oliver-feng/nuget,jmezach/NuGet2,pratikkagda/nuget,mrward/NuGet.V2,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,xoofx/NuGet,pratikkagda/nuget,antiufo/NuGet2,antiufo/NuGet2,antiufo/NuGet2,mrward/NuGet.V2,GearedToWar/NuGet2,GearedToWar/NuGet2,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,mrward/NuGet.V2,pratikkagda/nuget,jholovacs/NuGet,xoofx/NuGet,chocolatey/nuget-chocolatey,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,oliver-feng/nuget,jmezach/NuGet2,GearedToWar/NuGet2,jmezach/NuGet2,pratikkagda/nuget,oliver-feng/nuget,mono/nuget,xoofx/NuGet,rikoe/nuget,RichiCoder1/nuget-chocolatey,mono/nuget,mrward/nuget,RichiCoder1/nuget-chocolatey,jholovacs/NuGet,antiufo/NuGet2,indsoft/NuGet2,RichiCoder1/nuget-chocolatey,rikoe/nuget,indsoft/NuGet2,chocolatey/nuget-chocolatey,jmezach/NuGet2,indsoft/NuGet2,jholovacs/NuGet,akrisiun/NuGet,mono/nuget,mrward/nuget,xoofx/NuGet,mrward/NuGet.V2,jholovacs/NuGet,mrward/nuget,jmezach/NuGet2,rikoe/nuget,xoofx/NuGet,jholovacs/NuGet,GearedToWar/NuGet2,antiufo/NuGet2,OneGet/nuget,mrward/NuGet.V2,xoofx/NuGet,pratikkagda/nuget,chocolatey/nuget-chocolatey,mrward/nuget,OneGet/nuget,indsoft/NuGet2,jholovacs/NuGet,mrward/NuGet.V2,GearedToWar/NuGet2,indsoft/NuGet2,chocolatey/nuget-chocolatey,OneGet/nuget,rikoe/nuget,oliver-feng/nuget,jmezach/NuGet2
src/CommandLine/Common/CommandLineRepositoryFactory.cs
src/CommandLine/Common/CommandLineRepositoryFactory.cs
 using System.Windows; namespace NuGet.Common { public class CommandLineRepositoryFactory : PackageRepositoryFactory, IWeakEventListener { public static readonly string UserAgent = "NuGet Command Line"; private readonly IConsole _console; public CommandLineRepositoryFactory(IConsole console) { _console = console; } public override IPackageRepository CreateRepository(string packageSource) { var repository = base.CreateRepository(packageSource); var httpClientEvents = repository as IHttpClientEvents; if (httpClientEvents != null) { SendingRequestEventManager.AddListener(httpClientEvents, this); } return repository; } public bool ReceiveWeakEvent(System.Type managerType, object sender, System.EventArgs e) { if (managerType == typeof(SendingRequestEventManager)) { var args = (WebRequestEventArgs)e; if (_console.Verbosity == Verbosity.Detailed) { _console.WriteLine( System.ConsoleColor.Green, "{0} {1}", args.Request.Method, args.Request.RequestUri); } string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent); HttpUtility.SetUserAgent(args.Request, userAgent); return true; } else { return false; } } } }
 namespace NuGet.Common { public class CommandLineRepositoryFactory : PackageRepositoryFactory { public static readonly string UserAgent = "NuGet Command Line"; private readonly IConsole _console; public CommandLineRepositoryFactory(IConsole console) { _console = console; } public override IPackageRepository CreateRepository(string packageSource) { var repository = base.CreateRepository(packageSource); var httpClientEvents = repository as IHttpClientEvents; if (httpClientEvents != null) { httpClientEvents.SendingRequest += (sender, args) => { if (_console.Verbosity == Verbosity.Detailed) { _console.WriteLine( System.ConsoleColor.Green, "{0} {1}", args.Request.Method, args.Request.RequestUri); } string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent); HttpUtility.SetUserAgent(args.Request, userAgent); }; } return repository; } } }
apache-2.0
C#
9ba869c74409dcb0d2a60a29de5b89709b8b8d6c
Fix admin ObjectsTab error (#11272)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/Administration/UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs
Content.Client/Administration/UI/Tabs/ObjectsTab/ObjectsTab.xaml.cs
using System.Linq; using Content.Client.Station; using Robust.Client.AutoGenerated; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.XAML; namespace Content.Client.Administration.UI.Tabs.ObjectsTab; [GenerateTypedNameReferences] public sealed partial class ObjectsTab : Control { [Dependency] private readonly EntityManager _entityManager = default!; private readonly List<ObjectsTabEntry> _objects = new(); private List<ObjectsTabSelection> _selections = new(); public event Action<BaseButton.ButtonEventArgs>? OnEntryPressed; public ObjectsTab() { RobustXamlLoader.Load(this); IoCManager.InjectDependencies(this); ObjectTypeOptions.OnItemSelected += ev => { ObjectTypeOptions.SelectId(ev.Id); RefreshObjectList(_selections[ev.Id]); }; foreach (var type in Enum.GetValues(typeof(ObjectsTabSelection))) { _selections.Add((ObjectsTabSelection)type!); ObjectTypeOptions.AddItem(Enum.GetName((ObjectsTabSelection)type!)!); } RefreshObjectList(_selections[ObjectTypeOptions.SelectedId]); } private void RefreshObjectList(ObjectsTabSelection selection) { var entities = selection switch { ObjectsTabSelection.Stations => _entityManager.EntitySysManager.GetEntitySystem<StationSystem>().Stations.ToList(), ObjectsTabSelection.Grids => _entityManager.EntityQuery<IMapGridComponent>(true).Select(x => x.Owner).ToList(), ObjectsTabSelection.Maps => _entityManager.EntityQuery<IMapComponent>(true).Select(x => x.Owner).ToList(), _ => throw new ArgumentOutOfRangeException(nameof(selection), selection, null) }; foreach (var control in _objects) { ObjectList.RemoveChild(control); } _objects.Clear(); foreach (var entity in entities) { // TODO the server eitehr needs to send the entity's name, or it needs to ensure the client knows about the entity. var name = _entityManager.GetComponentOrNull<MetaDataComponent>(entity)?.EntityName ?? "Unknown Entity"; // this should be fixed, so I CBF localizing. var ctrl = new ObjectsTabEntry(name, entity); _objects.Add(ctrl); ObjectList.AddChild(ctrl); ctrl.OnPressed += args => OnEntryPressed?.Invoke(args); } } private enum ObjectsTabSelection { Grids, Maps, Stations, } }
using System.Linq; using Content.Client.Station; using Robust.Client.AutoGenerated; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.XAML; namespace Content.Client.Administration.UI.Tabs.ObjectsTab; [GenerateTypedNameReferences] public sealed partial class ObjectsTab : Control { [Dependency] private readonly EntityManager _entityManager = default!; private readonly List<ObjectsTabEntry> _objects = new(); private List<ObjectsTabSelection> _selections = new(); public event Action<BaseButton.ButtonEventArgs>? OnEntryPressed; public ObjectsTab() { RobustXamlLoader.Load(this); IoCManager.InjectDependencies(this); ObjectTypeOptions.OnItemSelected += ev => { ObjectTypeOptions.SelectId(ev.Id); RefreshObjectList(_selections[ev.Id]); }; foreach (var type in Enum.GetValues(typeof(ObjectsTabSelection))) { _selections.Add((ObjectsTabSelection)type!); ObjectTypeOptions.AddItem(Enum.GetName((ObjectsTabSelection)type!)!); } RefreshObjectList(_selections[ObjectTypeOptions.SelectedId]); } private void RefreshObjectList(ObjectsTabSelection selection) { var entities = selection switch { ObjectsTabSelection.Stations => _entityManager.EntitySysManager.GetEntitySystem<StationSystem>().Stations.ToList(), ObjectsTabSelection.Grids => _entityManager.EntityQuery<IMapGridComponent>(true).Select(x => x.Owner).ToList(), ObjectsTabSelection.Maps => _entityManager.EntityQuery<IMapComponent>(true).Select(x => x.Owner).ToList(), _ => throw new ArgumentOutOfRangeException(nameof(selection), selection, null) }; foreach (var control in _objects) { ObjectList.RemoveChild(control); } _objects.Clear(); foreach (var entity in entities) { var ctrl = new ObjectsTabEntry(_entityManager.GetComponent<MetaDataComponent>(entity).EntityName, entity); _objects.Add(ctrl); ObjectList.AddChild(ctrl); ctrl.OnPressed += args => OnEntryPressed?.Invoke(args); } } private enum ObjectsTabSelection { Grids, Maps, Stations, } }
mit
C#
b2f5d197103992dc6808c7fec2a4b2d70adec9f7
update code after change of namespace.
chtoucas/Narvalo.NET,chtoucas/Narvalo.NET
src/Narvalo.Common/Collections/NameValueCollection$.cs
src/Narvalo.Common/Collections/NameValueCollection$.cs
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Collections { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Narvalo; using Narvalo.Applicative; using Narvalo.Linq.Applicative; /// <summary> /// Provides extension methods for <see cref="NameValueCollection"/> /// that depend on the <see cref="Maybe{T}"/> class. /// </summary> public static partial class NameValueCollectionExtensions { public static Maybe<string> MayGetSingle(this NameValueCollection @this, string name) => from values in @this.MayGetValues(name) where values.Length == 1 select values[0]; public static Maybe<string[]> MayGetValues(this NameValueCollection @this, string name) { Require.NotNull(@this, nameof(@this)); return Maybe.Of(@this.GetValues(name)); } public static IEnumerable<T> ParseAny<T>( this NameValueCollection @this, string name, Func<string, Maybe<T>> parser) => (from arr in @this.MayGetValues(name) select arr.SelectAny(parser)) .ValueOrElse(Enumerable.Empty<T>()); public static Maybe<IEnumerable<T>> MayParseAll<T>( this NameValueCollection @this, string name, Func<string, Maybe<T>> parser) => @this.MayGetValues(name).Select(arr => arr.Select(parser).CollectAny()); } }
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Collections { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Narvalo; using Narvalo.Applicative; using Narvalo.Linq; /// <summary> /// Provides extension methods for <see cref="NameValueCollection"/> /// that depend on the <see cref="Maybe{T}"/> class. /// </summary> public static partial class NameValueCollectionExtensions { public static Maybe<string> MayGetSingle(this NameValueCollection @this, string name) => from values in @this.MayGetValues(name) where values.Length == 1 select values[0]; public static Maybe<string[]> MayGetValues(this NameValueCollection @this, string name) { Require.NotNull(@this, nameof(@this)); return Maybe.Of(@this.GetValues(name)); } public static IEnumerable<T> ParseAny<T>( this NameValueCollection @this, string name, Func<string, Maybe<T>> parser) => (from vals in @this.MayGetValues(name) select vals.SelectAny(parser)) .ValueOrElse(Enumerable.Empty<T>()); public static Maybe<IEnumerable<T>> MayParseAll<T>( this NameValueCollection @this, string name, Func<string, Maybe<T>> parser) => @this.MayGetValues(name).Select(val => val.Select(parser).CollectAny()); } }
bsd-2-clause
C#
c76b8f73e61cd34ff62c1748821ef070987b7869
Revert "LoginTest is completed"
oleksandrp1/SeleniumTasks
SeleniumTasksProject1.1/SeleniumTasksProject1.1/InternetExplorer.cs
SeleniumTasksProject1.1/SeleniumTasksProject1.1/InternetExplorer.cs
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.IE; using OpenQA.Selenium.Support.UI; using NUnit.Framework; namespace SeleniumTasksProject1._1 { [TestFixture] public class InternetExplorer { private IWebDriver driver; private WebDriverWait wait; [SetUp] public void start() { driver = new InternetExplorerDriver(); wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); } [Test] public void LoginTestInInternetExplorer() { driver.Url = "http://localhost:8082/litecart/admin/"; } [TearDown] public void stop() { driver.Quit(); driver = null; } } }
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.IE; using OpenQA.Selenium.Support.UI; using NUnit.Framework; namespace SeleniumTasksProject1._1 { [TestFixture] public class InternetExplorer { private IWebDriver driver; private WebDriverWait wait; [SetUp] public void start() { driver = new InternetExplorerDriver(); wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); } [Test] public void LoginTestInInternetExplorer() { driver.Url = "http://localhost:8082/litecart/admin/"; driver.FindElement(By.Name("username")).SendKeys("admin"); driver.FindElement(By.Name("password")).SendKeys("admin"); driver.FindElement(By.Name("login")).Click(); //wait.Until(ExpectedConditions.TitleIs("My Store")); } [TearDown] public void stop() { driver.Quit(); driver = null; } } }
apache-2.0
C#
1220f2718bb545d5ff2ec06dd496b89877417f01
Use bitwise operator (review by Clive)
mjac/dependency-injection-kata-series,jcrang/dependency-injection-kata-series
src/DependencyInjection.Console/OddEvenPatternGenerator.cs
src/DependencyInjection.Console/OddEvenPatternGenerator.cs
namespace DependencyInjection.Console { internal class OddEvenPatternGenerator : IPatternGenerator { public Pattern Generate(int width, int height) { var generate = new Pattern(width, height); var squares = generate.Squares; for (var i = 0; i < squares.GetLength(0); ++i) { for (var j = 0; j < squares.GetLength(1); ++j) { squares[i, j] = ((i ^ j) & 1) == 0 ? Square.White : Square.Black; } } return generate; } } }
namespace DependencyInjection.Console { internal class OddEvenPatternGenerator : IPatternGenerator { public Pattern Generate(int width, int height) { var generate = new Pattern(width, height); var squares = generate.Squares; for (var i = 0; i < squares.GetLength(0); ++i) { for (var j = 0; j < squares.GetLength(1); ++j) { squares[i, j] = (i ^ j) % 2 == 0 ? Square.White : Square.Black; } } return generate; } } }
mit
C#
10c832959e19c8aa31536dba5c545802c713d05d
Add description and copyright
jackawatts/ionfar-sharepoint-migration,sgryphon/ionfar-sharepoint-migration,jackawatts/ionfar-sharepoint-migration,sgryphon/ionfar-sharepoint-migration
src/IonFar.SharePoint.Migration/Properties/AssemblyInfo.cs
src/IonFar.SharePoint.Migration/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IonFar.SharePoint.Migration")] [assembly: AssemblyDescription("Library that helps you to deploy and manage changes to a SharePoint Site collection using the client side object model (CSOM). Changes are recorded once run in a SharePoint environment so that only changes that need to be run will be applied.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IonFar.SharePoint.Migration")] [assembly: AssemblyCopyright("Copyright © Jack Watts 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4f643f6d-aec9-42f4-94dd-d033f074088c")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IonFar.SharePoint.Migration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IonFar.SharePoint.Migration")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4f643f6d-aec9-42f4-94dd-d033f074088c")]
mit
C#
d463d9722ebc3be486fc61ee543ee5f87053976e
Remove whitespace
vflorusso/nether,ankodu/nether,krist00fer/nether,navalev/nether,stuartleeks/nether,brentstineman/nether,stuartleeks/nether,MicrosoftDX/nether,ankodu/nether,brentstineman/nether,brentstineman/nether,navalev/nether,navalev/nether,stuartleeks/nether,vflorusso/nether,vflorusso/nether,brentstineman/nether,ankodu/nether,navalev/nether,brentstineman/nether,ankodu/nether,stuartleeks/nether,vflorusso/nether,vflorusso/nether,oliviak/nether,stuartleeks/nether
src/Nether.Data/PlayerManagement/IPlayerManagementStore.cs
src/Nether.Data/PlayerManagement/IPlayerManagementStore.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Nether.Data.PlayerManagement { public interface IPlayerManagementStore { //Players Task SavePlayerAsync(Player player); Task<Player> GetPlayerDetailsAsync(string gamertag); Task<List<Player>> GetPlayersAsync(); Task<List<Group>> GetPlayersGroupsAsync(string gamertag); Task UploadPlayerImageAsync(string gamertag, byte[] image); Task<byte[]> GetPlayerImageAsync(string gamertag); //Group Task SaveGroupAsync(Group group); Task<Group> GetGroupDetailsAsync(string groupname); Task AddPlayerToGroupAsync(Group group, Player player); Task RemovePlayerFromGroupAsync(Group group, Player player); Task<List<Player>> GetGroupPlayersAsync(string groupname); Task<List<Group>> GetGroups(); Task UploadGroupImageAsync(string groupname, byte[] image); Task<byte[]> GetGroupImageAsync(string name); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Nether.Data.PlayerManagement { public interface IPlayerManagementStore { //Players Task SavePlayerAsync(Player player); Task<Player> GetPlayerDetailsAsync(string gamertag); Task<List<Player>> GetPlayersAsync(); Task<List<Group>> GetPlayersGroupsAsync(string gamertag); Task UploadPlayerImageAsync(string gamertag, byte[] image); Task<byte[]> GetPlayerImageAsync(string gamertag); //Group Task SaveGroupAsync(Group group); Task<Group> GetGroupDetailsAsync(string groupname); Task AddPlayerToGroupAsync(Group group, Player player); Task RemovePlayerFromGroupAsync(Group group, Player player); Task<List<Player>> GetGroupPlayersAsync(string groupname); Task<List<Group>> GetGroups(); Task UploadGroupImageAsync(string groupname, byte[] image); Task<byte[]> GetGroupImageAsync(string name); } }
mit
C#
0d1111c8f3283de9c0409754ac23aef375c1264d
Make QuartzOptions properties public for real
sean-gilliam/quartznet,quartznet/quartznet,sean-gilliam/quartznet,quartznet/quartznet,sean-gilliam/quartznet,quartznet/quartznet,sean-gilliam/quartznet,quartznet/quartznet,quartznet/quartznet,sean-gilliam/quartznet
src/Quartz.Extensions.DependencyInjection/QuartzOptions.cs
src/Quartz.Extensions.DependencyInjection/QuartzOptions.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using Quartz.Impl; namespace Quartz { public class QuartzOptions : NameValueCollection { internal readonly List<IJobDetail> jobDetails = new List<IJobDetail>(); internal readonly List<ITrigger> triggers = new List<ITrigger>(); public string? SchedulerId { get => this[StdSchedulerFactory.PropertySchedulerInstanceId]; set => this[StdSchedulerFactory.PropertySchedulerInstanceId] = value; } public string? SchedulerName { get => this[StdSchedulerFactory.PropertySchedulerName]; set => this[StdSchedulerFactory.PropertySchedulerName] = value; } public TimeSpan? MisfireThreshold { get => TimeSpan.FromMilliseconds(int.Parse(this["quartz.jobStore.misfireThreshold"])); set => this["quartz.jobStore.misfireThreshold"] = value != null ? ((int) value.Value.TotalMilliseconds).ToString() : ""; } public SchedulingOptions Scheduling { get; set; } = new SchedulingOptions(); public JobFactoryOptions JobFactory { get; set; } = new JobFactoryOptions(); public IReadOnlyList<IJobDetail> JobDetails => jobDetails; public IReadOnlyList<ITrigger> Triggers => triggers; public QuartzOptions AddJob(Type jobType, Action<JobBuilder> configure) { var builder = JobBuilder.Create(jobType); configure(builder); jobDetails.Add(builder.Build()); return this; } public QuartzOptions AddJob<T>(Action<JobBuilder> configure) where T : IJob { var builder = JobBuilder.Create<T>(); configure(builder); jobDetails.Add(builder.Build()); return this; } public QuartzOptions AddTrigger(Action<TriggerBuilder> configure) { var builder = TriggerBuilder.Create(); configure(builder); triggers.Add(builder.Build()); return this; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using Quartz.Impl; namespace Quartz { public class QuartzOptions : NameValueCollection { internal readonly List<IJobDetail> jobDetails = new List<IJobDetail>(); internal readonly List<ITrigger> triggers = new List<ITrigger>(); public string? SchedulerId { get => this[StdSchedulerFactory.PropertySchedulerInstanceId]; set => this[StdSchedulerFactory.PropertySchedulerInstanceId] = value; } public string? SchedulerName { get => this[StdSchedulerFactory.PropertySchedulerName]; set => this[StdSchedulerFactory.PropertySchedulerName] = value; } public TimeSpan? MisfireThreshold { get => TimeSpan.FromMilliseconds(int.Parse(this["quartz.jobStore.misfireThreshold"])); set => this["quartz.jobStore.misfireThreshold"] = value != null ? ((int) value.Value.TotalMilliseconds).ToString() : ""; } public SchedulingOptions Scheduling { get; set; } = new SchedulingOptions(); public JobFactoryOptions JobFactory { get; set; } = new JobFactoryOptions(); internal IReadOnlyList<IJobDetail> JobDetails => jobDetails; internal IReadOnlyList<ITrigger> Triggers => triggers; public QuartzOptions AddJob(Type jobType, Action<JobBuilder> configure) { var builder = JobBuilder.Create(jobType); configure(builder); jobDetails.Add(builder.Build()); return this; } public QuartzOptions AddJob<T>(Action<JobBuilder> configure) where T : IJob { var builder = JobBuilder.Create<T>(); configure(builder); jobDetails.Add(builder.Build()); return this; } public QuartzOptions AddTrigger(Action<TriggerBuilder> configure) { var builder = TriggerBuilder.Create(); configure(builder); triggers.Add(builder.Build()); return this; } } }
apache-2.0
C#
df6a755c3653a4c473c9031eea52198158cdf304
Update player loader screen mouse disable text to use localised version
peppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu
osu.Game/Screens/Play/PlayerSettings/InputSettings.cs
osu.Game/Screens/Play/PlayerSettings/InputSettings.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.Configuration; using osu.Game.Localisation; namespace osu.Game.Screens.Play.PlayerSettings { public class InputSettings : PlayerSettingsGroup { private readonly PlayerCheckbox mouseButtonsCheckbox; public InputSettings() : base("Input Settings") { Children = new Drawable[] { mouseButtonsCheckbox = new PlayerCheckbox { LabelText = MouseSettingsStrings.DisableMouseButtons } }; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) => mouseButtonsCheckbox.Current = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } }
// 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.Configuration; namespace osu.Game.Screens.Play.PlayerSettings { public class InputSettings : PlayerSettingsGroup { private readonly PlayerCheckbox mouseButtonsCheckbox; public InputSettings() : base("Input Settings") { Children = new Drawable[] { mouseButtonsCheckbox = new PlayerCheckbox { LabelText = "Disable mouse buttons" } }; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) => mouseButtonsCheckbox.Current = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } }
mit
C#
4ae9797f4a1b814d9ff7b08d23b37fdc60592364
Add comment.
mattwar/roslyn,jamesqo/roslyn,jkotas/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,mmitche/roslyn,physhi/roslyn,tvand7093/roslyn,srivatsn/roslyn,panopticoncentral/roslyn,mattscheffer/roslyn,heejaechang/roslyn,mattscheffer/roslyn,cston/roslyn,sharwell/roslyn,tannergooding/roslyn,robinsedlaczek/roslyn,Hosch250/roslyn,mattscheffer/roslyn,bkoelman/roslyn,khyperia/roslyn,dotnet/roslyn,AnthonyDGreen/roslyn,yeaicc/roslyn,TyOverby/roslyn,AlekseyTs/roslyn,TyOverby/roslyn,ErikSchierboom/roslyn,bkoelman/roslyn,xasx/roslyn,aelij/roslyn,mattwar/roslyn,kelltrick/roslyn,weltkante/roslyn,jamesqo/roslyn,abock/roslyn,CaptainHayashi/roslyn,amcasey/roslyn,Giftednewt/roslyn,Hosch250/roslyn,aelij/roslyn,tmat/roslyn,kelltrick/roslyn,lorcanmooney/roslyn,jamesqo/roslyn,AnthonyDGreen/roslyn,dotnet/roslyn,khyperia/roslyn,KirillOsenkov/roslyn,dpoeschl/roslyn,sharwell/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,MichalStrehovsky/roslyn,jcouv/roslyn,reaction1989/roslyn,agocke/roslyn,brettfo/roslyn,aelij/roslyn,AmadeusW/roslyn,kelltrick/roslyn,davkean/roslyn,nguerrera/roslyn,abock/roslyn,shyamnamboodiripad/roslyn,swaroop-sridhar/roslyn,agocke/roslyn,tannergooding/roslyn,nguerrera/roslyn,wvdd007/roslyn,orthoxerox/roslyn,DustinCampbell/roslyn,CaptainHayashi/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,tmat/roslyn,heejaechang/roslyn,DustinCampbell/roslyn,amcasey/roslyn,VSadov/roslyn,tannergooding/roslyn,pdelvo/roslyn,orthoxerox/roslyn,VSadov/roslyn,genlu/roslyn,mmitche/roslyn,MattWindsor91/roslyn,amcasey/roslyn,eriawan/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,mavasani/roslyn,jcouv/roslyn,eriawan/roslyn,dpoeschl/roslyn,khyperia/roslyn,bartdesmet/roslyn,cston/roslyn,reaction1989/roslyn,tmeschter/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,lorcanmooney/roslyn,gafter/roslyn,KevinRansom/roslyn,srivatsn/roslyn,paulvanbrenk/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,lorcanmooney/roslyn,OmarTawfik/roslyn,jkotas/roslyn,AlekseyTs/roslyn,mattwar/roslyn,KevinRansom/roslyn,gafter/roslyn,stephentoub/roslyn,mavasani/roslyn,davkean/roslyn,DustinCampbell/roslyn,brettfo/roslyn,diryboy/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tmat/roslyn,panopticoncentral/roslyn,tmeschter/roslyn,genlu/roslyn,diryboy/roslyn,tmeschter/roslyn,eriawan/roslyn,genlu/roslyn,jasonmalinowski/roslyn,xasx/roslyn,heejaechang/roslyn,KevinRansom/roslyn,stephentoub/roslyn,tvand7093/roslyn,yeaicc/roslyn,dpoeschl/roslyn,jmarolf/roslyn,srivatsn/roslyn,drognanar/roslyn,VSadov/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,jcouv/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,swaroop-sridhar/roslyn,MattWindsor91/roslyn,pdelvo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Hosch250/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,drognanar/roslyn,reaction1989/roslyn,OmarTawfik/roslyn,TyOverby/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,paulvanbrenk/roslyn,AnthonyDGreen/roslyn,agocke/roslyn,OmarTawfik/roslyn,paulvanbrenk/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,davkean/roslyn,robinsedlaczek/roslyn,Giftednewt/roslyn,mavasani/roslyn,cston/roslyn,xasx/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,physhi/roslyn,pdelvo/roslyn,CyrusNajmabadi/roslyn,MattWindsor91/roslyn,jkotas/roslyn,tvand7093/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,mgoertz-msft/roslyn,yeaicc/roslyn,wvdd007/roslyn,abock/roslyn,drognanar/roslyn,Giftednewt/roslyn,weltkante/roslyn,orthoxerox/roslyn,jasonmalinowski/roslyn,robinsedlaczek/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,jmarolf/roslyn,diryboy/roslyn,bartdesmet/roslyn,mmitche/roslyn
src/Features/Core/Portable/DesignerAttributes/DesignerAttributeDocumentData.cs
src/Features/Core/Portable/DesignerAttributes/DesignerAttributeDocumentData.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; namespace Microsoft.CodeAnalysis.DesignerAttributes { /// <summary> /// Marshalling type to pass designer attribute data to/from the OOP process. /// </summary> internal struct DesignerAttributeDocumentData : IEquatable<DesignerAttributeDocumentData> { public string FilePath; public string DesignerAttributeArgument; public bool ContainsErrors; public bool NotApplicable; public DesignerAttributeDocumentData(string filePath, string designerAttributeArgument, bool containsErrors, bool notApplicable) { FilePath = filePath; DesignerAttributeArgument = designerAttributeArgument; ContainsErrors = containsErrors; NotApplicable = notApplicable; } public override bool Equals(object obj) => Equals((DesignerAttributeDocumentData)obj); public bool Equals(DesignerAttributeDocumentData other) { return FilePath == other.FilePath && DesignerAttributeArgument == other.DesignerAttributeArgument && ContainsErrors == other.ContainsErrors && NotApplicable == other.NotApplicable; } // Currently no need for GetHashCode. If we end up using this as a key in a dictionary, // feel free to add. public override int GetHashCode() => throw new NotImplementedException(); } }
// 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; namespace Microsoft.CodeAnalysis.DesignerAttributes { /// <summary> /// Marshalling type to pass designer attribute data to/from the OOP process. /// </summary> internal struct DesignerAttributeDocumentData : IEquatable<DesignerAttributeDocumentData> { public string FilePath; public string DesignerAttributeArgument; public bool ContainsErrors; public bool NotApplicable; public DesignerAttributeDocumentData(string filePath, string designerAttributeArgument, bool containsErrors, bool notApplicable) { FilePath = filePath; DesignerAttributeArgument = designerAttributeArgument; ContainsErrors = containsErrors; NotApplicable = notApplicable; } public override bool Equals(object obj) => Equals((DesignerAttributeDocumentData)obj); public bool Equals(DesignerAttributeDocumentData other) { return FilePath == other.FilePath && DesignerAttributeArgument == other.DesignerAttributeArgument && ContainsErrors == other.ContainsErrors && NotApplicable == other.NotApplicable; } public override int GetHashCode() => throw new NotImplementedException(); } }
mit
C#
c31ed55a0efaaeb73164ec100e527cb96354c289
Remove unecessary code
zhenlan/corefx,Ermiar/corefx,Jiayili1/corefx,Jiayili1/corefx,Ermiar/corefx,axelheer/corefx,Jiayili1/corefx,ViktorHofer/corefx,BrennanConroy/corefx,ravimeda/corefx,ViktorHofer/corefx,wtgodbe/corefx,Jiayili1/corefx,axelheer/corefx,wtgodbe/corefx,Ermiar/corefx,ericstj/corefx,axelheer/corefx,BrennanConroy/corefx,Jiayili1/corefx,mmitche/corefx,zhenlan/corefx,zhenlan/corefx,shimingsg/corefx,ptoonen/corefx,ravimeda/corefx,Ermiar/corefx,shimingsg/corefx,ViktorHofer/corefx,mmitche/corefx,axelheer/corefx,mmitche/corefx,ptoonen/corefx,ericstj/corefx,mmitche/corefx,zhenlan/corefx,shimingsg/corefx,wtgodbe/corefx,wtgodbe/corefx,zhenlan/corefx,ravimeda/corefx,wtgodbe/corefx,Ermiar/corefx,mmitche/corefx,wtgodbe/corefx,ptoonen/corefx,Ermiar/corefx,ericstj/corefx,ravimeda/corefx,ravimeda/corefx,ravimeda/corefx,axelheer/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,mmitche/corefx,ptoonen/corefx,ViktorHofer/corefx,ptoonen/corefx,wtgodbe/corefx,zhenlan/corefx,axelheer/corefx,ViktorHofer/corefx,ptoonen/corefx,BrennanConroy/corefx,Jiayili1/corefx,Jiayili1/corefx,zhenlan/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,ericstj/corefx,ravimeda/corefx,Ermiar/corefx,mmitche/corefx
src/System.Runtime/tests/System/Reflection/ReflectionTypeLoadExceptionTests.cs
src/System.Runtime/tests/System/Reflection/ReflectionTypeLoadExceptionTests.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.Runtime.CompilerServices; using Xunit; [assembly: TypeForwardedTo(typeof(string))] [assembly: TypeForwardedTo(typeof(TypeInForwardedAssembly))] namespace System.Reflection.Tests { public static class ReflectionTypeLoadExceptionTests { [Fact] public static void NullExceptionsNoNullPointerException() { bool foundRtleException = false; try { Type[] Typo = new Type[1]; Exception[] Excepto = new Exception[1]; throw new ReflectionTypeLoadException(Typo, Excepto, "Null elements in Exceptions array"); } catch (ReflectionTypeLoadException) { foundRtleException = true; } Assert.True(foundRtleException); } [Fact] public static void NullArgumentsNoNullPointerException() { bool foundRtleException = false; try { throw new ReflectionTypeLoadException(null, null, "Null arguments"); } catch (ReflectionTypeLoadException) { foundRtleException = true; } Assert.True(foundRtleException); } } }
// 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.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; [assembly: TypeForwardedTo(typeof(string))] [assembly: TypeForwardedTo(typeof(TypeInForwardedAssembly))] namespace System.Reflection.Tests { public static class ReflectionTypeLoadExceptionTests { [Fact] public static void NullExceptionsNoNullPointerException() { bool foundRtleException = false; try { Type[] Typo = new Type[1]; Exception[] Excepto = new Exception[1]; throw new ReflectionTypeLoadException(Typo, Excepto, "Null elements in Exceptions array"); } catch (ReflectionTypeLoadException e) { foundRtleException = true; } Assert.True(foundRtleException); } [Fact] public static void NullArgumentsNoNullPointerException() { bool foundRtleException = false; try { throw new ReflectionTypeLoadException(null, null, "Null arguments"); } catch (ReflectionTypeLoadException e) { foundRtleException = true; } Assert.True(foundRtleException); } } }
mit
C#
0539fbc3ea440f4d71f81f0508a4ff4b871124df
implement suttering like TG does it
krille90/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Resources/ScriptableObjects/Speech/CustomMods/Stuttering.cs
UnityProject/Assets/Resources/ScriptableObjects/Speech/CustomMods/Stuttering.cs
using System.Text.RegularExpressions; using UnityEngine; [CreateAssetMenu(fileName = "CustomSpeechModifierCode", menuName = "ScriptableObjects/SpeechModifiers/CustomCode")] public class Stuttering : CustomSpeechModifier { private static string Stutter(Match m) { string x = m.ToString(); string stutter = ""; //80% to match TG probability if (DMMath.Prob(80)) { //Randomly pick how bad is the stutter int intensity = Random.Range(1, 4); for (int i = 0; i < intensity; i++) { stutter = stutter + x + "-"; //h-h-h- } stutter += x; //h-h-h-h[ello] } else { stutter = x; } return stutter; } public override string ProcessMessage(string message) { // //Stuttering people randomly repeat beginnings of words // //Regex - find word boundary followed by non digit, non special symbol, non end of word letter. Basically find the start of words. // Regex rx = new Regex(@"(\b)+([^\d\W])\B"); // message = rx.Replace(message, Stutter); message = Regex.Replace(message, @"(\b)+([^\d\W])\B", Stutter); return message; } }
using System.Text.RegularExpressions; using UnityEngine; [CreateAssetMenu(fileName = "CustomSpeechModifierCode", menuName = "ScriptableObjects/SpeechModifiers/CustomCode")] public class Stuttering : CustomSpeechModifier { private static string Stutter(Match m) { string x = m.ToString(); string stutter = ""; //20% chance to stutter at any given consonant if (Random.Range(1, 6) == 1) { //Randomly pick how bad is the stutter int intensity = Random.Range(1, 4); for (int i = 0; i < intensity; i++) { stutter = stutter + x + "... "; //h... h... h... } stutter += x; //h... h... h... h[ello] } else { stutter = x; } return stutter; } public override string ProcessMessage(string message) { // //Stuttering people randomly repeat beginnings of words // //Regex - find word boundary followed by non digit, non special symbol, non end of word letter. Basically find the start of words. Regex rx = new Regex(@"(\b)+([^\d\W])\B"); message = rx.Replace(message, Stutter); return message; } }
agpl-3.0
C#
6d0f8d90ffa15eafed122984cd397590a08af1bf
Increment version
R-Smith/vmPing
vmPing/Properties/AssemblyInfo.cs
vmPing/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("vmPing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("vmPing")] [assembly: AssemblyCopyright("Copyright © 2021 Ryan Smith")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.9.0")] [assembly: AssemblyFileVersion("1.3.9.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("vmPing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("vmPing")] [assembly: AssemblyCopyright("Copyright © 2021 Ryan Smith")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.8.0")] [assembly: AssemblyFileVersion("1.3.8.0")]
mit
C#
5aeef0383c7749408afd08484d56759e5fb81be4
Bump dll version
Nicholas-Westby/Archetype,kjac/Archetype,kipusoep/Archetype,kgiszewski/Archetype,tomfulton/Archetype,imulus/Archetype,kjac/Archetype,kgiszewski/Archetype,kgiszewski/Archetype,Nicholas-Westby/Archetype,kipusoep/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,kjac/Archetype,kipusoep/Archetype,tomfulton/Archetype,tomfulton/Archetype,imulus/Archetype
app/Umbraco/Umbraco.Archetype/Properties/VersionInfo.cs
app/Umbraco/Umbraco.Archetype/Properties/VersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0-beta")]
using System.Reflection; [assembly: AssemblyVersion("0.6")] [assembly: AssemblyFileVersion("0.6-beta")]
mit
C#
f06af4da99a86f54aab4c9a9c61a3049b4050a3e
Update automatic reservations flag to match what has been implemented
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/SFA.DAS.Reservations.Api.Types/ReservationAllocationStatusResult.cs
src/SFA.DAS.Reservations.Api.Types/ReservationAllocationStatusResult.cs
namespace SFA.DAS.Reservations.Api.Types { public class ReservationAllocationStatusResult { public bool CanAutoCreateReservations { get; set; } } }
using System.Collections.Generic; using System.Linq; namespace SFA.DAS.Reservations.Api.Types { public class ReservationAllocationStatusResult { public bool AutoReservations { get; set; } } }
mit
C#
039c51ae332b9f6146df36fd40ce48d2071cc7e4
Print out the response as a string when the exception is not JSON
projectkudu/kudu,puneet-gupta/kudu,juoni/kudu,uQr/kudu,shanselman/kudu,bbauya/kudu,MavenRain/kudu,dev-enthusiast/kudu,barnyp/kudu,shibayan/kudu,MavenRain/kudu,uQr/kudu,kali786516/kudu,projectkudu/kudu,EricSten-MSFT/kudu,shibayan/kudu,duncansmart/kudu,badescuga/kudu,shrimpy/kudu,uQr/kudu,chrisrpatterson/kudu,sitereactor/kudu,shibayan/kudu,kali786516/kudu,shibayan/kudu,kenegozi/kudu,projectkudu/kudu,mauricionr/kudu,uQr/kudu,juoni/kudu,projectkudu/kudu,shrimpy/kudu,juvchan/kudu,WeAreMammoth/kudu-obsolete,juoni/kudu,shibayan/kudu,EricSten-MSFT/kudu,WeAreMammoth/kudu-obsolete,kali786516/kudu,shrimpy/kudu,shanselman/kudu,oliver-feng/kudu,oliver-feng/kudu,chrisrpatterson/kudu,shanselman/kudu,oliver-feng/kudu,sitereactor/kudu,duncansmart/kudu,barnyp/kudu,badescuga/kudu,WeAreMammoth/kudu-obsolete,duncansmart/kudu,badescuga/kudu,shrimpy/kudu,mauricionr/kudu,duncansmart/kudu,MavenRain/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,juvchan/kudu,bbauya/kudu,mauricionr/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,puneet-gupta/kudu,dev-enthusiast/kudu,puneet-gupta/kudu,kenegozi/kudu,kenegozi/kudu,barnyp/kudu,juoni/kudu,MavenRain/kudu,kali786516/kudu,YOTOV-LIMITED/kudu,juvchan/kudu,sitereactor/kudu,badescuga/kudu,EricSten-MSFT/kudu,juvchan/kudu,bbauya/kudu,bbauya/kudu,puneet-gupta/kudu,chrisrpatterson/kudu,dev-enthusiast/kudu,oliver-feng/kudu,mauricionr/kudu,projectkudu/kudu,EricSten-MSFT/kudu,juvchan/kudu,chrisrpatterson/kudu,sitereactor/kudu,YOTOV-LIMITED/kudu,sitereactor/kudu,barnyp/kudu,YOTOV-LIMITED/kudu,kenegozi/kudu,dev-enthusiast/kudu
Kudu.Client/Infrastructure/HttpResponseMessageExtensions.cs
Kudu.Client/Infrastructure/HttpResponseMessageExtensions.cs
using System; using System.Net; using System.Net.Http; namespace Kudu.Client { public static class HttpResponseMessageExtensions { /// <summary> /// Determines if the HttpResponse is successful, throws otherwise. /// </summary> public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage) { if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError) { // For 500, we serialize the exception message on the server. HttpExceptionMessage exceptionMessage; try { exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result; } catch (InvalidOperationException ex) { // This would happen if the response type is not a Json object. throw new HttpRequestException(httpResponseMessage.Content.ReadAsStringAsync().Result, ex); } exceptionMessage.StatusCode = httpResponseMessage.StatusCode; exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase; throw new HttpUnsuccessfulRequestException(exceptionMessage); } return httpResponseMessage.EnsureSuccessStatusCode(); } } public class HttpExceptionMessage { public HttpStatusCode StatusCode { get; set; } public string ReasonPhrase { get; set; } public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } } public class HttpUnsuccessfulRequestException : HttpRequestException { public HttpUnsuccessfulRequestException() : this(null) { } public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage) : base( responseMessage != null ? String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) : null) { ResponseMessage = responseMessage; } public HttpExceptionMessage ResponseMessage { get; private set; } } }
using System; using System.Net; using System.Net.Http; namespace Kudu.Client { public static class HttpResponseMessageExtensions { /// <summary> /// Determines if the HttpResponse is successful, throws otherwise. /// </summary> public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage) { if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError) { // For 500, we serialize the exception message on the server. var exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result; exceptionMessage.StatusCode = httpResponseMessage.StatusCode; exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase; throw new HttpUnsuccessfulRequestException(exceptionMessage); } return httpResponseMessage.EnsureSuccessStatusCode(); } } public class HttpExceptionMessage { public HttpStatusCode StatusCode { get; set; } public string ReasonPhrase { get; set; } public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } } public class HttpUnsuccessfulRequestException : HttpRequestException { public HttpUnsuccessfulRequestException() : this(null) { } public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage) : base( responseMessage != null ? String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) : null) { ResponseMessage = responseMessage; } public HttpExceptionMessage ResponseMessage { get; private set; } } }
apache-2.0
C#
03b053e93f801d82c27b6b1637690d1e13c710a8
Use MediaUrl instead.
gjulianm/Ocell
Ocell.UI/Ocell.Phone7/Helpers/ValueConverters/TextToMediaConverter.cs
Ocell.UI/Ocell.Phone7/Helpers/ValueConverters/TextToMediaConverter.cs
using Ocell.Library; using System; using System.Linq; using System.Windows.Data; using System.Windows.Media.Imaging; using TweetSharp; namespace Ocell { public class TextToMediaConverter : IValueConverter { private static MediaLinkParser parser = new MediaLinkParser(); public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { var status = value as TwitterStatus; string imageLink = null; if (status != null && status.Entities != null) { if (status.Entities.Media.Any()) { imageLink = status.Entities.Media.First().MediaUrl; } else { foreach (var url in status.Entities.Urls) if (parser.TryGetMediaUrl(url.ExpandedValue, out imageLink)) break; } } Uri imageUri; if (imageLink != null && Uri.TryCreate(imageLink, UriKind.Absolute, out imageUri)) return new BitmapImage(imageUri); else return null; } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new System.NotImplementedException(); } } }
using Ocell.Library; using System; using System.Linq; using System.Windows.Data; using System.Windows.Media.Imaging; using TweetSharp; namespace Ocell { public class TextToMediaConverter : IValueConverter { private static MediaLinkParser parser = new MediaLinkParser(); public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { var status = value as TwitterStatus; string imageLink = null; if (status != null && status.Entities != null) { if (status.Entities.Media.Any()) { imageLink = status.Entities.Media.First().ExpandedUrl; } else { foreach (var url in status.Entities.Urls) if (parser.TryGetMediaUrl(url.ExpandedValue, out imageLink)) break; } } Uri imageUri; if (imageLink != null && Uri.TryCreate(imageLink, UriKind.Absolute, out imageUri)) return new BitmapImage(imageUri); else return null; } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new System.NotImplementedException(); } } }
mpl-2.0
C#
b49b517b415cb2ba8ca878d73ed368559b0080e4
Add Environment path tracing
Tuesdaysgreen/AzureSiteReplicator,Tuesdaysgreen/AzureSiteReplicator,Tuesdaysgreen/AzureSiteReplicator,projectkudu/AzureSiteReplicator,projectkudu/AzureSiteReplicator,projectkudu/AzureSiteReplicator
AzureSiteReplicator/Environment.cs
AzureSiteReplicator/Environment.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; namespace AzureSiteReplicator { public class Environment { public static Environment Instance = new Environment(); public Environment() { string homePath = System.Environment.ExpandEnvironmentVariables(@"%SystemDrive%\home"); if (Directory.Exists(homePath)) { // Running on Azure // Publish the wwwroot folder ContentPath = Path.Combine(homePath, "site", "wwwroot"); PublishSettingsPath = Path.Combine(homePath, "data", "SiteReplicator"); } else { // Local case: run from App_Data for testing purpose string appData = HostingEnvironment.MapPath("~/App_Data"); ContentPath = Path.Combine(appData, "source"); PublishSettingsPath = Path.Combine(appData, "PublishSettingsFiles"); } Trace.TraceInformation("ContentPath={0}", ContentPath); Directory.CreateDirectory(ContentPath); Trace.TraceInformation("PublishSettingsPath={0}", PublishSettingsPath); Directory.CreateDirectory(PublishSettingsPath); } // Path to the web content we want to replicate public string ContentPath { get; set; } // Path to the publish settings files that drive where we publish to public string PublishSettingsPath { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; namespace AzureSiteReplicator { public class Environment { public static Environment Instance = new Environment(); public Environment() { string homePath = System.Environment.ExpandEnvironmentVariables(@"%SystemDrive%\home"); if (Directory.Exists(homePath)) { // Running on Azure // Publish the wwwroot folder ContentPath = Path.Combine(homePath, "site", "wwwroot"); PublishSettingsPath = Path.Combine(homePath, "data", "SiteReplicator"); } else { // Local case: run from App_Data for testing purpose string appData = HostingEnvironment.MapPath("~/App_Data"); ContentPath = Path.Combine(appData, "source"); PublishSettingsPath = Path.Combine(appData, "PublishSettingsFiles"); } Directory.CreateDirectory(ContentPath); Directory.CreateDirectory(PublishSettingsPath); } // Path to the web content we want to replicate public string ContentPath { get; set; } // Path to the publish settings files that drive where we publish to public string PublishSettingsPath { get; set; } } }
apache-2.0
C#
3601a9825ae70abcf1cc6cc345c65dab2fd9db27
Make sure to expand out exceptions.
wasabii/Cogito,wasabii/Cogito
Cogito.Core/ExceptionExtensions.cs
Cogito.Core/ExceptionExtensions.cs
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace Cogito { public static class ExceptionExtensions { /// <summary> /// Traces the exception to the default trace source as an error. /// </summary> /// <param name="self"></param> public static void Trace(this Exception self) { Contract.Requires<ArgumentNullException>(self != null); System.Diagnostics.Trace.TraceError("{0:HH:mm:ss.fff} {1} {2}", DateTime.Now, self.GetType().FullName, self); } /// <summary> /// Unpacks any InnerExceptions hidden by <see cref="AggregateException"/>. /// </summary> /// <param name="e"></param> /// <returns></returns> public static IEnumerable<Exception> Expand(this Exception e) { var ae = e as AggregateException; if (ae != null) foreach (var aee in Expand(ae)) yield return aee; else yield return e; } } }
using System; using System.Diagnostics.Contracts; namespace Cogito { public static class ExceptionExtensions { /// <summary> /// Traces the exception to the default trace source as an error. /// </summary> /// <param name="self"></param> public static void Trace(this Exception self) { Contract.Requires<ArgumentNullException>(self != null); System.Diagnostics.Trace.TraceError("{0:HH:mm:ss.fff} {1} {2}", DateTime.Now, self.GetType().FullName, self); } } }
mit
C#
036be86ba0114d9185a91a1eefd985bbd8532eb5
Update server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
4af1f3fe52ec41224bd10de912344c98870134fc
修复单元测试升级CO2NET之后的代码
JeffreySu/WxOpen,JeffreySu/WxOpen
src/Senparc.Weixin.WxOpen.Tests/Containers/SessionContainerTests.cs
src/Senparc.Weixin.WxOpen.Tests/Containers/SessionContainerTests.cs
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 using Microsoft.VisualStudio.TestTools.UnitTesting; using Senparc.Weixin.WxOpen.Containers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Senparc.Weixin.MP.Test.CommonAPIs; namespace Senparc.Weixin.WxOpen.Containers.Tests { [TestClass()] public class SessionContainerTests:CommonApiTest { [TestMethod()] public void UpdateSessionTest() { var openId = "openid"; var sessionKey = "sessionKey"; var unionId = "unionId"; var bag = SessionContainer.UpdateSession(null, openId, sessionKey, unionId); Console.WriteLine("bag.Key:{0}",bag.Key); Console.WriteLine("bag.ExpireTime:{0}",bag.ExpireTime); var key = bag.Key; Thread.Sleep(1000); var bag2 = SessionContainer.GetSession(key); Assert.IsNotNull(bag2); Console.WriteLine("bag2.ExpireTime:{0}", bag2.ExpireTime); } } }
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 using Microsoft.VisualStudio.TestTools.UnitTesting; using Senparc.Weixin.WxOpen.Containers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Senparc.Weixin.MP.Test.CommonAPIs; namespace Senparc.Weixin.WxOpen.Containers.Tests { [TestClass()] public class SessionContainerTests:CommonApiTest { [TestMethod()] public void UpdateSessionTest() { var openId = "openid"; var sessionKey = "sessionKey"; var bag = SessionContainer.UpdateSession(null, openId, sessionKey); Console.WriteLine("bag.Key:{0}",bag.Key); Console.WriteLine("bag.ExpireTime:{0}",bag.ExpireTime); var key = bag.Key; Thread.Sleep(1000); var bag2 = SessionContainer.GetSession(key); Assert.IsNotNull(bag2); Console.WriteLine("bag2.ExpireTime:{0}", bag2.ExpireTime); } } }
apache-2.0
C#
07b8cfc15783b802d6dc8e2931f4fbac9d20550c
Make the two extra ByRef value-type equality comparer methods static
NickStrupat/Equality
Equality/StructEqualityComparer.cs
Equality/StructEqualityComparer.cs
using System; using System.Collections.Generic; namespace Equality { public struct StructEqualityComparer<T> : IEqualityComparer<T> where T : struct { public static StructEqualityComparer<T> Default = new StructEqualityComparer<T>(); public Boolean Equals(T x, T y) => Struct.Equals(ref x, ref y); public Int32 GetHashCode(T x) => Struct.GetHashCode(ref x); public static Boolean Equals(ref T x, ref T y) => Struct.Equals(ref x, ref y); public static Int32 GetHashCode(ref T x) => Struct.GetHashCode(ref x); } }
using System; using System.Collections.Generic; namespace Equality { public struct StructEqualityComparer<T> : IEqualityComparer<T> where T : struct { public static StructEqualityComparer<T> Default = new StructEqualityComparer<T>(); public Boolean Equals(T x, T y) => Struct.Equals(ref x, ref y); public Int32 GetHashCode(T x) => Struct.GetHashCode(ref x); public Boolean Equals(ref T x, ref T y) => Struct.Equals(ref x, ref y); public Int32 GetHashCode(ref T x) => Struct.GetHashCode(ref x); } }
mit
C#
05251a5e38f779e6467091cae97f658599280756
remove empty overrides
MichaelRumpler/GestureSample
GestureSample/GestureSample/App.cs
GestureSample/GestureSample/App.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GestureSample.Views; using Xamarin.Forms; namespace GestureSample { public class App : Application { public static NavigationPage MainNavigation; public App() { var samplePages = new[] { "ContentPage", "Layouts", "Views", "Cells", "AppCompat", "Tests", }; var mainPage = new MainPage() { Title = "Control Categories", BindingContext = samplePages }; MainPage = MainNavigation = new NavigationPage(mainPage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GestureSample.Views; using Xamarin.Forms; namespace GestureSample { public class App : Application { public static NavigationPage MainNavigation; public App() { var samplePages = new[] { "ContentPage", "Layouts", "Views", "Cells", "AppCompat", "Tests", }; var mainPage = new MainPage() { Title = "Control Categories", BindingContext = samplePages }; MainPage = MainNavigation = new NavigationPage(mainPage); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
mit
C#
8978fc81989c50c90ba0d46ef9ad204ad4f97940
Add inspect-able value
dasMulli/dotnet-win32-service
src/DasMulli.Win32.ServiceUtils/ServiceFailureActionsFlag.cs
src/DasMulli.Win32.ServiceUtils/ServiceFailureActionsFlag.cs
using System.Runtime.InteropServices; namespace DasMulli.Win32.ServiceUtils { [StructLayout(LayoutKind.Sequential)] internal struct ServiceFailureActionsFlag { private bool _fFailureActionsOnNonCrashFailures; /// <summary> /// Initializes a new instance of the <see cref="ServiceFailureActionsFlag"/> struct. /// </summary> public ServiceFailureActionsFlag(bool enabled) { _fFailureActionsOnNonCrashFailures = enabled; } public bool Flag { get => _fFailureActionsOnNonCrashFailures; set => _fFailureActionsOnNonCrashFailures = value; } } }
using System.Runtime.InteropServices; namespace DasMulli.Win32.ServiceUtils { [StructLayout(LayoutKind.Sequential)] internal struct ServiceFailureActionsFlag { private bool _fFailureActionsOnNonCrashFailures; /// <summary> /// Initializes a new instance of the <see cref="ServiceFailureActionsFlag"/> struct. /// </summary> internal ServiceFailureActionsFlag(bool enabled) { _fFailureActionsOnNonCrashFailures = enabled; } } }
mit
C#
4f460c866672f418fbeed53bc092736236662978
update assembly information and version number
heupel/hyperjs,quameleon/hyperjs
HyperJS/Properties/AssemblyInfo.cs
HyperJS/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HyperJS")] [assembly: AssemblyDescription("An attempt to create JavaScript in C# without writing a whole new language.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tony Heupel")] [assembly: AssemblyProduct("HyperJS")] [assembly: AssemblyCopyright("Copyright © Tony Heupel 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bcd13864-aa70-4d5f-bf03-59e3f47aeb0a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("JSObject")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("JSObject")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bcd13864-aa70-4d5f-bf03-59e3f47aeb0a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
52c7ed99607028bef24a0f13073638866e09931f
Add ability to change the flie extension of API download requests
2yangk23/osu,NeoAdonis/osu,johnneijzen/osu,EVAST9919/osu,ZLima12/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu
osu.Game/Online/API/APIDownloadRequest.cs
osu.Game/Online/API/APIDownloadRequest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.IO.Network; namespace osu.Game.Online.API { public abstract class APIDownloadRequest : APIRequest { private string filename; /// <summary> /// Sets the extension of the file outputted by this request. /// </summary> protected virtual string FileExtension { get; } = @".tmp"; protected override WebRequest CreateWebRequest() { var file = Path.GetTempFileName(); File.Move(file, filename = Path.ChangeExtension(file, FileExtension)); var request = new FileWebRequest(filename, Uri); request.DownloadProgress += request_Progress; return request; } private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total)); protected APIDownloadRequest() { base.Success += onSuccess; } private void onSuccess() { Success?.Invoke(filename); } public event APIProgressHandler Progressed; public new event APISuccessHandler<string> Success; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.IO.Network; namespace osu.Game.Online.API { public abstract class APIDownloadRequest : APIRequest { private string filename; protected override WebRequest CreateWebRequest() { var request = new FileWebRequest(filename = Path.GetTempFileName(), Uri); request.DownloadProgress += request_Progress; return request; } private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total)); protected APIDownloadRequest() { base.Success += onSuccess; } private void onSuccess() { Success?.Invoke(filename); } public event APIProgressHandler Progressed; public new event APISuccessHandler<string> Success; } }
mit
C#
8322a7ed6a2797bc8c537ed3cefb2e78ada1a963
Improve reliability of test by using semaphores
ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
osu.Framework.Tests/Audio/AudioCollectionManagerTest.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.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new TestAudioCollectionManager(); var threadExecutionFinished = new ManualResetEventSlim(); var updateLoopStarted = new ManualResetEventSlim(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a separate thread start processing the queue var thread = new Thread(() => { while (!manager.IsDisposed) { manager.Update(); updateLoopStarted.Set(); } threadExecutionFinished.Set(); }); thread.Start(); Assert.IsTrue(updateLoopStarted.Wait(1000)); Assert.DoesNotThrow(() => manager.Dispose()); Assert.IsTrue(threadExecutionFinished.Wait(1000)); } private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent> { public new bool IsDisposed => base.IsDisposed; } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
// 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.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
mit
C#
44d8f5a19fc7eeb3cd8e185eb06967491a7a2eb3
Fix XOR OTP used twice #93
DanGould/NTumbleBit,NTumbleBit/NTumbleBit
NTumbleBit/PuzzlePromise/XORKey.cs
NTumbleBit/PuzzlePromise/XORKey.cs
using NBitcoin; using NTumbleBit.BouncyCastle.Crypto.Digests; using NTumbleBit.BouncyCastle.Crypto.Generators; using NTumbleBit.BouncyCastle.Crypto.Parameters; using NTumbleBit.BouncyCastle.Math; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NTumbleBit.PuzzlePromise { public class XORKey { public XORKey(PuzzleSolution puzzleSolution) : this(puzzleSolution._Value) { } public XORKey(RsaPubKey pubKey) : this(Utils.GenerateEncryptableInteger(pubKey._Key)) { } public XORKey(byte[] key) { if(key == null) throw new ArgumentNullException(nameof(key)); if(key.Length != KeySize) throw new ArgumentException("Key has invalid length from expected " + KeySize); _Value = new BigInteger(1, key); } private XORKey(BigInteger value) { if(value == null) throw new ArgumentNullException(nameof(value)); _Value = value; } private BigInteger _Value; public byte[] XOR(byte[] data) { byte[] keyBytes = ToBytes(); Sha512Digest sha512 = new Sha512Digest(); var generator = new Mgf1BytesGenerator(sha512); generator.Init(new MgfParameters(keyBytes)); var keyHash = new byte[data.Length]; generator.GenerateBytes(keyHash, 0, keyHash.Length); var encrypted = new byte[data.Length]; for(int i = 0; i < encrypted.Length; i++) { encrypted[i] = (byte)(data[i] ^ keyHash[i]); } return encrypted; } private const int KeySize = 256; public byte[] ToBytes() { byte[] keyBytes = _Value.ToByteArrayUnsigned(); Utils.Pad(ref keyBytes, KeySize); return keyBytes; } } }
using NBitcoin; using NTumbleBit.BouncyCastle.Math; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NTumbleBit.PuzzlePromise { public class XORKey { public XORKey(PuzzleSolution puzzleSolution) : this(puzzleSolution._Value) { } public XORKey(RsaPubKey pubKey) : this(Utils.GenerateEncryptableInteger(pubKey._Key)) { } public XORKey(byte[] key) { if(key == null) throw new ArgumentNullException(nameof(key)); if(key.Length != KeySize) throw new ArgumentException("Key has invalid length from expected " + KeySize); _Value = new BigInteger(1, key); } private XORKey(BigInteger value) { if(value == null) throw new ArgumentNullException(nameof(value)); _Value = value; } private BigInteger _Value; public byte[] XOR(byte[] data) { byte[] keyBytes = ToBytes(); var keyHash = PromiseUtils.SHA512(keyBytes, 0, keyBytes.Length); var encrypted = new byte[data.Length]; for(int i = 0; i < encrypted.Length; i++) { encrypted[i] = (byte)(data[i] ^ keyHash[i % keyHash.Length]); } return encrypted; } private const int KeySize = 256; public byte[] ToBytes() { byte[] keyBytes = _Value.ToByteArrayUnsigned(); Utils.Pad(ref keyBytes, KeySize); return keyBytes; } } }
mit
C#
874352afc7df2598cf767436a43078ab98fc8980
Update SmsController.cs
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
quickstart/csharp/sms/receive-sms-core/SmsController.cs
quickstart/csharp/sms/receive-sms-core/SmsController.cs
// Code sample for ASP.NET Core on .NET Core // From command prompt, run: // dotnet add package Twilio.AspNet.Core using Twilio.AspNet.Common; using Twilio.AspNet.Core; using Twilio.TwiML; namespace TwilioReceive.Controllers { public class SmsController : TwilioController { public TwiMLResult Index(SmsRequest incomingMessage) { var messagingResponse = new MessagingResponse(); messagingResponse.Message("The copy cat says: " + incomingMessage.Body); return TwiML(messagingResponse); } } }
// Code sample for ASP.NET Core on .NET Core // From command prompt, run: // dotnet add package Twilio.AspNet.Core using Twilio.AspNet.Common; using Twilio.AspNet.Core; using Twilio.TwiML; namespace YourNewWebProject.Controllers { public class SmsController : TwilioController { public TwiMLResult Index(SmsRequest incomingMessage) { var messagingResponse = new MessagingResponse(); messagingResponse.Message("The copy cat says: " + incomingMessage.Body); return TwiML(messagingResponse); } } }
mit
C#
05481f8443027b87ccc77b1ffa4680f1394b6993
Add missing copyright header to CustomEffect.cs
Microsoft/real-time-filter-demo
RealtimeFilterDemo/CustomEffect.cs
RealtimeFilterDemo/CustomEffect.cs
/* * Copyright © 2013 Nokia Corporation. All rights reserved. * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. * Other product and company names mentioned herein may be trademarks * or trade names of their respective owners. * See LICENSE.TXT for license information. */ using Nokia.Graphics.Imaging; namespace RealtimeFilterDemo { public class CustomEffect : CustomEffectBase { public CustomEffect(IImageProvider source) : base(source) { } protected override void OnProcess(PixelRegion sourcePixelRegion, PixelRegion targetPixelRegion) { var sourcePixels = sourcePixelRegion.ImagePixels; var targetPixels = targetPixelRegion.ImagePixels; sourcePixelRegion.ForEachRow((index, width, position) => { for (int x = 0; x < width; ++x, ++index) { // the only supported color format is ColorFormat.Bgra8888 uint pixel = sourcePixels[index]; uint blue = pixel & 0x000000ff; // blue color component uint green = (pixel & 0x0000ff00) >> 8; // green color component uint red = (pixel & 0x00ff0000) >> 16; // red color component uint average = (uint)(0.0722 * blue + 0.7152 * green + 0.2126 * red); // weighted average component uint grayscale = 0xff000000 | average | (average << 8) | (average << 16); // use average for each color component targetPixels[index] = ~grayscale; // use inverse grayscale } }); } } }
using Nokia.Graphics.Imaging; namespace RealtimeFilterDemo { public class CustomEffect : CustomEffectBase { public CustomEffect(IImageProvider source) : base(source) { } protected override void OnProcess(PixelRegion sourcePixelRegion, PixelRegion targetPixelRegion) { var sourcePixels = sourcePixelRegion.ImagePixels; var targetPixels = targetPixelRegion.ImagePixels; sourcePixelRegion.ForEachRow((index, width, position) => { for (int x = 0; x < width; ++x, ++index) { // the only supported color format is ColorFormat.Bgra8888 uint pixel = sourcePixels[index]; uint blue = pixel & 0x000000ff; // blue color component uint green = (pixel & 0x0000ff00) >> 8; // green color component uint red = (pixel & 0x00ff0000) >> 16; // red color component uint average = (uint)(0.0722 * blue + 0.7152 * green + 0.2126 * red); // weighted average component uint grayscale = 0xff000000 | average | (average << 8) | (average << 16); // use average for each color component targetPixels[index] = ~grayscale; // use inverse grayscale } }); } } }
mit
C#
68b7d739658bb1e8097901b249730fd1dbc58d3d
Fix phone number storage
Branimir123/FMI-IoT-Teamwork,Branimir123/FMI-IoT-Teamwork
SmartHive/SmartHive.Models/User.cs
SmartHive/SmartHive.Models/User.cs
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace SmartHive.Models { public class User : IdentityUser { private ICollection<Hive> Hives; public User() : base(string.Empty) { this.HiveCollection = new HashSet<Hive>(); } public User(string username, string email, string name, string description, string phoneNumber) { this.UserName = username; this.Email = email; this.Name = name; this.Description = description; this.PhoneNumber = phoneNumber; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<Hive> HiveCollection { get { return this.Hives; } set { this.Hives = value; } } public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { return manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); } } }
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace SmartHive.Models { public class User : IdentityUser { private ICollection<Hive> Hives; public User() : base(string.Empty) { this.HiveCollection = new HashSet<Hive>(); } public User(string username, string email, string name, string description) { this.UserName = username; this.Email = email; this.Name = name; this.Description = description; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<Hive> HiveCollection { get { return this.Hives; } set { this.Hives = value; } } public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { return manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); } } }
mit
C#
84e2d820d7faad4b8a950e9adcc9f76d02245d6e
Remove Assembly mapped Content.
tainicom/Aether
Source/MonoGame/AetherContextMG.cs
Source/MonoGame/AetherContextMG.cs
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using tainicom.Aether.Engine; using System.IO; using System.Reflection; using System; using System.Collections.Generic; namespace tainicom.Aether.MonoGame { public class AetherContextMG: AetherContext { private GraphicsDevice _graphicsDevice; private ContentManager _contentManager; public GraphicsDevice Device { get { return _graphicsDevice; } } public ContentManager Content { get { return _contentManager; } } public AetherContextMG(GraphicsDevice graphicsDevice, ContentManager content):base() { this._graphicsDevice = graphicsDevice; this._contentManager = content; } protected override void OnDispose(bool disposing) { if (disposing) { _contentManager.Dispose(); _graphicsDevice.Dispose(); } this._graphicsDevice = null; this._contentManager = null; return; } public static GraphicsDevice GetDevice(AetherEngine engine) { return ((AetherContextMG)engine.Context).Device; } public static ContentManager GetContent(AetherEngine engine) { return ((AetherContextMG)engine.Context).Content; } } }
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using tainicom.Aether.Engine; using System.IO; using System.Reflection; using System; using System.Collections.Generic; namespace tainicom.Aether.MonoGame { public class AetherContextMG: AetherContext { private GraphicsDevice _graphicsDevice; private ContentManager _contentManager; private Dictionary<Assembly, ContentManager> _contentMgrs; public GraphicsDevice Device { get { return _graphicsDevice; } } public ContentManager Content { get { return _contentManager; } } public AetherContextMG(GraphicsDevice graphicsDevice, ContentManager content):base() { this._graphicsDevice = graphicsDevice; this._contentManager = content; this._contentMgrs = new Dictionary<Assembly, ContentManager>(); } protected override void OnDispose(bool disposing) { if (disposing) { _contentManager.Dispose(); _graphicsDevice.Dispose(); foreach (var contentMgr in _contentMgrs.Values) contentMgr.Dispose(); } this._graphicsDevice = null; this._contentManager = null; this._contentMgrs = null; return; } #if WINDOWS public ContentManager GetContent(Assembly library) { ContentManager result; _contentMgrs.TryGetValue(library, out result); if (result == null) { //cache lib contentManagers string hstLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\"; string asmLocation = Path.GetDirectoryName(library.Location) + "\\"; String relModuleLocation = new Uri(hstLocation).MakeRelativeUri(new Uri(asmLocation)).ToString(); String rootDirectory = relModuleLocation + "/Content"; result = new ContentManager(Content.ServiceProvider, rootDirectory); _contentMgrs.Add(library, result); } else return result; return result; } #endif public static GraphicsDevice GetDevice(AetherEngine engine) { return ((AetherContextMG)engine.Context).Device; } public static ContentManager GetContent(AetherEngine engine) { return ((AetherContextMG)engine.Context).Content; } } }
apache-2.0
C#
fba9428efb8627ae077889b2f170e232b0bdba47
Make node root path variable and add debugger display
Krusen/Additio.Sitecore.DependencyConfigReader
src/Additio.Configuration/Node.cs
src/Additio.Configuration/Node.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace Additio.Configuration { [DebuggerDisplay("{RelativePath}")] public class Node { private string Root { get; } public Node(string root) { if (!root.EndsWith("\\")) root += "\\"; Root = root; } public string FilePath { get; set; } public string RelativePath => FilePath.Replace(Root, ""); public List<Node> Dependencies { get; } = new List<Node>(); } }
using System; using System.Collections.Generic; namespace Additio.Configuration { public class Node { public const string IncludeFolderPath = @"App_Config\Include"; public string FilePath { get; set; } public string RelativePath => FilePath.Remove(0, FilePath.IndexOf(IncludeFolderPath, StringComparison.OrdinalIgnoreCase) + 19); public List<Node> Dependencies { get; } = new List<Node>(); } }
unlicense
C#
9d4a212c2d424eb7903c45c238bc53b33e395b33
Remove extraneous code
mstrother/BmpListener
src/BmpListener/Bgp/Capability.cs
src/BmpListener/Bgp/Capability.cs
using System; namespace BmpListener.Bgp { public abstract class Capability { protected Capability(byte[] data, int offset) { CapabilityType = (CapabilityCode)data[offset]; CapabilityLength = data[offset + 1]; } public CapabilityCode CapabilityType { get; } public int CapabilityLength { get; } public static Capability GetCapability(byte[] data, int offset) { switch ((CapabilityCode)data[offset]) { case CapabilityCode.Multiprotocol: return new CapabilityMultiProtocol(data, offset); case CapabilityCode.RouteRefresh: return new CapabilityRouteRefresh(data, offset); case CapabilityCode.GracefulRestart: return new CapabilityGracefulRestart(data, offset); case CapabilityCode.FourOctetAs: return new CapabilityFourOctetAsNumber(data, offset); case CapabilityCode.AddPath: return new CapabilityAddPath(data, offset); case CapabilityCode.EnhancedRouteRefresh: return new CapabilityEnhancedRouteRefresh(data, offset); case CapabilityCode.CiscoRouteRefresh: return new CapabilityCiscoRouteRefresh(data, offset); default: return null; } } } }
using System; namespace BmpListener.Bgp { public abstract class Capability { protected Capability(byte[] data, int offset) { CapabilityType = (CapabilityCode)data[offset]; CapabilityLength = data[offset + 1]; } public CapabilityCode CapabilityType { get; } public int CapabilityLength { get; } public static Capability GetCapability(byte[] data, int offset) { var capabilityType = (CapabilityCode)data[offset]; switch (capabilityType) { case CapabilityCode.Multiprotocol: return new CapabilityMultiProtocol(data, offset); case CapabilityCode.RouteRefresh: return new CapabilityRouteRefresh(data, offset); case CapabilityCode.GracefulRestart: return new CapabilityGracefulRestart(data, offset); case CapabilityCode.FourOctetAs: return new CapabilityFourOctetAsNumber(data, offset); case CapabilityCode.AddPath: return new CapabilityAddPath(data, offset); case CapabilityCode.EnhancedRouteRefresh: return new CapabilityEnhancedRouteRefresh(data, offset); case CapabilityCode.CiscoRouteRefresh: return new CapabilityCiscoRouteRefresh(data, offset); default: return null; } } } }
mit
C#
20e98da7b2bfa5af0c7245675dc4fe6049b74052
Update XShapes.cs
Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Collections/XShapes.cs
src/Core2D/Collections/XShapes.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Immutable; using Core2D.Attributes; using Core2D.Shape; namespace Core2D.Collections { /// <summary> /// Observable <see cref="BaseShape"/> collection. /// </summary> public class XShapes : ObservableResource { /// <summary> /// Gets or sets resource name. /// </summary> [Name] public string Name { get; set; } /// <summary> /// Gets or sets children collection. /// </summary> [Content] public ImmutableArray<BaseShape> Children { get; set; } /// <summary> /// Initializes a new instance of the <see cref="XShapes"/> class. /// </summary> public XShapes() { Children = ImmutableArray.Create<BaseShape>(); } /// <summary> /// Check whether the <see cref="Name"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeName() => !String.IsNullOrWhiteSpace(Name); /// <summary> /// Check whether the <see cref="Children"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeChildren() => Children.IsEmpty == false; } }
// 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.Collections.Immutable; using Core2D.Attributes; using Core2D.Shape; namespace Core2D.Collections { /// <summary> /// Observable <see cref="BaseShape"/> collection. /// </summary> public class XShapes : ObservableResource { /// <summary> /// Gets or sets resource name. /// </summary> [Name] public string Name { get; set; } /// <summary> /// Gets or sets children collection. /// </summary> [Content] public ImmutableArray<BaseShape> Children { get; set; } /// <summary> /// Initializes a new instance of the <see cref="XShapes"/> class. /// </summary> public XShapes() { Children = ImmutableArray.Create<BaseShape>(); } } }
mit
C#
973edba0f93eeefc17b100bc377d45023bacc998
Add a few helpers for MonoMac on the desktop to ExportAttribute
mono/maccore,cwensley/maccore,jorik041/maccore,beni55/maccore
src/Foundation/ExportAttribute.cs
src/Foundation/ExportAttribute.cs
// // ExportAttribetu.cs: The Export attribetu // // Authors: // Geoff Norton // // Copyright 2009, Novell, Inc. // Copyright 2010, Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Reflection; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ExportAttribute : Attribute { string selector; ArgumentSemantic semantic; public ExportAttribute() {} public ExportAttribute(string selector) { this.selector = selector; this.semantic = ArgumentSemantic.None; } public ExportAttribute(string selector, ArgumentSemantic semantic) { this.selector = selector; this.semantic = semantic; } public string Selector { get { return this.selector; } set { this.selector = value; } } public ArgumentSemantic ArgumentSemantic { get { return this.semantic; } set { this.semantic = value; } } #if MONOMAC public ExportAttribute ToGetter (PropertyInfo prop) { if (string.IsNullOrEmpty (Selector)) Selector = prop.Name; return new ExportAttribute (selector, semantic); } public ExportAttribute ToSetter (PropertyInfo prop) { if (string.IsNullOrEmpty (Selector)) Selector = prop.Name; return new ExportAttribute (string.Format ("set{0}{1}:", char.ToUpper (selector [0]), selector.Substring (1)), semantic); } #endif } }
// // ExportAttribetu.cs: The Export attribetu // // Authors: // Geoff Norton // // Copyright 2009, Novell, Inc. // Copyright 2010, Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { [AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ExportAttribute : Attribute { string selector; ArgumentSemantic semantic; public ExportAttribute() {} public ExportAttribute(string selector) { this.selector = selector; this.semantic = ArgumentSemantic.None; } public ExportAttribute(string selector, ArgumentSemantic semantic) { this.selector = selector; this.semantic = semantic; } public string Selector { get { return this.selector; } set { this.selector = value; } } public ArgumentSemantic ArgumentSemantic { get { return this.semantic; } set { this.semantic = value; } } } }
apache-2.0
C#
e3bdaafd46bf53d3cd9339a0abbc74a49c4d5288
Replace SerialPort construction with factory invocation
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
SupportManager.Control/ATHelper.cs
SupportManager.Control/ATHelper.cs
using System; using System.IO.Ports; using MYCroes.ATCommands; using MYCroes.ATCommands.Forwarding; namespace SupportManager.Control { public class ATHelper : IDisposable { private readonly SerialPort serialPort; public ATHelper(string portConnectionString) { serialPort = SerialPortFactory.CreateFromConnectionString(portConnectionString); serialPort.Open(); } public ATHelper(SerialPort port) { serialPort = port; port.Open(); } public void ForwardTo(string phoneNumberWithInternationalAccessCode) { var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration, phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode, ForwardingClass.Voice); Execute(cmd); } public string GetForwardedPhoneNumber() { var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional); var res = Execute(cmd); return ForwardingStatus.Parse(res[0]).Number; } private string[] Execute(ATCommand command) { var stream = serialPort.BaseStream; stream.ReadTimeout = 10000; stream.WriteTimeout = 10000; return command.Execute(stream); } public void Dispose() { if (serialPort.IsOpen) serialPort.Close(); serialPort.Dispose(); } } }
using System; using System.IO.Ports; using MYCroes.ATCommands; using MYCroes.ATCommands.Forwarding; namespace SupportManager.Control { public class ATHelper : IDisposable { private readonly SerialPort serialPort; public ATHelper(string port) { serialPort = new SerialPort(port); serialPort.Open(); } public void ForwardTo(string phoneNumberWithInternationalAccessCode) { var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration, phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode, ForwardingClass.Voice); Execute(cmd); } public string GetForwardedPhoneNumber() { var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional); var res = Execute(cmd); return ForwardingStatus.Parse(res[0]).Number; } private string[] Execute(ATCommand command) { var stream = serialPort.BaseStream; stream.ReadTimeout = 10000; stream.WriteTimeout = 10000; return command.Execute(stream); } public void Dispose() { if (serialPort.IsOpen) serialPort.Close(); serialPort.Dispose(); } } }
mit
C#
da30931d9e6e5aa8f18fc90da1f9ea7ec58dc1e7
include total record count
Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore
src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs
src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs
namespace JsonApiDotNetCore.Configuration { public class JsonApiOptions { public string Namespace { get; set; } public int DefaultPageSize { get; set; } public bool IncludeTotalRecordCount { get; set; } } }
namespace JsonApiDotNetCore.Configuration { public class JsonApiOptions { public string Namespace { get; set; } public int DefaultPageSize { get; set; } } }
mit
C#
636d1dfe1c2124a1d6cc87bdba51f23c045f84df
Throw exception when USB device not found
huysentruitw/win-beacon
src/WinBeacon.Stack/Transports/LibUsb/LibUsbDevice.cs
src/WinBeacon.Stack/Transports/LibUsb/LibUsbDevice.cs
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using LibUsbDotNet; using LibUsbDotNet.Info; using LibUsbDotNet.Main; namespace WinBeacon.Stack.Transports.LibUsb { /// <summary> /// LibUsbDotNet.UsbDevice wrapper that implements ILibUsbDevice. /// </summary> internal class LibUsbDevice : ILibUsbDevice { private UsbDevice usbDevice; public int Vid { get; private set; } public int Pid { get; private set; } public LibUsbDevice(int vid, int pid) { Vid = vid; Pid = pid; } public void Open() { if (usbDevice != null) return; usbDevice = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(Vid, Pid)); if (usbDevice == null) throw new WinBeaconException("USB device not found, check VID & PID"); } public void Close() { if (usbDevice == null) return; usbDevice.Close(); usbDevice = null; } public IEnumerable<UsbConfigInfo> Configs { get { return usbDevice.Configs; } } public UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID) { return usbDevice.OpenEndpointReader(readEndpointID); } public UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID) { return usbDevice.OpenEndpointWriter(writeEndpointID); } public bool ControlTransfer(ref UsbSetupPacket setupPacket, object buffer, int bufferLength, out int lengthTransferred) { return usbDevice.ControlTransfer(ref setupPacket, buffer, bufferLength, out lengthTransferred); } } }
/* * Copyright 2015 Huysentruit Wouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using LibUsbDotNet; using LibUsbDotNet.Info; using LibUsbDotNet.Main; namespace WinBeacon.Stack.Transports.LibUsb { /// <summary> /// LibUsbDotNet.UsbDevice wrapper that implements ILibUsbDevice. /// </summary> internal class LibUsbDevice : ILibUsbDevice { private UsbDevice usbDevice; public int Vid { get; private set; } public int Pid { get; private set; } public LibUsbDevice(int vid, int pid) { Vid = vid; Pid = pid; } public void Open() { if (usbDevice != null) return; usbDevice = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(Vid, Pid)); } public void Close() { if (usbDevice == null) return; usbDevice.Close(); usbDevice = null; } public IEnumerable<UsbConfigInfo> Configs { get { return usbDevice.Configs; } } public UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID) { return usbDevice.OpenEndpointReader(readEndpointID); } public UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID) { return usbDevice.OpenEndpointWriter(writeEndpointID); } public bool ControlTransfer(ref UsbSetupPacket setupPacket, object buffer, int bufferLength, out int lengthTransferred) { return usbDevice.ControlTransfer(ref setupPacket, buffer, bufferLength, out lengthTransferred); } } }
mit
C#
44bd2f92bba1cacb3fb7abade75379a22756654b
fix typo for activity attribute.
kenakamu/UCWA2.0-CS
UCWASDK/UCWASDK/Models/Presence.cs
UCWASDK/UCWASDK/Models/Presence.cs
using Microsoft.Skype.UCWA.Enums; using Microsoft.Skype.UCWA.Services; using Newtonsoft.Json; using System.Threading.Tasks; namespace Microsoft.Skype.UCWA.Models { /// <summary> /// Represents the user's availability and activity. /// presence is updated when the user's availability or activity changes.The user can express her willingness to communicate by manually changing her presence. /// </summary> public class Presence : UCWAModelBaseLink { [JsonProperty("activity")] public string Acitvity { get; set; } [JsonProperty("availability")] public Availability Availability { get; set; } public async Task Update() { await HttpService.Post(Self, this); } } }
using Microsoft.Skype.UCWA.Enums; using Microsoft.Skype.UCWA.Services; using Newtonsoft.Json; using System.Threading.Tasks; namespace Microsoft.Skype.UCWA.Models { /// <summary> /// Represents the user's availability and activity. /// presence is updated when the user's availability or activity changes.The user can express her willingness to communicate by manually changing her presence. /// </summary> public class Presence : UCWAModelBaseLink { [JsonProperty("acitvity")] public string Acitvity { get; set; } [JsonProperty("availability")] public Availability Availability { get; set; } public async Task Update() { await HttpService.Post(Self, this); } } }
mit
C#
0adea1b77bc0aa992d66023de7d586aa917e49aa
Update regex to account for Windows and *nix style line breads ( CR/LF and LF )
rdennis/cassette.mapfile,rdennis/cassette.mapfile,rdennis/cassette.mapfile,rdennis/cassette.mapfile
src/Albatross.Cassette.MapFile/MapFileRewriter.cs
src/Albatross.Cassette.MapFile/MapFileRewriter.cs
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Cassette; namespace Albatross.Cassette.MapFile { public class MapFileRewriter : IMapFileRewriter { private static readonly Regex sourceMapReplacement = new Regex(@"^(/[/|\*]# sourceMappingURL=)(.+\.map)\s*?(\*/)?\r?$", RegexOptions.IgnoreCase | RegexOptions.Multiline); private readonly CassetteSettings settings; public MapFileRewriter(CassetteSettings settings) { this.settings = settings; } public CompileResult Compile(string source, CompileContext context) { if(this.settings != null && !this.settings.IsDebuggingEnabled) { return new CompileResult(source, Enumerable.Empty<string>()); } var relativePath = this.GetRawDirectoryRelativePath(context.SourceFilePath); var result = sourceMapReplacement.Replace(source, String.Format("$1{0}$2$3", relativePath)); return new CompileResult(result, Enumerable.Empty<string>()); } private string GetRawDirectoryRelativePath(string sourcePath) { sourcePath = sourcePath .Replace('\\', '/') .Replace("~/", "../"); if(sourcePath[0] == '/') { sourcePath = sourcePath.Substring(1); } for(var depth = sourcePath.Count(c => c == '/'); depth > 0; depth--) { sourcePath = sourcePath.Insert(0, "../"); } var directoryPath = Path.GetDirectoryName(sourcePath).Replace('\\', '/'); return string.Format("../file/{0}/", directoryPath); // make RawFileRequestRewriter see this as a raw file } } }
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Cassette; namespace Albatross.Cassette.MapFile { public class MapFileRewriter : IMapFileRewriter { private static readonly Regex sourceMapReplacement = new Regex(@"^(/[/|\*]# sourceMappingURL=)(.+\.map)\s*( \*/)?$", RegexOptions.IgnoreCase | RegexOptions.Multiline); private readonly CassetteSettings settings; public MapFileRewriter(CassetteSettings settings) { this.settings = settings; } public CompileResult Compile(string source, CompileContext context) { if(this.settings != null && !this.settings.IsDebuggingEnabled) { return new CompileResult(source, Enumerable.Empty<string>()); } var relativePath = this.GetRawDirectoryRelativePath(context.SourceFilePath); var result = sourceMapReplacement.Replace(source, String.Format("$1{0}$2$3", relativePath)); return new CompileResult(result, Enumerable.Empty<string>()); } private string GetRawDirectoryRelativePath(string sourcePath) { sourcePath = sourcePath .Replace('\\', '/') .Replace("~/", "../"); if(sourcePath[0] == '/') { sourcePath = sourcePath.Substring(1); } for(var depth = sourcePath.Count(c => c == '/'); depth > 0; depth--) { sourcePath = sourcePath.Insert(0, "../"); } var directoryPath = Path.GetDirectoryName(sourcePath).Replace('\\', '/'); return string.Format("../file/{0}/", directoryPath); // make RawFileRequestRewriter see this as a raw file } } }
mit
C#
e8f0a191bc45fbe7c949338b6227af5f7ed8bece
Fix test
gafter/roslyn,stephentoub/roslyn,robinsedlaczek/roslyn,amcasey/roslyn,AmadeusW/roslyn,pdelvo/roslyn,robinsedlaczek/roslyn,jkotas/roslyn,xasx/roslyn,khyperia/roslyn,mmitche/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,jkotas/roslyn,tvand7093/roslyn,orthoxerox/roslyn,jcouv/roslyn,aelij/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,wvdd007/roslyn,VSadov/roslyn,panopticoncentral/roslyn,mattscheffer/roslyn,reaction1989/roslyn,amcasey/roslyn,shyamnamboodiripad/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Giftednewt/roslyn,mgoertz-msft/roslyn,jcouv/roslyn,paulvanbrenk/roslyn,mgoertz-msft/roslyn,OmarTawfik/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,TyOverby/roslyn,davkean/roslyn,drognanar/roslyn,genlu/roslyn,OmarTawfik/roslyn,aelij/roslyn,CaptainHayashi/roslyn,mavasani/roslyn,pdelvo/roslyn,AnthonyDGreen/roslyn,panopticoncentral/roslyn,tvand7093/roslyn,khyperia/roslyn,mmitche/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,nguerrera/roslyn,physhi/roslyn,kelltrick/roslyn,gafter/roslyn,jmarolf/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,gafter/roslyn,dpoeschl/roslyn,bkoelman/roslyn,yeaicc/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,drognanar/roslyn,tmat/roslyn,diryboy/roslyn,cston/roslyn,orthoxerox/roslyn,mattwar/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,Giftednewt/roslyn,pdelvo/roslyn,dotnet/roslyn,mavasani/roslyn,bartdesmet/roslyn,lorcanmooney/roslyn,heejaechang/roslyn,DustinCampbell/roslyn,amcasey/roslyn,AlekseyTs/roslyn,physhi/roslyn,CaptainHayashi/roslyn,kelltrick/roslyn,mattscheffer/roslyn,stephentoub/roslyn,drognanar/roslyn,bkoelman/roslyn,brettfo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jasonmalinowski/roslyn,brettfo/roslyn,tannergooding/roslyn,tvand7093/roslyn,tmeschter/roslyn,mattscheffer/roslyn,weltkante/roslyn,orthoxerox/roslyn,CyrusNajmabadi/roslyn,yeaicc/roslyn,robinsedlaczek/roslyn,weltkante/roslyn,AlekseyTs/roslyn,mmitche/roslyn,abock/roslyn,heejaechang/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,sharwell/roslyn,OmarTawfik/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,dpoeschl/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,mattwar/roslyn,kelltrick/roslyn,lorcanmooney/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,agocke/roslyn,jcouv/roslyn,Hosch250/roslyn,wvdd007/roslyn,swaroop-sridhar/roslyn,diryboy/roslyn,dpoeschl/roslyn,cston/roslyn,Hosch250/roslyn,davkean/roslyn,jmarolf/roslyn,reaction1989/roslyn,genlu/roslyn,sharwell/roslyn,jamesqo/roslyn,VSadov/roslyn,abock/roslyn,eriawan/roslyn,yeaicc/roslyn,xasx/roslyn,srivatsn/roslyn,tannergooding/roslyn,jamesqo/roslyn,mattwar/roslyn,swaroop-sridhar/roslyn,paulvanbrenk/roslyn,DustinCampbell/roslyn,lorcanmooney/roslyn,AmadeusW/roslyn,MattWindsor91/roslyn,agocke/roslyn,cston/roslyn,AnthonyDGreen/roslyn,Hosch250/roslyn,VSadov/roslyn,AlekseyTs/roslyn,tmeschter/roslyn,srivatsn/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,aelij/roslyn,bkoelman/roslyn,MattWindsor91/roslyn,AnthonyDGreen/roslyn,tannergooding/roslyn,mavasani/roslyn,genlu/roslyn,TyOverby/roslyn,brettfo/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,KevinRansom/roslyn,jamesqo/roslyn,khyperia/roslyn,weltkante/roslyn,wvdd007/roslyn,KevinRansom/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,tmat/roslyn,physhi/roslyn,nguerrera/roslyn,diryboy/roslyn,TyOverby/roslyn,jmarolf/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,abock/roslyn,eriawan/roslyn,jkotas/roslyn,ErikSchierboom/roslyn,Giftednewt/roslyn,CaptainHayashi/roslyn,KirillOsenkov/roslyn
src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs
src/Compilers/Server/VBCSCompiler/VBCSCompiler.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 Microsoft.CodeAnalysis.CommandLine; using System; using System.Collections.Specialized; using System.Configuration; using System.IO; namespace Microsoft.CodeAnalysis.CompilerServer { internal static class VBCSCompiler { public static int Main(string[] args) { NameValueCollection appSettings; try { appSettings = ConfigurationManager.AppSettings; } catch (Exception ex) { // It is possible for AppSettings to throw when the application or machine configuration // is corrupted. This should not prevent the server from starting, but instead just revert // to the default configuration. appSettings = new NameValueCollection(); CompilerServerLogger.LogException(ex, "Error loading application settings"); } try { var controller = new DesktopBuildServerController(appSettings); return controller.Run(args); } catch (FileNotFoundException e) { // Assume the exception was the result of a missing compiler assembly. LogException(e); } catch (TypeInitializationException e) when (e.InnerException is FileNotFoundException) { // Assume the exception was the result of a missing compiler assembly. LogException((FileNotFoundException)e.InnerException); } return CommonCompiler.Failed; } private static void LogException(FileNotFoundException e) { CompilerServerLogger.LogException(e, "File not found"); } } }
// 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 Microsoft.CodeAnalysis.CommandLine; using System; using System.Collections.Specialized; using System.Configuration; using System.IO; namespace Microsoft.CodeAnalysis.CompilerServer { internal static class VBCSCompiler { public static int Main(string[] args) { NameValueCollection appSettings; try { appSettings = ConfigurationManager.AppSettings; } catch (Exception ex) { // It is possible for AppSettings to throw when the application or machine configuration // is corrupted. This should not prevent the server from starting, but instead just revert // to the default configuration. appSettings = new NameValueCollection(); CompilerServerLogger.LogException(ex, "Error loading application settings"); } try { var controller = new DesktopBuildServerController(appSettings); return controller.Run(args); } catch (TypeInitializationException ex) when (ex.InnerException is FileNotFoundException) { // Assume FileNotFoundException was the result of a missing // compiler assembly. Log the exception and terminate the process. CompilerServerLogger.LogException(ex, "File not found"); return CommonCompiler.Failed; } } } }
mit
C#
f3027a3e4b194123ead21f441c51d21170a2a16b
REVERT of SqlClientBatchingBatcher changes after r4279
nhibernate/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core
src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs
src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs
using System.Data; using System.Text; using NHibernate.AdoNet.Util; namespace NHibernate.AdoNet { /// <summary> /// Summary description for SqlClientBatchingBatcher. /// </summary> internal class SqlClientBatchingBatcher : AbstractBatcher { private int batchSize; private int totalExpectedRowsAffected; private SqlClientSqlCommandSet currentBatch; private StringBuilder currentBatchCommandsLog; public SqlClientBatchingBatcher(ConnectionManager connectionManager, IInterceptor interceptor) : base(connectionManager, interceptor) { batchSize = Factory.Settings.AdoBatchSize; currentBatch = new SqlClientSqlCommandSet(); if (log.IsDebugEnabled) { currentBatchCommandsLog = new StringBuilder(); } } public override int BatchSize { get { return batchSize; } set { batchSize = value; } } public override void AddToBatch(IExpectation expectation) { totalExpectedRowsAffected += expectation.ExpectedRowCount; IDbCommand batchUpdate = CurrentCommand; if (log.IsDebugEnabled) { string lineWithParameters = Factory.Settings.SqlStatementLogger.GetCommandLineWithParameters(batchUpdate); if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) { Factory.Settings.SqlStatementLogger.LogCommand("Adding to batch:", batchUpdate, FormatStyle.Basic); } else { log.Debug("Adding to batch:" + lineWithParameters); } currentBatchCommandsLog.Append("Batch command: ").AppendLine(lineWithParameters); } else { Factory.Settings.SqlStatementLogger.LogCommand(batchUpdate, FormatStyle.Basic); } currentBatch.Append((System.Data.SqlClient.SqlCommand)batchUpdate); if (currentBatch.CountOfCommands >= batchSize) { DoExecuteBatch(batchUpdate); } } protected override void DoExecuteBatch(IDbCommand ps) { log.Debug("Executing batch"); CheckReaders(); Prepare(currentBatch.BatchCommand); if (log.IsDebugEnabled) { if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) Factory.Settings.SqlStatementLogger.LogBatchCommand(currentBatchCommandsLog.ToString()); else log.Debug(currentBatchCommandsLog.ToString()); currentBatchCommandsLog = new StringBuilder(); } int rowsAffected = currentBatch.ExecuteNonQuery(); Expectations.VerifyOutcomeBatched(totalExpectedRowsAffected, rowsAffected); currentBatch.Dispose(); totalExpectedRowsAffected = 0; currentBatch = new SqlClientSqlCommandSet(); } } }
using System.Data; using System.Text; using NHibernate.AdoNet.Util; namespace NHibernate.AdoNet { /// <summary> /// Summary description for SqlClientBatchingBatcher. /// </summary> internal class SqlClientBatchingBatcher : AbstractBatcher { private int batchSize; private int totalExpectedRowsAffected; private SqlClientSqlCommandSet currentBatch; private StringBuilder currentBatchCommandsLog; public SqlClientBatchingBatcher(ConnectionManager connectionManager, IInterceptor interceptor) : base(connectionManager, interceptor) { batchSize = Factory.Settings.AdoBatchSize; currentBatch = new SqlClientSqlCommandSet(); currentBatchCommandsLog = new StringBuilder(); } public override int BatchSize { get { return batchSize; } set { batchSize = value; } } public override void AddToBatch(IExpectation expectation) { totalExpectedRowsAffected += expectation.ExpectedRowCount; IDbCommand batchUpdate = CurrentCommand; if (log.IsDebugEnabled || Factory.Settings.SqlStatementLogger.IsDebugEnabled) { string lineWithParameters = Factory.Settings.SqlStatementLogger.GetCommandLineWithParameters(batchUpdate); currentBatchCommandsLog.Append("Batch command: ").AppendLine(lineWithParameters); if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) { Factory.Settings.SqlStatementLogger.LogCommand("Adding to batch:", batchUpdate, FormatStyle.Basic); } else if (log.IsDebugEnabled) { log.Debug("Adding to batch:" + lineWithParameters); } currentBatch.Append((System.Data.SqlClient.SqlCommand)batchUpdate); } if (currentBatch.CountOfCommands >= batchSize) { DoExecuteBatch(batchUpdate); } } protected override void DoExecuteBatch(IDbCommand ps) { log.Debug("Executing batch"); CheckReaders(); Prepare(currentBatch.BatchCommand); if (log.IsDebugEnabled || Factory.Settings.SqlStatementLogger.IsDebugEnabled) { if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) Factory.Settings.SqlStatementLogger.LogBatchCommand(currentBatchCommandsLog.ToString()); else if (log.IsDebugEnabled) log.Debug(currentBatchCommandsLog.ToString()); currentBatchCommandsLog = new StringBuilder(); } int rowsAffected = currentBatch.ExecuteNonQuery(); Expectations.VerifyOutcomeBatched(totalExpectedRowsAffected, rowsAffected); currentBatch.Dispose(); totalExpectedRowsAffected = 0; currentBatch = new SqlClientSqlCommandSet(); } } }
lgpl-2.1
C#
8840fcc056ebf54ce93707ca3caf43fa1e139f0d
Update Program.cs
nanoframework/nf-Visual-Studio-extension
source/CSharp.BlankApplication/Program.cs
source/CSharp.BlankApplication/Program.cs
using System; using System.Threading; namespace $safeprojectname$ { public class Program { public static void Main() { Thread.Sleep(1000); // Temporary dirty fix to enable correct debugging session // Insert your code below this line // The main() method has to end with this infinite loop. // Do not use the NETMF style : Thread.Sleep(Timeout.Infinite) while (true) { Thread.Sleep(200); } } } }
using System; namespace $safeprojectname$ { public class Program { public static void Main() { // Insert your code below this line // The main() method has to end with this infinite loop. // Do not use the NETMF style : Thread.Sleep(Timeout.Infinite) while (true) { Thread.Sleep(200); } } } }
mit
C#
e0fd6a723b7d17b0f9f97fb33e609f5329c869b9
Update FilterStateVisibilityConverter.cs
paulvanbrenk/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,lukedgr/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,paulvanbrenk/nodejstools,paulvanbrenk/nodejstools,kant2002/nodejstools,kant2002/nodejstools,Microsoft/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,kant2002/nodejstools,lukedgr/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools
Nodejs/Product/Nodejs/NpmUI/FilterStateVisibilityConverter.cs
Nodejs/Product/Nodejs/NpmUI/FilterStateVisibilityConverter.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; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Microsoft.NodejsTools.NpmUI { public sealed class FilterStateVisibilityConverter : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string state && parameter is string expected) { if (targetType == typeof(Visibility)) { return StringComparer.OrdinalIgnoreCase.Equals(state, expected) ? Visibility.Visible : Visibility.Hidden; } if (targetType == typeof(bool)) { return StringComparer.OrdinalIgnoreCase.Equals(state, expected); } } throw new InvalidCastException("Wrong input type."); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
// 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; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Microsoft.NodejsTools.NpmUI { public sealed class FilterStateVisibilityConverter : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string state && parameter is string expected) { if (targetType == typeof(Visibility)) { return StringComparer.OrdinalIgnoreCase.Equals(state, expected) ? Visibility.Visible : Visibility.Hidden; } if(targetType == typeof(bool)) { return StringComparer.OrdinalIgnoreCase.Equals(state, expected); } } throw new InvalidCastException("Wrong input type."); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
apache-2.0
C#
e0d28e06d2ed4654550293cb9b31182364a34985
Put some more complicated xml docs around this.
darrencauthon/AutoMoq,darrencauthon/AutoMoq,darrencauthon/AutoMoq
src/AutoMoq/Helpers/AutoMoqTestFixture.cs
src/AutoMoq/Helpers/AutoMoqTestFixture.cs
using Moq; namespace AutoMoq.Helpers { /// <summary> /// An auto moq base class that you can use to get AutoMoq setup built-in. /// /// [TestFixture] /// public class LoginGetTests : AutoMoqTestFixture<MyClassToTest> /// { /// [SetUp] /// public void Setup() /// { /// ResetSubject(); /// } /// /// [Test] /// public void Test_this() /// { /// Mocked<IFoo>().Verify(x => x.SomethingIsDone()); /// Subject.DoSomething(); /// } /// } /// </summary> /// <typeparam name="T"></typeparam> public class AutoMoqTestFixture<T> where T : class { private T subject; /// <summary> /// The current AutoMoqer /// </summary> public AutoMoqer Mocker { get; private set; } = new AutoMoqer(); /// <summary> /// The Class being tested in this Test Fixture. /// </summary> public T Subject { get { return subject ?? (subject = Mocker.Resolve<T>()); } } /// <summary> /// A Mock dependency that was auto-injected into Subject /// </summary> /// <typeparam name="TMock"></typeparam> /// <returns></returns> public Mock<TMock> Mocked<TMock>() where TMock : class { return Mocker.GetMock<TMock>(); } /// <summary> /// A dependency that was auto-injected into Subject. Implementation is a Moq object. /// </summary> /// <typeparam name="TDepend"></typeparam> /// <returns></returns> public TDepend Dependency<TDepend>() where TDepend : class { return Mocked<TDepend>().Object; } /// <summary> /// Resets Subject instance. A new instance will be created, with new depenencies auto-injected. /// Call this from NUnit's [SetUp] method, if you want each of your tests in the fixture to have a fresh instance of /// <typeparamref name="T" /> /// </summary> public void ResetSubject() { Mocker = new AutoMoqer(); subject = null; } } }
using Moq; namespace AutoMoq.Helpers { public class AutoMoqTestFixture<T> where T : class { private T subject; /// <summary> /// The current AutoMoqer /// </summary> public AutoMoqer Mocker { get; private set; } = new AutoMoqer(); /// <summary> /// The Class being tested in this Test Fixture. /// </summary> public T Subject { get { return subject ?? (subject = Mocker.Resolve<T>()); } } /// <summary> /// A Mock dependency that was auto-injected into Subject /// </summary> /// <typeparam name="TMock"></typeparam> /// <returns></returns> public Mock<TMock> Mocked<TMock>() where TMock : class { return Mocker.GetMock<TMock>(); } /// <summary> /// A dependency that was auto-injected into Subject. Implementation is a Moq object. /// </summary> /// <typeparam name="TDepend"></typeparam> /// <returns></returns> public TDepend Dependency<TDepend>() where TDepend : class { return Mocked<TDepend>().Object; } /// <summary> /// Resets Subject instance. A new instance will be created, with new depenencies auto-injected. /// Call this from NUnit's [SetUp] method, if you want each of your tests in the fixture to have a fresh instance of /// <typeparamref name="T" /> /// </summary> public void ResetSubject() { Mocker = new AutoMoqer(); subject = null; } } }
mit
C#
041e627950d2a89c3bad7c2499f89dce240d7fc9
Revise EnterText to restore original behaviour. (#111)
Bumblebee/Bumblebee,Bumblebee/Bumblebee,chrisblock/Bumblebee,toddmeinershagen/Bumblebee,toddmeinershagen/Bumblebee,chrisblock/Bumblebee
src/Bumblebee/Implementation/TextField.cs
src/Bumblebee/Implementation/TextField.cs
using Bumblebee.Interfaces; using OpenQA.Selenium; namespace Bumblebee.Implementation { public class TextField : Element, ITextField { public TextField(IBlock parent, By by) : base(parent, by) { } public TextField(IBlock parent, IWebElement tag) : base(parent, tag) { } public TResult Press<TResult>(Key key) where TResult : IBlock { Tag.SendKeys(key.Value); return Session.CurrentBlock<TResult>(ParentBlock.Tag); } public virtual TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock { var executor = (IJavaScriptExecutor) Session.Driver; executor.ExecuteScript($"arguments[0].value = '';", Tag); return AppendText<TCustomResult>(text); } public virtual TResult AppendText<TResult>(string text) where TResult : IBlock { Tag.SendKeys(text); return Session.CurrentBlock<TResult>(ParentBlock.Tag); } public override string Text { get { return Tag.GetAttribute("value"); } } } public class TextField<TResult> : TextField, ITextField<TResult> where TResult : IBlock { public TextField(IBlock parent, By by) : base(parent, by) { } public TextField(IBlock parent, IWebElement element) : base(parent, element) { } public TResult Press(Key key) { return Press<TResult>(key); } public virtual TResult EnterText(string text) { return EnterText<TResult>(text); } public virtual TResult AppendText(string text) { return AppendText<TResult>(text); } } }
using Bumblebee.Interfaces; using OpenQA.Selenium; namespace Bumblebee.Implementation { public class TextField : Element, ITextField { public TextField(IBlock parent, By by) : base(parent, by) { } public TextField(IBlock parent, IWebElement tag) : base(parent, tag) { } public TResult Press<TResult>(Key key) where TResult : IBlock { Tag.SendKeys(key.Value); return Session.CurrentBlock<TResult>(ParentBlock.Tag); } public virtual TCustomResult EnterText<TCustomResult>(string text) where TCustomResult : IBlock { Tag.Clear(); return AppendText<TCustomResult>(text); } public virtual TResult AppendText<TResult>(string text) where TResult : IBlock { Tag.SendKeys(text); return Session.CurrentBlock<TResult>(ParentBlock.Tag); } public override string Text { get { return Tag.GetAttribute("value"); } } } public class TextField<TResult> : TextField, ITextField<TResult> where TResult : IBlock { public TextField(IBlock parent, By by) : base(parent, by) { } public TextField(IBlock parent, IWebElement element) : base(parent, element) { } public TResult Press(Key key) { return Press<TResult>(key); } public virtual TResult EnterText(string text) { return EnterText<TResult>(text); } public virtual TResult AppendText(string text) { return AppendText<TResult>(text); } } }
mit
C#
02265ad686625583982e19142bcd4f82ae31955b
Enable mania's basic conversion testcase
peppy/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,johnneijzen/osu,2yangk23/osu,johnneijzen/osu,DrabWeb/osu,ppy/osu,Nabile-Rahmani/osu,UselessToucan/osu,ZLima12/osu,DrabWeb/osu,naoey/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu-new,smoogipoo/osu,Frontear/osuKyzer,ppy/osu,smoogipooo/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,naoey/osu,UselessToucan/osu
osu.Game.Rulesets.Mania/Tests/ManiaBeatmapConversionTest.cs
osu.Game.Rulesets.Mania/Tests/ManiaBeatmapConversionTest.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.MathUtils; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Mania.Tests { public class ManiaBeatmapConversionTest : BeatmapConversionTest<ConvertValue> { protected override string ResourceAssembly => "osu.Game.Rulesets.Mania"; private bool isForCurrentRuleset; [NonParallelizable] [TestCase("basic", false)] public void Test(string name, bool isForCurrentRuleset) { this.isForCurrentRuleset = isForCurrentRuleset; base.Test(name); } protected override IEnumerable<ConvertValue> CreateConvertValue(HitObject hitObject) { yield return new ConvertValue { StartTime = hitObject.StartTime, EndTime = (hitObject as IHasEndTime)?.EndTime ?? hitObject.StartTime, Column = ((ManiaHitObject)hitObject).Column }; } protected override IBeatmapConverter CreateConverter(Beatmap beatmap) => new ManiaBeatmapConverter(isForCurrentRuleset, beatmap); } public struct ConvertValue : IEquatable<ConvertValue> { /// <summary> /// A sane value to account for osu!stable using ints everwhere. /// </summary> private const float conversion_lenience = 2; public double StartTime; public double EndTime; public int Column; public bool Equals(ConvertValue other) => Precision.AlmostEquals(StartTime, other.StartTime, conversion_lenience) && Precision.AlmostEquals(EndTime, other.EndTime, conversion_lenience) && Column == other.Column; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.MathUtils; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Mania.Tests { public class ManiaBeatmapConversionTest : BeatmapConversionTest<ConvertValue> { protected override string ResourceAssembly => "osu.Game.Rulesets.Mania"; private bool isForCurrentRuleset; [NonParallelizable] [TestCase("basic", false), Ignore("See: https://github.com/ppy/osu/issues/2150")] public void Test(string name, bool isForCurrentRuleset) { this.isForCurrentRuleset = isForCurrentRuleset; base.Test(name); } protected override IEnumerable<ConvertValue> CreateConvertValue(HitObject hitObject) { yield return new ConvertValue { StartTime = hitObject.StartTime, EndTime = (hitObject as IHasEndTime)?.EndTime ?? hitObject.StartTime, Column = ((ManiaHitObject)hitObject).Column }; } protected override IBeatmapConverter CreateConverter(Beatmap beatmap) => new ManiaBeatmapConverter(isForCurrentRuleset, beatmap); } public struct ConvertValue : IEquatable<ConvertValue> { /// <summary> /// A sane value to account for osu!stable using ints everwhere. /// </summary> private const float conversion_lenience = 2; public double StartTime; public double EndTime; public int Column; public bool Equals(ConvertValue other) => Precision.AlmostEquals(StartTime, other.StartTime, conversion_lenience) && Precision.AlmostEquals(EndTime, other.EndTime, conversion_lenience) && Column == other.Column; } }
mit
C#
9116775d3ccdf54b577b1c2a8c51ca7ee46334d7
remove unused extension method
ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate
src/Abp.Zero.EntityFramework/EntityHistory/Extensions/DbEntityEntryExtensions.cs
src/Abp.Zero.EntityFramework/EntityHistory/Extensions/DbEntityEntryExtensions.cs
using System; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Reflection; using Abp.Domain.Entities; using Abp.Extensions; namespace Abp.EntityHistory.Extensions { internal static class DbEntityEntryExtensions { internal static Type GetEntityBaseType(this DbEntityEntry entityEntry) { return ObjectContext.GetObjectType(entityEntry.Entity.GetType()); } internal static PropertyInfo GetPropertyInfo(this DbEntityEntry entityEntry, string propertyName) { return entityEntry.GetEntityBaseType().GetProperty(propertyName); } internal static bool IsCreated(this DbEntityEntry entityEntry) { return entityEntry.State == EntityState.Added; } internal static bool IsDeleted(this DbEntityEntry entityEntry) { if (entityEntry.State == EntityState.Deleted) { return true; } var entity = entityEntry.Entity; return entity is ISoftDelete && entity.As<ISoftDelete>().IsDeleted; } } }
using System; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using System.Reflection; using Abp.Auditing; using Abp.Domain.Entities; using Abp.Extensions; namespace Abp.EntityHistory.Extensions { internal static class DbEntityEntryExtensions { internal static Type GetEntityBaseType(this DbEntityEntry entityEntry) { return ObjectContext.GetObjectType(entityEntry.Entity.GetType()); } internal static PropertyInfo GetPropertyInfo(this DbEntityEntry entityEntry, string propertyName) { return entityEntry.GetEntityBaseType().GetProperty(propertyName); } internal static DbPropertyValues GetPropertyValues(this DbEntityEntry entityEntry) { if (entityEntry.State == EntityState.Deleted) { return entityEntry.OriginalValues; } return entityEntry.CurrentValues; } internal static bool HasAuditedProperties(this DbEntityEntry entityEntry) { var propertyNames = entityEntry.GetPropertyValues().PropertyNames; var entityType = entityEntry.GetEntityBaseType(); return propertyNames.Any(p => entityType.GetProperty(p)?.IsDefined(typeof(AuditedAttribute)) ?? false); } internal static bool IsCreated(this DbEntityEntry entityEntry) { return entityEntry.State == EntityState.Added; } internal static bool IsDeleted(this DbEntityEntry entityEntry) { if (entityEntry.State == EntityState.Deleted) { return true; } var entity = entityEntry.Entity; return entity is ISoftDelete && entity.As<ISoftDelete>().IsDeleted; } } }
mit
C#
094d4d6bb6486daa305d33422138d587ac638e86
update autofac sample
AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/Abstractions,AspectCore/AspectCore-Framework
extras/sample/AspectCore.Extensions.Autofac.Sample/Program.cs
extras/sample/AspectCore.Extensions.Autofac.Sample/Program.cs
using System; using AspectCore.Configuration; using AspectCore.Injector; using Autofac; namespace AspectCore.Extensions.Autofac.Sample { class Program { static void Main(string[] args) { var serviceContaniner = new ServiceContainer(); serviceContaniner.AddType<ITaskService, TaskService>(); var containerBuilder = new ContainerBuilder(); //调用Populate扩展方法在Autofac中注册已经注册到ServiceContainer中的服务(如果有)。注:此方法调用应在RegisterDynamicProxy之前 containerBuilder.Populate(serviceContaniner); var configuration = serviceContaniner.Configuration; //调用RegisterDynamicProxy扩展方法在Autofac中注册动态代理服务和动态代理配置 containerBuilder.RegisterDynamicProxy(configuration, config => { config.Interceptors.AddTyped<MethodExecuteLoggerInterceptor>(Predicates.ForService("*Service")); }); var container = containerBuilder.Build(); var taskService = container.Resolve<ITaskService>(); taskService.Run(); Console.ReadKey(); } } public interface ITaskService { bool Run(); } public class TaskService : ITaskService { public bool Run() { return true; } } }
using System; using AspectCore.Configuration; using AspectCore.Injector; using Autofac; namespace AspectCore.Extensions.Autofac.Sample { class Program { static void Main(string[] args) { var serviceContaniner = new ServiceContainer(); serviceContaniner.AddType<ITaskService, TaskService>(); var containerBuilder = new ContainerBuilder(); //调用Populate扩展方法在Autofac中注册已经注册到ServiceContainer中的服务(如果有)。注:此方法调用应在RegisterDynamicProxy之前 containerBuilder.Populate(serviceContaniner); //调用RegisterDynamicProxy扩展方法在Autofac中注册动态代理服务和动态代理配置 containerBuilder.RegisterDynamicProxy(config => { config.Interceptors.AddTyped<MethodExecuteLoggerInterceptor>(Predicates.ForService("*Service")); }); var container = containerBuilder.Build(); var taskService = container.Resolve<ITaskService>(); taskService.Run(); Console.ReadKey(); } } public interface ITaskService { bool Run(); } public class TaskService : ITaskService { public bool Run() { return true; } } }
mit
C#
f619632b1da853d596bd24c3ffd5dabc13b42063
Change comments header
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/ConsoleMinesweeper.Test/Properties/AssemblyInfo.cs
src2/ConsoleMinesweeper.Test/Properties/AssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleMinesweeper.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johnson Controls")] [assembly: AssemblyProduct("ConsoleMinesweeper.Test")] [assembly: AssemblyCopyright("Copyright © Johnson Controls 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dca5595d-4497-463c-8f75-632c704cef94")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company=""> // // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleMinesweeper.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johnson Controls")] [assembly: AssemblyProduct("ConsoleMinesweeper.Test")] [assembly: AssemblyCopyright("Copyright © Johnson Controls 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dca5595d-4497-463c-8f75-632c704cef94")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
b1af8a258a38ce66e0ddee1231b917f8efd29499
Remove YAML handling code
faint32/snowflake-1,SnowflakePowered/snowflake,faint32/snowflake-1,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1
Snowflake/Emulator/Configuration/ConfigurationProfile.cs
Snowflake/Emulator/Configuration/ConfigurationProfile.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SharpYaml.Serialization; using Snowflake.Emulator.Configuration; namespace Snowflake.Emulator.Configuration { public class ConfigurationProfile : IConfigurationProfile { public IReadOnlyDictionary<string, dynamic> ConfigurationValues { get; private set; } public string TemplateID { get; private set; } public ConfigurationProfile (string templateId, IDictionary<string, dynamic> value) { this.ConfigurationValues = value.AsReadOnly(); this.TemplateID = templateId; } public static IConfigurationProfile FromJsonProtoTemplate (IDictionary<string, dynamic> protoTemplate) { //Account for JSON source where JObject is required return new ConfigurationProfile(protoTemplate["TemplateID"], ((JObject)protoTemplate["ConfigurationValues"]) .ToObject<IDictionary<object, dynamic>>() .ToDictionary(value => (string)value.Key, value => value.Value)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SharpYaml.Serialization; using Snowflake.Emulator.Configuration; namespace Snowflake.Emulator.Configuration { public class ConfigurationProfile : IConfigurationProfile { public IReadOnlyDictionary<string, dynamic> ConfigurationValues { get; private set; } public string TemplateID { get; private set; } public ConfigurationProfile (string templateId, IDictionary<string, dynamic> value) { this.ConfigurationValues = value.AsReadOnly(); this.TemplateID = templateId; } public static IConfigurationProfile FromJsonProtoTemplate (IDictionary<string, dynamic> protoTemplate) { try { return new ConfigurationProfile(protoTemplate["TemplateID"], ((IDictionary<object, dynamic>)protoTemplate["ConfigurationValues"]) .ToDictionary(value => (string)value.Key, value => value.Value)); } catch (InvalidCastException) { //Account for JSON source where JObject is required return new ConfigurationProfile(protoTemplate["TemplateID"], ((JObject)protoTemplate["ConfigurationValues"]) .ToObject<IDictionary<object, dynamic>>() .ToDictionary(value => (string)value.Key, value => value.Value)); } } } }
mpl-2.0
C#
61bc0351a6cb706ba9b64c1b25b52c2f907c45c0
Add installer_patcher get controller method
Endlessages/EndlessAges.LauncherService
src/EndlessAges.LauncherService/Controllers/ContentManager.cs
src/EndlessAges.LauncherService/Controllers/ContentManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace EndlessAges.LauncherService.Controllers { /// <summary> /// Emulated controller ContentManager.aspx from the Endless Ages backend. /// </summary> [Route("ContentManager.aspx")] public class ContentManager : Controller { //ContentManager.aspx?installer_patcher=ENDLESS [HttpGet] public IActionResult Get([FromQuery]string installer_patcher) { //If no valid parameter was provided in the query then return an error code //This should only happen if someone is spoofing //422 (Unprocessable Entity) if (string.IsNullOrWhiteSpace(installer_patcher)) return StatusCode(422); //TODO: What exactly should the backend return? EACentral returns a broken url return Content($"{@"http://game1.endlessagesonline./ENDLESSINSTALL.cab"}\n{@"ENDLESSINSTALL.cab"}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace EndlessAges.LauncherService.Controllers { /// <summary> /// Emulated controller ContentManager.aspx from the Endless Ages backend. /// </summary> [Route("ContentManager.aspx")] public class ContentManager : Controller { } }
mit
C#
f117a00ce104a7146cc366e0ffa7785b0b0caeed
Fix piping issue with Get-AzureRmDnsZone (#4213)
hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell
src/ResourceManager/Dns/Commands.Dns/Zones/GetAzureDnsZone.cs
src/ResourceManager/Dns/Commands.Dns/Zones/GetAzureDnsZone.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Dns.Models; using System.Management.Automation; using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources; namespace Microsoft.Azure.Commands.Dns { /// <summary> /// Gets one or more existing zones. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmDnsZone", DefaultParameterSetName = "Default"), OutputType(typeof(DnsZone))] public class GetAzureDnsZone : DnsBaseCmdlet { private const string ParameterSetResourceGroup = "ResourceGroup"; [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetResourceGroup, HelpMessage = "The full name of the zone (without a terminating dot).")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetResourceGroup, HelpMessage = "The resource group in which the zone exists.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } public override void ExecuteCmdlet() { if (this.Name != null) { if (this.Name.EndsWith(".")) { this.Name = this.Name.TrimEnd('.'); this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'. Zone name used is \"{0}\".", this.Name)); } this.WriteObject(this.DnsClient.GetDnsZone(this.Name, this.ResourceGroupName)); } else if (!string.IsNullOrEmpty(this.ResourceGroupName)) { WriteObject(this.DnsClient.ListDnsZonesInResourceGroup(this.ResourceGroupName), true); } else { WriteObject(this.DnsClient.ListDnsZonesInSubscription(), true); } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Dns.Models; using System.Management.Automation; using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources; namespace Microsoft.Azure.Commands.Dns { /// <summary> /// Gets one or more existing zones. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmDnsZone", DefaultParameterSetName = "Default"), OutputType(typeof(DnsZone))] public class GetAzureDnsZone : DnsBaseCmdlet { private const string ParameterSetResourceGroup = "ResourceGroup"; [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetResourceGroup, HelpMessage = "The full name of the zone (without a terminating dot).")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetResourceGroup, HelpMessage = "The resource group in which the zone exists.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } public override void ExecuteCmdlet() { if (this.Name != null) { if (this.Name.EndsWith(".")) { this.Name = this.Name.TrimEnd('.'); this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'. Zone name used is \"{0}\".", this.Name)); } this.WriteObject(this.DnsClient.GetDnsZone(this.Name, this.ResourceGroupName)); } else if (!string.IsNullOrEmpty(this.ResourceGroupName)) { WriteObject(this.DnsClient.ListDnsZonesInResourceGroup(this.ResourceGroupName)); } else { WriteObject(this.DnsClient.ListDnsZonesInSubscription()); } } } }
apache-2.0
C#
5c0f6629145bada67410299acdce52a1b464618f
Add tests.
gafter/roslyn,dotnet/roslyn,genlu/roslyn,sharwell/roslyn,diryboy/roslyn,DustinCampbell/roslyn,VSadov/roslyn,genlu/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,davkean/roslyn,jasonmalinowski/roslyn,xasx/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,abock/roslyn,weltkante/roslyn,heejaechang/roslyn,eriawan/roslyn,wvdd007/roslyn,reaction1989/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,nguerrera/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,sharwell/roslyn,jmarolf/roslyn,DustinCampbell/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,AmadeusW/roslyn,aelij/roslyn,stephentoub/roslyn,nguerrera/roslyn,physhi/roslyn,mavasani/roslyn,tmat/roslyn,dotnet/roslyn,eriawan/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,swaroop-sridhar/roslyn,agocke/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,mavasani/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,nguerrera/roslyn,jmarolf/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,tmat/roslyn,abock/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,tannergooding/roslyn,agocke/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,VSadov/roslyn,AlekseyTs/roslyn,diryboy/roslyn,VSadov/roslyn,MichalStrehovsky/roslyn,KevinRansom/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,aelij/roslyn,abock/roslyn,xasx/roslyn,tannergooding/roslyn,jcouv/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,MichalStrehovsky/roslyn,sharwell/roslyn,davkean/roslyn,tmat/roslyn,genlu/roslyn,jmarolf/roslyn,bartdesmet/roslyn,physhi/roslyn,reaction1989/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,jcouv/roslyn,xasx/roslyn,aelij/roslyn,gafter/roslyn,weltkante/roslyn,DustinCampbell/roslyn,wvdd007/roslyn,davkean/roslyn,gafter/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,dotnet/roslyn,panopticoncentral/roslyn,physhi/roslyn
src/EditorFeatures/CSharpTest/UseCompoundAssignment/UseCompoundAssignmentTests.cs
src/EditorFeatures/CSharpTest/UseCompoundAssignment/UseCompoundAssignmentTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment; using Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCompoundAssignment { public class UseCompoundAssignmentTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCompoundAssignmentDiagnosticAnalyzer(), new CSharpUseCompoundAssignmentCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] public async Task TestAddExpression() { await TestInRegularAndScriptAsync( @"public class C { void M(int a) { a [||]= a + 10; } }", @"public class C { void M(int a) { a += 10; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] public async Task TestSubtractExpression() { await TestInRegularAndScriptAsync( @"public class C { void M(int a) { a [||]= a - 10; } }", @"public class C { void M(int a) { a -= 10; } }"); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment; using Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCompoundAssignment { public class UseCompoundAssignmentTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCompoundAssignmentDiagnosticAnalyzer(), new CSharpUseCompoundAssignmentCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)] public async Task TestAddExpression() { await TestInRegularAndScriptAsync( @"public class C { void M(int a) { a [||]= a + 10; } }", @"public class C { void M(int a) { a += 10; } }"); } } }
mit
C#
a5cb3b66fbab88c01e85ae4987f24f202c5b5c74
Update to v2.0.2.0
wbish/jsondiffpatch.net
Src/JsonDiffPatchDotNet/Properties/AssemblyInfo.cs
Src/JsonDiffPatchDotNet/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("JsonDiffPatch.Net")] [assembly: AssemblyDescription("JSON object diffs and reversible patching (jsondiffpatch compatible)")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("William Bishop")] [assembly: AssemblyProduct("JsonDiffPatch.Net")] [assembly: AssemblyCopyright("Copyright © William Bishop 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.2.0")] [assembly: AssemblyFileVersion("2.0.2.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("JsonDiffPatch.Net")] [assembly: AssemblyDescription("JSON object diffs and reversible patching (jsondiffpatch compatible)")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("William Bishop")] [assembly: AssemblyProduct("JsonDiffPatch.Net")] [assembly: AssemblyCopyright("Copyright © William Bishop 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.1.0")] [assembly: AssemblyFileVersion("2.0.1.0")]
mit
C#
0a86023a695e2f6ef2ffaaa1d6b6b80475c44b32
Update ShellCommandParameterAttribute.cs
tiksn/TIKSN-Framework
TIKSN.Core/Shell/ShellCommandParameterAttribute.cs
TIKSN.Core/Shell/ShellCommandParameterAttribute.cs
using System; namespace TIKSN.Shell { [AttributeUsage(AttributeTargets.Property)] public sealed class ShellCommandParameterAttribute : ShellAttributeBase { public ShellCommandParameterAttribute(int nameKey) : base(nameKey) { } public ShellCommandParameterAttribute(string nameKey) : base(nameKey) { } public bool Mandatory { get; set; } public int Position { get; set; } } }
using System; namespace TIKSN.Shell { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public sealed class ShellCommandParameterAttribute : ShellAttributeBase { public ShellCommandParameterAttribute(int nameKey) : base(nameKey) { } public ShellCommandParameterAttribute(string nameKey) : base(nameKey) { } public bool Mandatory { get; set; } public int Position { get; set; } } }
mit
C#
e4780abdfddf1642ff454e2fcad4e882adbe58e7
Split out `base` call from `switch` statement
smoogipooo/osu,ppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu
osu.Game/Overlays/Wiki/Markdown/WikiMarkdownContainer.cs
osu.Game/Overlays/Wiki/Markdown/WikiMarkdownContainer.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 Markdig.Extensions.Yaml; using Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Wiki.Markdown { public class WikiMarkdownContainer : OsuMarkdownContainer { public string CurrentPath { set => Schedule(() => DocumentUrl += $"wiki/{value}"); } protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level) { switch (markdownObject) { case YamlFrontMatterBlock yamlFrontMatterBlock: container.Add(CreateNotice(yamlFrontMatterBlock)); return; } base.AddMarkdownComponent(markdownObject, container, level); } public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer(); protected override MarkdownParagraph CreateParagraph(ParagraphBlock paragraphBlock, int level) => new WikiMarkdownParagraph(paragraphBlock); protected virtual FillFlowContainer CreateNotice(YamlFrontMatterBlock yamlFrontMatterBlock) => new WikiNoticeContainer(yamlFrontMatterBlock); private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline)); } } }
// 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 Markdig.Extensions.Yaml; using Markdig.Syntax; using Markdig.Syntax.Inlines; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Graphics.Containers.Markdown; namespace osu.Game.Overlays.Wiki.Markdown { public class WikiMarkdownContainer : OsuMarkdownContainer { public string CurrentPath { set => Schedule(() => DocumentUrl += $"wiki/{value}"); } protected override void AddMarkdownComponent(IMarkdownObject markdownObject, FillFlowContainer container, int level) { switch (markdownObject) { case YamlFrontMatterBlock yamlFrontMatterBlock: container.Add(CreateNotice(yamlFrontMatterBlock)); break; default: base.AddMarkdownComponent(markdownObject, container, level); break; } } public override MarkdownTextFlowContainer CreateTextFlow() => new WikiMarkdownTextFlowContainer(); protected override MarkdownParagraph CreateParagraph(ParagraphBlock paragraphBlock, int level) => new WikiMarkdownParagraph(paragraphBlock); protected virtual FillFlowContainer CreateNotice(YamlFrontMatterBlock yamlFrontMatterBlock) => new WikiNoticeContainer(yamlFrontMatterBlock); private class WikiMarkdownTextFlowContainer : OsuMarkdownTextFlowContainer { protected override void AddImage(LinkInline linkInline) => AddDrawable(new WikiMarkdownImage(linkInline)); } } }
mit
C#
1df45dd0f5020adc98beeeb741eb85eff12a870b
Improve the example code
defmys/Unity3D-Raven-CS
Assets/Unity3D-Raven-CS/Example/example.cs
Assets/Unity3D-Raven-CS/Example/example.cs
using UnityEngine; using System.Collections.Generic; using System; public class example : MonoBehaviour { private Unity3DRavenCS.Unity3DRavenCS m_client; private Dictionary<string, string> m_tags = null; void Start() { // Create a raven client with DSN uri. m_client = new Unity3DRavenCS.Unity3DRavenCS("http://5aa275ef70b0416f80a405b258d20a15:801b6e0d9cbf46508560b9ca0b320c6a@192.168.188.128:9000/2"); // Create some tags that need to be sent with log messages. m_tags = new Dictionary<string, string>(); m_tags.Add("playTime", Time.realtimeSinceStartup.ToString()); m_tags.Add("time", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); m_tags.Add("ProcessorType", SystemInfo.processorType); m_tags.Add("ProcessorCount", SystemInfo.processorCount.ToString()); m_tags.Add("Device-Uid", SystemInfo.deviceUniqueIdentifier); m_tags.Add("Device-Model", SystemInfo.deviceModel); m_tags.Add("Device-Name", SystemInfo.deviceName); m_tags.Add("OS", SystemInfo.operatingSystem); m_tags.Add("MemorySize", SystemInfo.systemMemorySize.ToString()); m_tags.Add("GPU-Memory", SystemInfo.graphicsMemorySize.ToString()); m_tags.Add("GPU-Name", SystemInfo.graphicsDeviceName); m_tags.Add("GPU-Vendor", SystemInfo.graphicsDeviceVendor); m_tags.Add("GPU-VendorID", SystemInfo.graphicsDeviceVendorID.ToString()); m_tags.Add("GPU-id", SystemInfo.graphicsDeviceID.ToString()); m_tags.Add("GPU-Version", SystemInfo.graphicsDeviceVersion); m_tags.Add("GPU-ShaderLevel", SystemInfo.graphicsShaderLevel.ToString()); // ========================================================================================================= // Capture message m_client.CaptureMessage("Hello, world!", LogType.Log, m_tags); // Capture exception try { ExceptionCall(); } catch (Exception e) { m_client.CaptureException(e); } // ========================================================================================================= // You can register a log handler to handle all logs including exceptions. // See LogHandler(), OnEnable() and OnDisable(). // The following logs will be sent to sentry server automatically. Debug.Log("Info log"); Debug.LogWarning("Warning log"); Debug.LogError("Error log"); // The following function call throws an exception. An error log with stack trace will be sent // to sentry server automatically. ExceptionCall(); } void OnEnable() { Application.logMessageReceived += LogHandler; } void OnDisable() { Application.logMessageReceived -= LogHandler; } public void LogHandler(string condition, string stackTrace, LogType type) { if (m_client == null) { return; } if (type == LogType.Exception) { m_client.CaptureException(condition, stackTrace, m_tags); } else { m_client.CaptureMessage(condition, type, m_tags); } } private void ExceptionCall() { ExceptionCall1(); } private void ExceptionCall1() { ExceptionCall2(); } private void ExceptionCall2() { int a = 1; int b = 0; int x = a / b; } }
using UnityEngine; using System.Collections; using System; public class example : MonoBehaviour { private Unity3DRavenCS.Unity3DRavenCS client; // Use this for initialization void Start () { Application.stackTraceLogType = StackTraceLogType.ScriptOnly; client = new Unity3DRavenCS.Unity3DRavenCS ("http://ab02bafeb811496c825b4f22631f3ea3:81efdf5ff4f34aeb8e4bb20b27d286eb@192.168.1.109:9000/2"); //client.CaptureMessage ("Hello, world!"); try { int a = 1; int b = 0; int x = a / b; } catch (Exception e) { client.captureException(e); Debug.Log (e.Message); throw; } } // Update is called once per frame void Update () { } }
mit
C#
a2e94bb61f300d6f70e2025ecd84a493011804d6
Update version
Yonom/CupCake
CupCake/Properties/AssemblyInfo.cs
CupCake/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CupCake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CupCake")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("45412037-53ac-4f20-97ce-4245dcc4c215")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.4.7")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CupCake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CupCake")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("45412037-53ac-4f20-97ce-4245dcc4c215")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.4.6")]
mit
C#
b4a23462bf9488e19e3dad2544eab32a9c540ae4
add exception in BaseResponse
ChiiAyano/Mikaboshi.Locapos
Mikaboshi.Locapos/Response/BaseResponse.cs
Mikaboshi.Locapos/Response/BaseResponse.cs
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Mikaboshi.Locapos.Response { /// <summary> /// Locapos からの、特別な情報を持たない、ベースとなるレスポンスを格納するクラスです。 /// </summary> public class BaseResponse { protected HttpResponseMessage ResponseMessage { get; private set; } /// <summary> /// Locapos からの応答コードを取得します。 /// </summary> public HttpStatusCode StatusCode { get; private set; } /// <summary> /// Locapos から成功の応答があったかどうかを取得します。 /// </summary> public bool Succeeded => this.ResponseMessage?.IsSuccessStatusCode ?? false; /// <summary> /// 例外が発生した場合、発生した例外を取得します。 /// </summary> public Exception Exception { get; private set; } public BaseResponse() { } public BaseResponse(Exception ex) { this.Exception = ex; } /// <summary> /// ベース クラスでは、基本的なレスポンス情報を設定します。 /// </summary> /// <param name="response"></param> /// <returns></returns> internal virtual Task SetResponseAsync(HttpResponseMessage response) { this.ResponseMessage = response; this.StatusCode = response.StatusCode; #if NETSTANDARD1_4 || NET46 return Task.CompletedTask; #else return Task.FromResult<object>(null); #endif } } }
using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Mikaboshi.Locapos.Response { /// <summary> /// Locapos からの、特別な情報を持たない、ベースとなるレスポンスを格納するクラスです。 /// </summary> public class BaseResponse { protected HttpResponseMessage ResponseMessage { get; private set; } /// <summary> /// Locapos からの応答コードを取得します。 /// </summary> public HttpStatusCode StatusCode { get; private set; } /// <summary> /// Locapos から成功の応答があったかどうかを取得します。 /// </summary> public bool Succeeded => this.ResponseMessage?.IsSuccessStatusCode ?? false; /// <summary> /// ベース クラスでは、基本的なレスポンス情報を設定します。 /// </summary> /// <param name="response"></param> /// <returns></returns> internal virtual Task SetResponseAsync(HttpResponseMessage response) { this.ResponseMessage = response; this.StatusCode = response.StatusCode; #if NETSTANDARD1_4 || NET46 return Task.CompletedTask; #else return Task.FromResult<object>(null); #endif } } }
mit
C#
1e2c8ad362a8771225d055ef6a38e002428bec02
Update sample
MarcBruins/TTGSnackbar-Xamarin-iOS
Sample/TTGSnackbarSample/ViewController.cs
Sample/TTGSnackbarSample/ViewController.cs
using System; using System.Threading.Tasks; using SnackBarTTG.Source; using UIKit; namespace TTGSnackbarSample { public partial class ViewController : UIViewController { protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); } partial void buttonClicked(UIButton sender) { var snackbar = new TTGSnackbar("Hello Xamarin snackbar", TTGSnackbarDuration.Long); snackbar.AnimationType = TTGSnackbarAnimationType.SlideFromRightToLeft; // Action 1 snackbar.ActionText = "Yes"; snackbar.ActionTextColor = UIColor.Green; snackbar.ActionBlock = (t) => { Console.WriteLine("clicked yes"); }; // Action 2 snackbar.SecondActionText = "No"; snackbar.SecondActionTextColor = UIColor.Magenta; snackbar.SecondActionBlock = (t) => { Console.WriteLine("clicked no"); }; snackbar.Show(); } public void cancel() { //do something } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
using System; using System.Threading.Tasks; using SnackBarTTG.Source; using UIKit; namespace TTGSnackbarSample { public partial class ViewController : UIViewController { protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); } partial void buttonClicked(UIButton sender) { var snackbar = new TTGSnackbar("Hello Xamarin snackbar", TTGSnackbarDuration.Forever); // Action 1 snackbar.ActionText = "Yes"; snackbar.ActionTextColor = UIColor.Green; snackbar.ActionBlock = (t) => { Console.WriteLine("clicked yes"); }; // Action 2 snackbar.SecondActionText = "No"; snackbar.SecondActionTextColor = UIColor.Magenta; snackbar.SecondActionBlock = (t) => { Console.WriteLine("clicked no"); }; snackbar.Show(); } public void cancel() { //do something } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
mit
C#
180beb6518692b6693946954b621ddcae53216fd
Update ResourceConverterExtenstions.cs
eoin55/HoneyBear.HalClient
Src/HoneyBear.HalClient/Models/ResourceConverterExtenstions.cs
Src/HoneyBear.HalClient/Models/ResourceConverterExtenstions.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Newtonsoft.Json.Linq; namespace HoneyBear.HalClient.Models { /// <summary> /// Contains a set of IResource extensions. /// </summary> public static class ResourceConverterExtenstions { internal static T Data<T>(this IResource source) where T : class, new() { var data = new T(); var dataType = typeof(T); foreach (var property in dataType.GetProperties()) { var pair = source.FirstOrDefault(p => p.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)); if (pair.Key == null) continue; var propertyType = dataType.GetProperty(property.Name).PropertyType; object value; var complex = pair.Value as JObject; var array = pair.Value as JArray; if (complex != null) value = complex.ToObject(propertyType); else if (array != null) value = array.ToObject(propertyType); else if (pair.Value != null) value = TypeDescriptor.GetConverter(propertyType).ConvertFromInvariantString(pair.Value.ToString()); else value = null; property.SetValue(data, value, null); } return data; } /// <summary> /// Deserialises a list of resources into a given type. /// </summary> /// <param name="source">The list of resources.</param> /// <typeparam name="T">The type to deserialise the resources into.</typeparam> /// <returns>A list of deserialised POCOs.</returns> public static IEnumerable<T> Data<T>(this IEnumerable<IResource<T>> source) where T : class, new() => source.Select(s => s.Data); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Newtonsoft.Json.Linq; namespace HoneyBear.HalClient.Models { /// <summary> /// Contains a set of IResource extensions. /// </summary> public static class ResourceConverterExtenstions { internal static T Data<T>(this IResource source) where T : class, new() { var data = new T(); var dataType = typeof(T); foreach (var property in dataType.GetProperties()) { var pair = source.FirstOrDefault(p => p.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)); if (pair.Key == null) continue; var propertyType = dataType.GetProperty(property.Name).PropertyType; object value; var complex = pair.Value as JObject; var array = pair.Value as JArray; if (complex != null) value = complex.ToObject(propertyType); else if (array != null) value = array.ToObject(propertyType); else value = TypeDescriptor.GetConverter(propertyType).ConvertFromInvariantString(pair.Value.ToString()); property.SetValue(data, value, null); } return data; } /// <summary> /// Deserialises a list of resources into a given type. /// </summary> /// <param name="source">The list of resources.</param> /// <typeparam name="T">The type to deserialise the resources into.</typeparam> /// <returns>A list of deserialised POCOs.</returns> public static IEnumerable<T> Data<T>(this IEnumerable<IResource<T>> source) where T : class, new() => source.Select(s => s.Data); } }
mit
C#
3e6a1454248c4763dece4a14722da82bd8ddbff8
remove comments only
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts/Mappings/AccountMappings.cs
src/SFA.DAS.EmployerAccounts/Mappings/AccountMappings.cs
using AutoMapper; using SFA.DAS.Authorization; using SFA.DAS.EmployerAccounts.Api.Types; using SFA.DAS.EmployerAccounts.Dtos; using SFA.DAS.EmployerAccounts.Models.Account; namespace SFA.DAS.EmployerAccounts.Mappings { public class AccountMappings : Profile { public AccountMappings() { CreateMap<Account, AccountContext>(); CreateMap<Account, AccountDto>(); CreateMap<Account, AccountDetailViewModel>() .ForMember(target => target.AccountId, opt => opt.MapFrom(src => src.Id)) .ForMember(target => target.HashedAccountId, opt => opt.MapFrom(src => src.HashedId)) .ForMember(target => target.PublicHashedAccountId, opt => opt.MapFrom(src => src.PublicHashedId)) .ForMember(target => target.DateRegistered, opt => opt.MapFrom(src => src.CreatedDate)) .ForMember(target => target.DasAccountName, opt => opt.MapFrom(src => src.Name)); } } }
using AutoMapper; using SFA.DAS.Authorization; using SFA.DAS.EmployerAccounts.Api.Types; using SFA.DAS.EmployerAccounts.Dtos; using SFA.DAS.EmployerAccounts.Models.Account; namespace SFA.DAS.EmployerAccounts.Mappings { public class AccountMappings : Profile { public AccountMappings() { CreateMap<Account, AccountContext>(); CreateMap<Account, AccountDto>(); // tangled api has this mapping in api project itself // check gets called. right place? // original maps from Domain.Models.Account.Account CreateMap<Account, AccountDetailViewModel>() .ForMember(target => target.AccountId, opt => opt.MapFrom(src => src.Id)) .ForMember(target => target.HashedAccountId, opt => opt.MapFrom(src => src.HashedId)) .ForMember(target => target.PublicHashedAccountId, opt => opt.MapFrom(src => src.PublicHashedId)) .ForMember(target => target.DateRegistered, opt => opt.MapFrom(src => src.CreatedDate)) .ForMember(target => target.DasAccountName, opt => opt.MapFrom(src => src.Name)); } } }
mit
C#
be9d6bcad9892fc6f4a6dc41b8375f2faa8884a0
Add ignore attribute to test which for some reason fails when it is run together with other tests
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Zk.Tests/Helpers/UrlHelperExtensionTest.cs
Zk.Tests/Helpers/UrlHelperExtensionTest.cs
using NUnit.Framework; using System.Web.Mvc; using System.Web.Routing; using Zk.Helpers; namespace Zk.Tests { [Ignore] [TestFixture] public class UrlHelperExtensionTest { [Test] public void UrlHelper_CreatePartialViewName() { // ARRANGE var httpContext = MvcMockHelpers.MockHttpContext(); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext, routeData); var urlHelper = new UrlHelper(requestContext); // ACT var expected = "~/Views/Controller/_PartialView.cshtml"; var actual = urlHelper.View("_PartialView", "Controller"); // ASSERT Assert.AreEqual(expected, actual, "The UrlpHelper View extension should return the path to the partial view."); } } }
using NUnit.Framework; using System.Web.Mvc; using System.Web.Routing; using Zk.Helpers; namespace Zk.Tests { [TestFixture] public class UrlHelperExtensionTest { [Test] public void UrlHelper_CreatePartialViewName() { // ARRANGE var httpContext = MvcMockHelpers.MockHttpContext(); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext, routeData); var urlHelper = new UrlHelper(requestContext); // ACT var expected = "~/Views/Controller/_PartialView.cshtml"; var actual = urlHelper.View("_PartialView", "Controller"); // ASSERT Assert.AreEqual(expected, actual, "The UrlpHelper View extension should return the path to the partial view."); } } }
mit
C#
c5f9b5e6971da9611b599991858e9c4dd23ee008
Bump version to 1.3.2
mwilliamson/dotnet-mammoth
Mammoth/Properties/AssemblyInfo.cs
Mammoth/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Mammoth")] [assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Williamson")] [assembly: AssemblyProduct("Mammoth")] [assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.3.2.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Mammoth")] [assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Michael Williamson")] [assembly: AssemblyProduct("Mammoth")] [assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.3.1.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
bsd-2-clause
C#
01b706b0a1bcb194f7a70af59681bb690b8b651d
Update ElmahIoApplicationEventHandler.cs
elmahio/elmah.io.umbraco
elmah.io.umbraco/ElmahIoApplicationEventHandler.cs
elmah.io.umbraco/ElmahIoApplicationEventHandler.cs
using System.Web; using Umbraco.Core; using Umbraco.Web.Routing; namespace Elmah.Io.Umbraco { public class ElmahIoApplicationEventHandler : ApplicationEventHandler { protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { ContentLastChanceFinderResolver.Current.SetFinder(new NotFoundLastChangeFinder()); base.ApplicationStarting(umbracoApplication, applicationContext); } } public class NotFoundLastChangeFinder : IContentFinder { public bool TryFindContent(PublishedContentRequest contentRequest) { if (contentRequest.Is404) { ErrorSignal.FromCurrentContext().Raise(new HttpException(404, "Page not found")); } return false; } } }
using System.Web; using Umbraco.Core; using Umbraco.Web.Routing; namespace Elmah.Io.Umbraco { public class ElmahIoApplicationEventHandler : ApplicationEventHandler { protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { ContentLastChanceFinderResolver.Current.SetFinder(new NotFoundLastChangeFinder()); base.ApplicationStarting(umbracoApplication, applicationContext); } } public class NotFoundLastChangeFinder : IContentFinder { public bool TryFindContent(PublishedContentRequest contentRequest) { if (contentRequest.Is404) { ErrorSignal.FromCurrentContext().Raise(new HttpException(404, "Page not fount")); } return false; } } }
apache-2.0
C#
a149e5c5f8d07ecbbb80f93e9bf4344e6bcf7b94
add GetVolsByDepartureDateDepartureCityArrivalCity
guillaume-chs/EMN-dotnet,guillaume-chs/EMN-dotnet,guillaume-chs/EMN-dotnet,guillaume-chs/EMN-dotnet
PKG-vols-hotels/DALVols/DALVols.cs
PKG-vols-hotels/DALVols/DALVols.cs
using static ResaVoyages.DAL.DALGeneric.DALGeneric; using System.Data; using System.Data.SqlClient; namespace ResaVoyages.DAL.DALVols { public class DALVols { public const string SERVER_NAME = "PAUL\\SQLEXPRESS"; public const string BD_NAME = "VOLS"; public const string TABLE_NAME = "VOLS"; public DataSet GetVolById(int id) { SqlCommand command = new SqlCommand("sp_getVolById"); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@idVol", SqlDbType.Int); command.Parameters["@idVol"].Value = id; return CallSP(command, SERVER_NAME, BD_NAME, TABLE_NAME); } public DataSet GetVols() { SqlCommand command = new SqlCommand("sp_getVols"); command.CommandType = CommandType.StoredProcedure; return CallSP(command, SERVER_NAME, BD_NAME, TABLE_NAME); } public DataSet GetVolsByDepartureDateDepartureCityArrivalCity(System.DateTime dateDeparture, string departureCity, string arrivalCity) { SqlCommand command = new SqlCommand("sp_getVolsByDepartureDateDepartureCityArrivalCity"); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@departureDate", SqlDbType.DateTime); command.Parameters["@departureDate"].Value = dateDeparture; command.Parameters.Add("@departureCity", SqlDbType.VarChar); command.Parameters["@departureCity"].Value = departureCity; command.Parameters.Add("@arrivalCity", SqlDbType.VarChar); command.Parameters["@arrivalCity"].Value = arrivalCity; return CallSP(command, SERVER_NAME, BD_NAME, TABLE_NAME); } } }
using static ResaVoyages.DAL.DALGeneric.DALGeneric; using System.Data; using System.Data.SqlClient; namespace ResaVoyages.DAL.DALVols { public class DALVols { public const string SERVER_NAME = "PAUL\\SQLEXPRESS"; public const string BD_NAME = "VOLS"; public const string TABLE_NAME = "VOLS"; public DataSet GetVolById(int id) { SqlCommand command = new SqlCommand("sp_getVolById"); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@idVol", SqlDbType.Int); command.Parameters["@idVol"].Value = id; return CallSP(command, SERVER_NAME, BD_NAME, TABLE_NAME); } public DataSet GetVols() { SqlCommand command = new SqlCommand("sp_getVols"); command.CommandType = CommandType.StoredProcedure; return CallSP(command, SERVER_NAME, BD_NAME, TABLE_NAME); } } }
mit
C#
94d102865da88e8f938cd93712d4ff3783ace6f8
Remove unused code
florentbr/SeleniumBasic,florentbr/SeleniumBasic,florentbr/SeleniumBasic,florentbr/SeleniumBasic
Selenium/Internal/RunningObject.cs
Selenium/Internal/RunningObject.cs
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace Selenium.Internal { class RunningObject : IDisposable { /// <summary> /// Register a COM instance in the running table /// </summary> /// <param name="name">Regitered name</param> /// <param name="instance">Object instance</param> /// <returns></returns> public static RunningObject Register(string name, object instance) { IRunningObjectTable table; if (NativeMethods.GetRunningObjectTable(0, out table) != 0) return null; IMoniker moniker; if (NativeMethods.CreateFileMoniker(name, out moniker) != 0) return null; int id = table.Register(1, instance, moniker); if (id == 0) return null; return new RunningObject(id); } private int _id; public RunningObject(int id) { _id = id; } ~RunningObject() { this.Dispose(); } public void Dispose() { if (_id == 0) return; NativeMethods.RevokeActiveObject(_id, (IntPtr)0); } class NativeMethods { const string OLE32 = "ole32.dll"; const string OLEAUT32 = "oleaut32.dll"; [DllImport(OLE32)] public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot); [DllImport(OLE32)] public static extern int CreateFileMoniker([MarshalAs(UnmanagedType.LPWStr)] string lpszPathName , out IMoniker ppmk); [DllImport(OLEAUT32)] public static extern int RevokeActiveObject(int register, IntPtr reserved); } } }
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace Selenium.Internal { class RunningObject : IDisposable { /// <summary> /// Register a COM instance in the running table /// </summary> /// <param name="name">Regitered name</param> /// <param name="instance">Object instance</param> /// <returns></returns> public static RunningObject Register(string name, object instance) { IRunningObjectTable table; if (NativeMethods.GetRunningObjectTable(0, out table) != 0) return null; IMoniker moniker; if (NativeMethods.CreateFileMoniker(name, out moniker) != 0) return null; int id = table.Register(1, instance, moniker); if (id == 0) return null; return new RunningObject(id); } private int _id; public RunningObject(int id) { _id = id; } ~RunningObject() { this.Dispose(); } public void Dispose() { if (_id == 0) return; NativeMethods.RevokeActiveObject(_id, (IntPtr)0); } class NativeMethods { const string OLE32 = "ole32.dll"; const string OLEAUT32 = "oleaut32.dll"; [DllImport(OLE32)] public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot); [DllImport(OLE32)] public static extern int CreateFileMoniker([MarshalAs(UnmanagedType.LPWStr)] string lpszPathName , out IMoniker ppmk); [DllImport(OLEAUT32)] public static extern int RegisterActiveObject([MarshalAs(UnmanagedType.IUnknown)] object punk , ref Guid rclsid, uint dwFlags, out int pdwRegister); [DllImport(OLEAUT32)] public static extern int RevokeActiveObject(int register, IntPtr reserved); } } }
bsd-3-clause
C#
6723098b721b8e37d09c109ff02a5757017a7c29
Bump client-server versions to 2.1.0.0
zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder
Zbu.ModelsBuilder/Compatibility.cs
Zbu.ModelsBuilder/Compatibility.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Zbu.ModelsBuilder { public class Compatibility { /// <summary> /// Gets ModelsBuilder version. /// </summary> public static readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; // indicate which versions of the client API are supported by this server's API. public static readonly Version MinClientVersionSupportedByServer = new Version(2, 1, 0, 0); // indicate which versions of the server API support this client public static readonly Version MinServerVersionSupportingClient = new Version(2, 1, 0, 0); // say, version 42 adds an optional parameter to the API // min client = 40 (because we support clients that do not send the optional parameter) // min server for client 42 = 42 (because we're sending the optional parameter) // say, version 43 makes that parameter mandatory // min client = 42 (because we don't support clients that do not send the now-mandatory parameter) // min server for client 43 = 42 (because it sends the now-mandatory parameter) public static bool IsCompatible(Version clientVersion) { if (clientVersion <= Version) // if we know about this client (client older than server) return clientVersion >= MinClientVersionSupportedByServer; // check it is supported (we know) // cannot happen, newer clients should use the other API?! return false; } public static bool IsCompatible(Version clientVersion, Version minServerVersionSupportingClient) { return clientVersion <= Version // if we know about this client (client older than server) ? clientVersion >= MinClientVersionSupportedByServer // check it is supported (we know) : minServerVersionSupportingClient <= Version; // else do what client says } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Zbu.ModelsBuilder { public class Compatibility { /// <summary> /// Gets ModelsBuilder version. /// </summary> public static readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; // indicate which versions of the client API are supported by this server's API. public static readonly Version MinClientVersionSupportedByServer = new Version(2, 0, 0, 0); // indicate which versions of the server API support this client public static readonly Version MinServerVersionSupportingClient = new Version(2, 0, 0, 0); // say, version 42 adds an optional parameter to the API // min client = 40 (because we support clients that do not send the optional parameter) // min server for client 42 = 42 (because we're sending the optional parameter) // say, version 43 makes that parameter mandatory // min client = 42 (because we don't support clients that do not send the now-mandatory parameter) // min server for client 43 = 42 (because it sends the now-mandatory parameter) public static bool IsCompatible(Version clientVersion) { if (clientVersion <= Version) // if we know about this client (client older than server) return clientVersion >= MinClientVersionSupportedByServer; // check it is supported (we know) // cannot happen, newer clients should use the other API?! return false; } public static bool IsCompatible(Version clientVersion, Version minServerVersionSupportingClient) { return clientVersion <= Version // if we know about this client (client older than server) ? clientVersion >= MinClientVersionSupportedByServer // check it is supported (we know) : minServerVersionSupportingClient <= Version; // else do what client says } } }
mit
C#
7d4e46e81f745e6213d4d92fab9a606e728de09b
Test für top-level-Gremlinq config.
ExRam/ExRam.Gremlinq
test/ExRam.Gremlinq.Core.AspNet.Tests/GremlinqConfigurationSectionTests.cs
test/ExRam.Gremlinq.Core.AspNet.Tests/GremlinqConfigurationSectionTests.cs
using System.Collections.Generic; using FluentAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace ExRam.Gremlinq.Core.AspNet.Tests { public class GremlinqConfigurationSectionTests { private readonly IGremlinqConfigurationSection _section; public GremlinqConfigurationSectionTests() : base() { var serviceCollection = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { { "Gremlinq:Gremlinq_key_1", "value1" }, { "Gremlinq:Gremlinq_key_2", "value2" } }) .Build()) .AddGremlinq(s => { }) .BuildServiceProvider(); _section = serviceCollection .GetRequiredService<IGremlinqConfigurationSection>(); } [Fact] public void Indexer_can_be_null() { _section["Key"] .Should() .BeNull(); } [Fact] public void General_config() { _section["Gremlinq_key_1"] .Should() .Be("value1"); _section["Gremlinq_key_2"] .Should() .Be("value2"); } } }
using FluentAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace ExRam.Gremlinq.Core.AspNet.Tests { public class GremlinqConfigurationSectionTests { private readonly IGremlinqConfigurationSection _section; public GremlinqConfigurationSectionTests() : base() { var serviceCollection = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder() .AddInMemoryCollection() .Build()) .AddGremlinq(s => { }) .BuildServiceProvider(); _section = serviceCollection .GetRequiredService<IGremlinqConfigurationSection>(); } [Fact] public void Indexer_can_be_null() { _section["Key"] .Should() .BeNull(); } } }
mit
C#
1b7e31b03fbcc506472921a4e2d8f5bcaa0a0a91
increase version
tinohager/Nager.AmazonProductAdvertising,tinohager/Nager.AmazonProductAdvertising
Nager.AmazonProductAdvertising/Properties/AssemblyInfo.cs
Nager.AmazonProductAdvertising/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Nager.AmazonProductAdvertising")] [assembly: AssemblyDescription("Amazon ProductAdvertising")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("nager.at")] [assembly: AssemblyProduct("Nager.AmazonProductAdvertising")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("026a9ee3-9a48-48a1-9026-1573f2e8a85e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.9.0")] [assembly: AssemblyFileVersion("1.0.9.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Nager.AmazonProductAdvertising")] [assembly: AssemblyDescription("Amazon ProductAdvertising")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("nager.at")] [assembly: AssemblyProduct("Nager.AmazonProductAdvertising")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("026a9ee3-9a48-48a1-9026-1573f2e8a85e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.8.0")] [assembly: AssemblyFileVersion("1.0.8.0")]
mit
C#
bcb98a4d7762fb3ec6d7953ddb77aa7a27f88010
Tweak GroupBox preferred sizing (again)
PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1
Source/Eto.Platform.Mac/Forms/Controls/GroupBoxHandler.cs
Source/Eto.Platform.Mac/Forms/Controls/GroupBoxHandler.cs
using System; using Eto.Forms; using MonoMac.AppKit; using SD = System.Drawing; using Eto.Drawing; using Eto.Platform.Mac.Drawing; namespace Eto.Platform.Mac.Forms.Controls { public class GroupBoxHandler : MacContainer<NSBox, GroupBox>, IGroupBox { Font font; public class EtoBox : NSBox, IMacControl { public object Handler { get; set; } } public GroupBoxHandler () { Control = new EtoBox { Handler = this }; Control.Title = string.Empty; Control.ContentView = new NSView (); Enabled = true; } public override object ContainerObject { get { return Control.ContentView; } } public override bool Enabled { get; set; } public override Eto.Drawing.Size ClientSize { get { var view = Control.ContentView as NSView; return view.Frame.Size.ToEtoSize (); } set { Control.SetFrameFromContentFrame (new System.Drawing.RectangleF (0, 0, value.Width, value.Height)); } } public Font Font { get { if (font == null) font = new Font (Widget.Generator, new FontHandler (Control.TitleFont)); return font; } set { font = value; if (font != null) Control.TitleFont = ((FontHandler)font.Handler).Control; else Control.TitleFont = null; LayoutIfNeeded (); } } public virtual string Text { get { return Control.Title; } set { Control.Title = value; } } public override Eto.Drawing.Size GetPreferredSize (Size availableSize) { return base.GetPreferredSize (availableSize) + new Size (14, (int)(Control.TitleFont.LineHeight () + 9)); } public override void SetContentSize (SD.SizeF contentSize) { Control.SetFrameFromContentFrame (new System.Drawing.RectangleF (0, 0, contentSize.Width, contentSize.Height)); } } }
using System; using Eto.Forms; using MonoMac.AppKit; using SD = System.Drawing; using Eto.Drawing; using Eto.Platform.Mac.Drawing; namespace Eto.Platform.Mac.Forms.Controls { public class GroupBoxHandler : MacContainer<NSBox, GroupBox>, IGroupBox { Font font; public class EtoBox : NSBox, IMacControl { public object Handler { get; set; } } public GroupBoxHandler () { Control = new EtoBox { Handler = this }; Control.Title = string.Empty; Control.ContentView = new NSView (); Enabled = true; } public override object ContainerObject { get { return Control.ContentView; } } public override bool Enabled { get; set; } public override Eto.Drawing.Size ClientSize { get { var view = Control.ContentView as NSView; return view.Frame.Size.ToEtoSize (); } set { Control.SetFrameFromContentFrame (new System.Drawing.RectangleF (0, 0, value.Width, value.Height)); } } public Font Font { get { if (font == null) font = new Font (Widget.Generator, new FontHandler (Control.TitleFont)); return font; } set { font = value; if (font != null) Control.TitleFont = ((FontHandler)font.Handler).Control; else Control.TitleFont = null; LayoutIfNeeded (); } } public virtual string Text { get { return Control.Title; } set { Control.Title = value; } } public override Eto.Drawing.Size GetPreferredSize (Size availableSize) { return base.GetPreferredSize (availableSize) + new Size (14, (int)(Control.TitleFont.LineHeight () * 1.4)); } public override void SetContentSize (SD.SizeF contentSize) { Control.SetFrameFromContentFrame (new System.Drawing.RectangleF (0, 0, contentSize.Width, contentSize.Height)); } } }
bsd-3-clause
C#
06d0d6723a69e61963c1d57ba244fdff05fc1ddd
Add support for IEnumerable in android adapters
Julien-Mialon/StormXamarin,snipervld/StormXamarin,snipervld/StormXamarin,Julien-Mialon/StormXamarin,snipervld/StormXamarin,Julien-Mialon/StormXamarin
StormXamarin/Storm.Mvvm.Android.Shared/BindableAdapter.cs
StormXamarin/Storm.Mvvm.Android.Shared/BindableAdapter.cs
using System; using System.Collections; using System.Collections.Specialized; using System.Linq; using Android.Views; using Android.Widget; using Storm.Mvvm.Interfaces; namespace Storm.Mvvm { public class BindableAdapter : BaseAdapter<object>, IMvvmAdapter, ISearchableAdapter { private ITemplateSelector _templateSelector; private IList _collection; public object Collection { get { return _collection; } set { if (!object.Equals(_collection, value)) { Unregister(_collection); _collection = value as IList; if (_collection == null) { if (value is IEnumerable) { _collection = ToIList((IEnumerable) value); } else if (value != null) { throw new InvalidOperationException("Binding with adapter only support collection binding which implement IEnumerable or IList"); } } Register(_collection); NotifyDataChanged(); } } } public ITemplateSelector TemplateSelector { get { return _templateSelector; } set { if (!object.Equals(_templateSelector, value)) { _templateSelector = value; NotifyDataChanged(); } } } public override object this[int position] { get { if (_collection == null || position < 0 || position >= _collection.Count) { return null; } return _collection[position]; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { return TemplateSelector.GetView(this[position], parent, convertView); } public override int Count { get { return _collection == null ? 0 : _collection.Count; } } public int IndexOf(object value) { return _collection == null ? -1 : _collection.IndexOf(value); } private void Unregister(object collection) { INotifyCollectionChanged observable = collection as INotifyCollectionChanged; if (observable != null) { observable.CollectionChanged -= OnCollectionChanged; } } private void Register(object collection) { INotifyCollectionChanged observable = collection as INotifyCollectionChanged; if (observable != null) { observable.CollectionChanged += OnCollectionChanged; } } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { NotifyDataChanged(); } private void NotifyDataChanged() { if (TemplateSelector != null) { NotifyDataSetChanged(); } } private IList ToIList(IEnumerable source) { ArrayList result = new ArrayList(); foreach (object item in source) { result.Add(item); } return result; } } }
using System.Collections; using System.Collections.Specialized; using Android.Views; using Android.Widget; using Storm.Mvvm.Interfaces; namespace Storm.Mvvm { public class BindableAdapter : BaseAdapter<object>, IMvvmAdapter, ISearchableAdapter { private ITemplateSelector _templateSelector; private IList _collection; public object Collection { get { return _collection; } set { if (!object.Equals(_collection, value)) { Unregister(_collection); _collection = value as IList; Register(_collection); NotifyDataChanged(); } } } public ITemplateSelector TemplateSelector { get { return _templateSelector; } set { if (!object.Equals(_templateSelector, value)) { _templateSelector = value; NotifyDataChanged(); } } } public override object this[int position] { get { if (_collection == null || position < 0 || position >= _collection.Count) { return null; } return _collection[position]; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { return TemplateSelector.GetView(this[position], parent, convertView); } public override int Count { get { return _collection == null ? 0 : _collection.Count; } } public int IndexOf(object value) { return _collection == null ? -1 : _collection.IndexOf(value); } private void Unregister(object collection) { INotifyCollectionChanged observable = collection as INotifyCollectionChanged; if (observable != null) { observable.CollectionChanged -= OnCollectionChanged; } } private void Register(object collection) { INotifyCollectionChanged observable = collection as INotifyCollectionChanged; if (observable != null) { observable.CollectionChanged += OnCollectionChanged; } } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { NotifyDataChanged(); } private void NotifyDataChanged() { if (TemplateSelector != null) { NotifyDataSetChanged(); } } } }
mit
C#
3efb97e307b38d9d5f1868133958855ee461e05b
Use MirroringPackageRepository to auto-mirror packages in OData lookup.
googol/NuGet.Lucene,Stift/NuGet.Lucene,themotleyfool/NuGet.Lucene
source/NuGet.Lucene.Web/Controllers/PackagesODataController.cs
source/NuGet.Lucene.Web/Controllers/PackagesODataController.cs
using System.Linq; using System.Web.Http; using System.Web.Http.OData; using NuGet.Lucene.Web.Models; using NuGet.Lucene.Web.Util; namespace NuGet.Lucene.Web.Controllers { /// <summary> /// OData provider for Lucene based NuGet package repository. /// </summary> public class PackagesODataController : ODataController { public ILucenePackageRepository Repository { get; set; } public IMirroringPackageRepository MirroringRepository { get; set; } [Queryable] public IQueryable<ODataPackage> Get() { return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable(); } public object Get([FromODataUri] string id, [FromODataUri] string version) { SemanticVersion semanticVersion; if (!SemanticVersion.TryParse(version, out semanticVersion)) { return BadRequest("Invalid version"); } if (string.IsNullOrWhiteSpace(id)) { return BadRequest("Invalid package id"); } var package = MirroringRepository.FindPackage(id, semanticVersion); return package == null ? (object)NotFound() : package.AsDataServicePackage(); } } }
using System.Linq; using System.Web.Http; using System.Web.Http.OData; using NuGet.Lucene.Web.Models; using NuGet.Lucene.Web.Util; namespace NuGet.Lucene.Web.Controllers { /// <summary> /// OData provider for Lucene based NuGet package repository. /// </summary> public class PackagesODataController : ODataController { public ILucenePackageRepository Repository { get; set; } [Queryable] public IQueryable<ODataPackage> Get() { return Repository.LucenePackages.Select(p => p.AsDataServicePackage()).AsQueryable(); } public object Get([FromODataUri] string id, [FromODataUri] string version) { SemanticVersion semanticVersion; if (!SemanticVersion.TryParse(version, out semanticVersion)) { return BadRequest("Invalid version"); } if (string.IsNullOrWhiteSpace(id)) { return BadRequest("Invalid package id"); } var package = Repository.FindPackage(id, semanticVersion); return package == null ? (object)NotFound() : package.AsDataServicePackage(); } } }
apache-2.0
C#
e7608f4b1256b0d33b6c3135de9b36a0e1af1874
Update BasketController.cs
productinfo/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers
src/Services/Basket/Basket.API/Controllers/BasketController.cs
src/Services/Basket/Basket.API/Controllers/BasketController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.AspNetCore.Authorization; namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers { [Route("/")] [Authorize] public class BasketController : Controller { private IBasketRepository _repository; public BasketController(IBasketRepository repository) { _repository = repository; } // GET api/values/5 [HttpGet("{id}")] public async Task<IActionResult> Get(string id) { var basket = await _repository.GetBasketAsync(id); return Ok(basket); } // POST api/values [HttpPost] public async Task<IActionResult> Post([FromBody]CustomerBasket value) { var basket = await _repository.UpdateBasketAsync(value); return Ok(basket); } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(string id) { _repository.DeleteBasketAsync(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.AspNetCore.Authorization; namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers { //TODO NOTE: Right now this is a very chunky API, as the app evolves it is possible we would //want to make the actions more fine grained, add basket item as an action for example. //If this is the case we should also investigate changing the serialization format used for Redis, //using a HashSet instead of a simple string. [Route("/")] [Authorize] public class BasketController : Controller { private IBasketRepository _repository; public BasketController(IBasketRepository repository) { _repository = repository; } // GET api/values/5 [HttpGet("{id}")] public async Task<IActionResult> Get(string id) { var basket = await _repository.GetBasketAsync(id); return Ok(basket); } // POST api/values [HttpPost] public async Task<IActionResult> Post([FromBody]CustomerBasket value) { var basket = await _repository.UpdateBasketAsync(value); return Ok(basket); } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(string id) { _repository.DeleteBasketAsync(id); } } }
mit
C#
df48ee1f63ecf71b25e9ef824aa3a4af831d1ee2
Update CameraEffectControlScript.cs
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Camera/CameraEffectControlScript.cs
UnityProject/Assets/Scripts/Camera/CameraEffectControlScript.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CameraEffects { public class CameraEffectControlScript : MonoBehaviour { public DrunkCamera drunkCamera; public GlitchEffect glitchEffect; public NightVisionCamera nightVisionCamera; public void ToggleDrunkEffectState() { drunkCamera.enabled = !drunkCamera.enabled; } public void ToggleGlitchEffectState() { glitchEffect.enabled = !glitchEffect.enabled; } public void ToggleNightVisionEffectState() { nightVisionCamera.enabled = !nightVisionCamera.enabled; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CameraEffects { public class CameraEffectControlScript : MonoBehaviour { public DrunkCamera drunkCamera; public GlitchEffect glitchEffect; public NightVisionCamera nightVisionCamera; public void ChangeDrunkState() { drunkCamera.enabled = !drunkCamera.enabled; } public void ChangeGlitchState() { glitchEffect.enabled = !glitchEffect.enabled; } public void ChangeNightVisionState() { nightVisionCamera.enabled = !nightVisionCamera.enabled; } } }
agpl-3.0
C#
4928e5fefacaa1ca80bcda66eb78a3926c104c6a
Add quotes when searching with an order ID in BO.
ChalmersLibrary/Chillin,ChalmersLibrary/Chillin,ChalmersLibrary/Chillin,ChalmersLibrary/Chillin
Chalmers.ILL/Controllers/SurfaceControllers/Page/ChalmersILLOrderListPageController.cs
Chalmers.ILL/Controllers/SurfaceControllers/Page/ChalmersILLOrderListPageController.cs
using Chalmers.ILL.Members; using Chalmers.ILL.Models.Page; using Chalmers.ILL.OrderItems; using System; using System.Text.RegularExpressions; using System.Web.Mvc; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Chalmers.ILL.Controllers.SurfaceControllers.Page { public class ChalmersILLOrderListPageController : RenderMvcController { IMemberInfoManager _memberInfoManager; IOrderItemSearcher _orderItemSearcher; public ChalmersILLOrderListPageController(IMemberInfoManager memberInfoManager, IOrderItemSearcher orderItemSearcher) { _memberInfoManager = memberInfoManager; _orderItemSearcher = orderItemSearcher; } public override ActionResult Index(RenderModel model) { var customModel = new ChalmersILLOrderListPageModel(); _memberInfoManager.PopulateModelWithMemberData(Request, Response, customModel); if (!String.IsNullOrEmpty(Request.QueryString["query"])) { var queryString = Request.QueryString["query"].Trim(); if (IsOrderId(queryString)) { queryString = "\"" + queryString + "\""; } customModel.PendingOrderItems = _orderItemSearcher.Search(queryString); } else { customModel.PendingOrderItems = _orderItemSearcher.Search(@"status:01\:Ny OR status:02\:Åtgärda OR status:09\:Mottagen OR (status:03\:Beställd AND followUpDate:[1975-01-01T00:00:00.000Z TO " + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + @"]) OR (status:14\:Infodisk AND dueDate:[1975-01-01T00:00:00.000Z TO " + DateTime.Now.AddDays(5).Date.ToString("yyyy-MM-ddT") + @"23:59:59.999Z])"); } return CurrentTemplate(customModel); } #region Private methods private bool IsOrderId(string text) { var orderIdPattern = new Regex("^cthb-[a-zA-Z0-9]{8}-[0-9]+$"); return orderIdPattern.IsMatch(text); } #endregion } }
using Chalmers.ILL.Members; using Chalmers.ILL.Models.Page; using Chalmers.ILL.OrderItems; using System; using System.Web.Mvc; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Chalmers.ILL.Controllers.SurfaceControllers.Page { public class ChalmersILLOrderListPageController : RenderMvcController { IMemberInfoManager _memberInfoManager; IOrderItemSearcher _orderItemSearcher; public ChalmersILLOrderListPageController(IMemberInfoManager memberInfoManager, IOrderItemSearcher orderItemSearcher) { _memberInfoManager = memberInfoManager; _orderItemSearcher = orderItemSearcher; } public override ActionResult Index(RenderModel model) { var customModel = new ChalmersILLOrderListPageModel(); _memberInfoManager.PopulateModelWithMemberData(Request, Response, customModel); if (!String.IsNullOrEmpty(Request.QueryString["query"])) { customModel.PendingOrderItems = _orderItemSearcher.Search(Request.Params["query"].ToString()); } else { customModel.PendingOrderItems = _orderItemSearcher.Search(@"status:01\:Ny OR status:02\:Åtgärda OR status:09\:Mottagen OR (status:03\:Beställd AND followUpDate:[1975-01-01T00:00:00.000Z TO " + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + @"]) OR (status:14\:Infodisk AND dueDate:[1975-01-01T00:00:00.000Z TO " + DateTime.Now.AddDays(5).Date.ToString("yyyy-MM-ddT") + @"23:59:59.999Z])"); } return CurrentTemplate(customModel); } } }
mit
C#
a8c8eb6b85bdee6cfdcdc1d2e3899e074b2be658
Fix spelling
abstractspoon/ToDoList_Plugins,abstractspoon/ToDoList_Plugins,abstractspoon/ToDoList_Plugins
UIExension/WordCloudUIExtension/CloudControl/TextAnalyses/Blacklist/CommonBlacklist.cs
UIExension/WordCloudUIExtension/CloudControl/TextAnalyses/Blacklist/CommonBlacklist.cs
using System; using System.Collections.Generic; using System.IO; namespace Gma.CodeCloud.Controls.TextAnalyses.Blacklist { public class CommonBlacklist : IBlacklist { private readonly HashSet<string> m_ExcludedWordsHashSet; public CommonBlacklist() : this(new string[] {}) { } public CommonBlacklist(IEnumerable<string> excludedWords) : this(excludedWords, StringComparer.InvariantCultureIgnoreCase) { } public static IBlacklist CreateFromTextFile(string fileName) { return !File.Exists(fileName) ? new NullBlacklist() : CreateFromStreamReader(new FileInfo(fileName).OpenText()); } public static IBlacklist CreateFromStreamReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); CommonBlacklist commonBlacklist = new CommonBlacklist(); using (reader) { string line = reader.ReadLine(); while (line != null) { line.Trim(); commonBlacklist.Add(line); line = reader.ReadLine(); } } return commonBlacklist; } public CommonBlacklist(IEnumerable<string> excludedWords, StringComparer comparer) { m_ExcludedWordsHashSet = new HashSet<string>(excludedWords, comparer); } public bool Countains(string word) { return m_ExcludedWordsHashSet.Contains(word); } public void Add(string line) { m_ExcludedWordsHashSet.Add(line); } public int Count { get { return m_ExcludedWordsHashSet.Count; } } } }
using System; using System.Collections.Generic; using System.IO; namespace Gma.CodeCloud.Controls.TextAnalyses.Blacklist { public class CommonBlacklist : IBlacklist { private readonly HashSet<string> m_ExcludedWordsHashSet; public CommonBlacklist() : this(new string[] {}) { } public CommonBlacklist(IEnumerable<string> excludedWords) : this(excludedWords, StringComparer.InvariantCultureIgnoreCase) { } public static IBlacklist CreateFromTextFile(string fileName) { return !File.Exists(fileName) ? new NullBlacklist() : CreateFromStremReader(new FileInfo(fileName).OpenText()); } public static IBlacklist CreateFromStremReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); CommonBlacklist commonBlacklist = new CommonBlacklist(); using (reader) { string line = reader.ReadLine(); while (line != null) { line.Trim(); commonBlacklist.Add(line); line = reader.ReadLine(); } } return commonBlacklist; } public CommonBlacklist(IEnumerable<string> excludedWords, StringComparer comparer) { m_ExcludedWordsHashSet = new HashSet<string>(excludedWords, comparer); } public bool Countains(string word) { return m_ExcludedWordsHashSet.Contains(word); } public void Add(string line) { m_ExcludedWordsHashSet.Add(line); } public int Count { get { return m_ExcludedWordsHashSet.Count; } } } }
epl-1.0
C#
03d07ad80384d7e30f2c8f4ec81fe8701401f4c8
Add [Fact] attribute to a test that was missing it, regaining coverage.
LHCGreg/mal-api,LHCGreg/mal-api
MalApi.IntegrationTests/GetRecentOnlineUsersTest.cs
MalApi.IntegrationTests/GetRecentOnlineUsersTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace MalApi.IntegrationTests { public class GetRecentOnlineUsersTest { [Fact] public void GetRecentOnlineUsers() { using (MyAnimeListApi api = new MyAnimeListApi()) { RecentUsersResults results = api.GetRecentOnlineUsers(); Assert.NotEmpty(results.RecentUsers); } } } } /* Copyright 2017 Greg Najda Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace MalApi.IntegrationTests { public class GetRecentOnlineUsersTest { public void GetRecentOnlineUsers() { using (MyAnimeListApi api = new MyAnimeListApi()) { RecentUsersResults results = api.GetRecentOnlineUsers(); Assert.NotEmpty(results.RecentUsers); } } } } /* Copyright 2017 Greg Najda 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. */
apache-2.0
C#
97525abb2ab11ceafe10b17c907860eb22232ecb
fix ScopedOption NotImplementedException
AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/Abstractions
src/ScopedContext/src/AspectCore.Extensions.ScopedContext/ScopedInterceptorAttribute.cs
src/ScopedContext/src/AspectCore.Extensions.ScopedContext/ScopedInterceptorAttribute.cs
using System; using AspectCore.Abstractions; namespace AspectCore.Extensions.ScopedContext { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] [NonAspect] public abstract class ScopedInterceptorAttribute : InterceptorAttribute, IScopedInterceptor { public virtual ScopedOptions ScopedOption { get; set; } = ScopedOptions.None; } }
using System; using AspectCore.Abstractions; namespace AspectCore.Extensions.ScopedContext { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] [NonAspect] public abstract class ScopedInterceptorAttribute : InterceptorAttribute, IScopedInterceptor { public ScopedOptions ScopedOption { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } } }
mit
C#
ce3ed8473a1318d205e599e0551b824741a263a1
fix defer: true by default
riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm
src/DotVVM.Framework/ResourceManagement/ScriptResource.cs
src/DotVVM.Framework/ResourceManagement/ScriptResource.cs
#nullable enable using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.Controls; using DotVVM.Framework.Hosting; namespace DotVVM.Framework.ResourceManagement { /// <summary> /// Reference to a javascript file. /// </summary> public class ScriptResource : LinkResourceBase, IPreloadResource, IDeferableResource { public bool Defer { get; } public ScriptResource(IResourceLocation location, bool defer = true) : base(defer ? ResourceRenderPosition.Anywhere : ResourceRenderPosition.Body, "text/javascript", location) { this.Defer = defer; } /// <summary>Location property is required!</summary> public ScriptResource() : this(location: null!) // hack: people assign the Location property late, but it should non-nullable... { } public override void RenderLink(IResourceLocation location, IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { AddSrcAndIntegrity(writer, context, location.GetUrl(context, resourceName), "src"); if (MimeType != "text/javascript") // this is the default, no need to write it writer.AddAttribute("type", MimeType); if (Defer) writer.AddAttribute("defer", null); writer.RenderBeginTag("script"); writer.RenderEndTag(); } public void RenderPreloadLink(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { writer.AddAttribute("rel", "preload"); writer.AddAttribute("href", Location.GetUrl(context, resourceName)); writer.AddAttribute("as", "script"); writer.RenderBeginTag("link"); writer.RenderEndTag(); } } }
#nullable enable using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.Controls; using DotVVM.Framework.Hosting; namespace DotVVM.Framework.ResourceManagement { /// <summary> /// Reference to a javascript file. /// </summary> public class ScriptResource : LinkResourceBase, IPreloadResource, IDeferableResource { public bool Defer { get; } public ScriptResource(IResourceLocation location, bool defer = true) : base(defer ? ResourceRenderPosition.Anywhere : ResourceRenderPosition.Body, "text/javascript", location) { this.Defer = defer; } /// <summary>Location property is required!</summary> public ScriptResource() : base(ResourceRenderPosition.Body, "text/javascript") { } public override void RenderLink(IResourceLocation location, IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { AddSrcAndIntegrity(writer, context, location.GetUrl(context, resourceName), "src"); if (MimeType != "text/javascript") // this is the default, no need to write it writer.AddAttribute("type", MimeType); if (Defer) writer.AddAttribute("defer", null); writer.RenderBeginTag("script"); writer.RenderEndTag(); } public void RenderPreloadLink(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName) { writer.AddAttribute("rel", "preload"); writer.AddAttribute("href", Location.GetUrl(context, resourceName)); writer.AddAttribute("as", "script"); writer.RenderBeginTag("link"); writer.RenderEndTag(); } } }
apache-2.0
C#
435202db616c617bf2bdbb6cb7fbe81a3ebcc069
Fix the long initializer test case that was failing
shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,weltkante/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,mavasani/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,weltkante/roslyn,dotnet/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn
src/EditorFeatures/CSharpTest/Wrapping/InitializerExpressionWrappingTests.cs
src/EditorFeatures/CSharpTest/Wrapping/InitializerExpressionWrappingTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class IntializerExpressionWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestNoWrappingSuggestions() { await TestMissingAsync( @"class C { void Bar() { var test = new[] [||]{ 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWrappingShortInitializerExpression() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var test = new[] [||]{ 1, 2 }; } }", @"class C { void Bar() { var test = new[] { 1, 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWrappingLongIntializerExpression() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var test = new[] [||]{ ""the"", ""quick"", ""brown"", ""fox"", ""jumps"", ""over"", ""the"", ""lazy"", ""dog"" }; } }", @"class C { void Bar() { var test = new[] { ""the"", ""quick"", ""brown"", ""fox"", ""jumps"", ""over"", ""the"", ""lazy"", ""dog"" }; } }", @"class C { void Bar() { var test = new[] { ""the"", ""quick"", ""brown"", ""fox"", ""jumps"", ""over"", ""the"", ""lazy"", ""dog"" }; } }" ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class IntializerExpressionWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestNoWrappingSuggestions() { await TestMissingAsync( @"class C { void Bar() { var test = new[] [||]{ 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWrappingShortInitializerExpression() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var test = new[] [||]{ 1, 2 }; } }", @"class C { void Bar() { var test = new[] { 1, 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWrappingLongIntializerExpression() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var test = new[] [||]{ ""the"", ""quick"", ""brown"", ""fox"", ""jumps"", ""over"", ""the"", ""lazy"", ""dog"" }; } }", @"class C { void Bar() { var test = new[] { ""the"", ""quick"", ""brown"", ""fox"", ""jumps"", ""over"", ""the"", ""lazy"", ""dog""}; } }", @"class C { void Bar() { var test = new[] { ""the"",""quick"",""brown"",""fox"",""jumps"",""over"",""the"",""lazy"",""dog""}; } }" ); } } }
mit
C#
dc5ef02e6d474ca1582cfd4a93f2da8196dce3a9
Fix typo in `OnCrashOnly` documentation
Topshelf/Topshelf
src/Topshelf/Configuration/ServiceRecoveryConfigurator.cs
src/Topshelf/Configuration/ServiceRecoveryConfigurator.cs
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 Topshelf { public interface ServiceRecoveryConfigurator { /// <summary> /// Restart the service after waiting the delay period specified /// </summary> /// <param name="delayInMinutes"> </param> ServiceRecoveryConfigurator RestartService(int delayInMinutes); /// <summary> /// Restart the computer after waiting the delay period in minutes /// </summary> /// <param name="delayInMinutes"> </param> /// <param name="message"> </param> ServiceRecoveryConfigurator RestartComputer(int delayInMinutes, string message); /// <summary> /// Run the command specified /// </summary> /// <param name="delayInMinutes"> </param> /// <param name="command"> </param> ServiceRecoveryConfigurator RunProgram(int delayInMinutes, string command); /// <summary> /// Specifies the reset period for the restart options /// </summary> /// <param name="days"> </param> ServiceRecoveryConfigurator SetResetPeriod(int days); /// <summary> /// Specifies that the recovery actions should only be taken on a service crash. If the service exits /// with a non-zero exit code, it will not be restarted. /// </summary> void OnCrashOnly(); } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 Topshelf { public interface ServiceRecoveryConfigurator { /// <summary> /// Restart the service after waiting the delay period specified /// </summary> /// <param name="delayInMinutes"> </param> ServiceRecoveryConfigurator RestartService(int delayInMinutes); /// <summary> /// Restart the computer after waiting the delay period in minutes /// </summary> /// <param name="delayInMinutes"> </param> /// <param name="message"> </param> ServiceRecoveryConfigurator RestartComputer(int delayInMinutes, string message); /// <summary> /// Run the command specified /// </summary> /// <param name="delayInMinutes"> </param> /// <param name="command"> </param> ServiceRecoveryConfigurator RunProgram(int delayInMinutes, string command); /// <summary> /// Specifies the reset period for the restart options /// </summary> /// <param name="days"> </param> ServiceRecoveryConfigurator SetResetPeriod(int days); /// <summary> /// Specifies that the recovery actions should only be taken on a service crash. If the service exists /// with a non-zero exit code, it will not be restarted. /// </summary> void OnCrashOnly(); } }
apache-2.0
C#
635b4b315d30728d2aaae6718f592d9f7a397581
fix spelling mistake
WilliamsJason/WindowsDevicePortalWrapper-1,davidkline-ms/WindowsDevicePortalWrapper,c-don/WindowsDevicePortalWrapper,hpsin/WindowsDevicePortalWrapper
WindowsDevicePortalWrapper/WindowsDevicePortalWrapper/Core/AppFileExplorer.cs
WindowsDevicePortalWrapper/WindowsDevicePortalWrapper/Core/AppFileExplorer.cs
//---------------------------------------------------------------------------------------------- // <copyright file="AppFileExplorer.cs" company="Microsoft Corporation"> // Licensed under the MIT License. See LICENSE.TXT in the project root license information. // </copyright> //---------------------------------------------------------------------------------------------- namespace Microsoft.Tools.WindowsDevicePortal { /// <content> /// Wrappers for App File explorer methods /// </content> public partial class DevicePortal { /// <summary> /// API to upload, download or delete a file in a folder. /// </summary> private static readonly string GetFileApi = "api/filesystem/apps/file"; /// <summary> /// API to retrieve the list of files in a folder. /// </summary> private static readonly string GetFilesApi = "api/filesystem/apps/files"; /// <summary> /// API to retrieve the list of accessible top-level folders. /// </summary> private static readonly string KnownFoldersApi = "api/filesystem/apps/knownfolders"; } }
//---------------------------------------------------------------------------------------------- // <copyright file="AppFileExplorer.cs" company="Microsoft Corporation"> // Licensed under the MIT License. See LICENSE.TXT in the project root license information. // </copyright> //---------------------------------------------------------------------------------------------- namespace Microsoft.Tools.WindowsDevicePortal { /// <content> /// Wrappers for App File explorer methods /// </content> public partial class DevicePortal { /// <summary> /// API to upload, download or delete a file in a folder. /// </summary> private static readonly string GetFileApi = "api/filesystem/apps/file"; /// <summary> /// API to retrieve the list of files in a folder. /// </summary> private static readonly string GetFilesApi = "api/filesystem/apps/files"; /// <summary> /// API to retrieve the list of accessible top-level folders. /// </summary> private static readonly string KnownFoldersApi = "api/filesystem/apps/knownfilders"; } }
mit
C#
3aaa3f4a2141ab3952538963a93a704656687d6c
replace version in RoundRobinAddressRouterShould.cs
lvermeulen/Equalizer
test/Equalizer.Nanophone.Tests/RoundRobinAddressRouterShould.cs
test/Equalizer.Nanophone.Tests/RoundRobinAddressRouterShould.cs
using System; using System.Collections.Generic; using Nanophone.Core; using Xunit; namespace Equalizer.Nanophone.Tests { public class RoundRobinAddressRouterShould { [Fact] public void WrapAround() { var oneDotOne = new RegistryInformation("1", 1234, "some version"); var oneDotTwo = new RegistryInformation("1", 1234, "some version"); var twoDotOne = new RegistryInformation("2", 1234, "some version"); var twoDotTwo = new RegistryInformation("2", 1234, "some version"); var threeDotOne = new RegistryInformation("3", 1234, "some version"); var threeDotTwo = new RegistryInformation("3", 1234, "some version"); var instances = new List<RegistryInformation> { oneDotOne, oneDotTwo, twoDotOne, twoDotTwo, threeDotOne, threeDotTwo }; var router = new RoundRobinAddressRouter(); // choose first var next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("1", next.Address); // choose next next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("2", next.Address); // choose next next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("3", next.Address); // choose first next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("1", next.Address); } } }
using System; using System.Collections.Generic; using Nanophone.Core; using Xunit; namespace Equalizer.Nanophone.Tests { public class RoundRobinAddressRouterShould { [Fact] public void WrapAround() { var oneDotOne = new RegistryInformation("1", 1234, "v2.7"); var oneDotTwo = new RegistryInformation("1", 1234, "v2.7"); var twoDotOne = new RegistryInformation("2", 1234, "v2.7"); var twoDotTwo = new RegistryInformation("2", 1234, "v2.7"); var threeDotOne = new RegistryInformation("3", 1234, "v2.7"); var threeDotTwo = new RegistryInformation("3", 1234, "v2.7"); var instances = new List<RegistryInformation> { oneDotOne, oneDotTwo, twoDotOne, twoDotTwo, threeDotOne, threeDotTwo }; var router = new RoundRobinAddressRouter(); // choose first var next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("1", next.Address); // choose next next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("2", next.Address); // choose next next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("3", next.Address); // choose first next = router.Choose(instances); Assert.NotNull(next); Assert.Equal("1", next.Address); } } }
mit
C#
8cbf657c48acd8f0241918f5bfcd0c74519603fb
update searchUI test
grenade/NuGetGallery_download-count-patch,mtian/SiteExtensionGallery,ScottShingler/NuGetGallery,projectkudu/SiteExtensionGallery,skbkontur/NuGetGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,projectkudu/SiteExtensionGallery,mtian/SiteExtensionGallery,ScottShingler/NuGetGallery,skbkontur/NuGetGallery,grenade/NuGetGallery_download-count-patch,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery
tests/NuGetGallery.FunctionalTests.Fluent/SearchUITest.cs
tests/NuGetGallery.FunctionalTests.Fluent/SearchUITest.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using NuGetGallery.FunctionTests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAutomation; namespace NuGetGallery.FunctionalTests.Fluent { [TestClass] public class SearchUITest : NuGetFluentTest { [TestMethod] [Description("Verify focus scenarios for the search box.")] public void SearchUI() { // This test made more sense back when our search box expanded and contracted. // Now the width of the search box is 650. Update the test, so it verifies the width is large enough. // Go to the front page. I.Open(UrlHelper.BaseUrl); // Click in the box I.Click("#searchBoxInput", 3, 3); I.Wait(1); I.Expect.True(() => (I.Find("#searchBoxInput")().Width > 600)); I.Type("fred"); I.Wait(1); I.Expect.True(() => (I.Find("#searchBoxInput")().Width > 600)); // Click out of the box I.Click("img[alt='Manage NuGet Packages Dialog Window']", 3, 3); I.Expect.True(() => (I.Find("#searchBoxInput")().Width > 600)); I.Wait(1); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using NuGetGallery.FunctionTests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAutomation; namespace NuGetGallery.FunctionalTests.Fluent { [TestClass] public class SearchUITest : NuGetFluentTest { [TestMethod] [Description("Verify focus scenarios for the search box.")] public void SearchUI() { // This test made more sense back when our search box expanded and contracted. // Go to the front page. I.Open(UrlHelper.BaseUrl); // Click in the box I.Click("#searchBoxInput", 3, 3); I.Wait(1); I.Expect.True(() => (I.Find("#searchBoxInput")().Width > 200)); I.Type("fred"); I.Wait(1); I.Expect.True(() => (I.Find("#searchBoxInput")().Width > 200)); // Click out of the box I.Click("img[alt='Manage NuGet Packages Dialog Window']", 3, 3); I.Expect.True(() => (I.Find("#searchBoxInput")().Width > 200)); I.Wait(1); } } }
apache-2.0
C#
57558ccbe93e171741f83bd73de7bc299dc44fb2
Refactor NumberOfClassificationSystemsTest
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade.Test/Tests/Noark5/NumberOfClassificationSystemsTest.cs
src/Arkivverket.Arkade.Test/Tests/Noark5/NumberOfClassificationSystemsTest.cs
using System; using System.IO; using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Tests.Noark5 { public class NumberOfClassificationSystemsTest : IDisposable { private Stream _archiveContent; private TestResults RunTest() { return new NumberOfClassificationSystems(new ArchiveContentMemoryStreamReader(_archiveContent)).RunTest(new ArchiveExtraction("123", "")); } [Fact] public void NumberOfClassificationSystemsIsOne() { _archiveContent = new ArchiveBuilder().WithArchivePart().WithClassificationSystem().Build(); TestResults testResults = RunTest(); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("1"); } [Fact] public void NumberOfClassificationSystemsIsTwo() { _archiveContent = new ArchiveBuilder() .WithArchivePart("part 1").WithClassificationSystem("classification system 1") .WithArchivePart("part 2").WithClassificationSystem("classification system 2") .Build(); TestResults testResults = RunTest(); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("2"); } public void Dispose() { _archiveContent.Dispose(); } } }
using System; using System.IO; using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Tests; using Arkivverket.Arkade.Tests.Noark5; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Test.Tests.Noark5 { public class NumberOfClassificationSystemsTest : IDisposable { private Stream _archiveContent; private TestResults RunTest(Stream content) { return new NumberOfClassificationSystems(new ArchiveContentMemoryStreamReader(content)).RunTest(new ArchiveExtraction("123", "")); } [Fact] public void NumberOfClassificationSystemsIsOne() { _archiveContent = new ArchiveBuilder().WithArchivePart().WithClassificationSystem().Build(); TestResults testResults = RunTest(_archiveContent); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("1"); } [Fact] public void NumberOfClassificationSystemsIsTwo() { _archiveContent = new ArchiveBuilder() .WithArchivePart("part 1").WithClassificationSystem("classification system 1") .WithArchivePart("part 2").WithClassificationSystem("classification system 2") .Build(); TestResults testResults = RunTest(_archiveContent); testResults.AnalysisResults[NumberOfClassificationSystems.AnalysisKeyClassificationSystems].Should().Be("2"); } public void Dispose() { _archiveContent.Dispose(); } } }
agpl-3.0
C#