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
cb0b3650b82affcc7ea46a4c90cf0c5fb4368800
Use a blockingUpdateTokenCount uint rather than a boolean to deal with nested BeginUpdate()-EndUpdate() pairs better.
PenguinF/sandra-three
Sandra.UI.WF/RichTextBox/UpdatableRichTextBox.cs
Sandra.UI.WF/RichTextBox/UpdatableRichTextBox.cs
/********************************************************************************* * UpdatableRichTextBox.cs * * Copyright (c) 2004-2017 Henk Nicolai * * 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.Runtime.InteropServices; using System.Windows.Forms; namespace Sandra.UI.WF { /// <summary> /// Standard Windows <see cref="RichTextBox"/> with <see cref="BeginUpdate"/> and <see cref="EndUpdate"/> /// methods which suspend repaints of the <see cref="RichTextBox"/>. /// </summary> public class UpdatableRichTextBox : RichTextBox { private uint blockingUpdateTokenCount; /// <summary> /// Gets if the <see cref="UpdatableRichTextBox"/> is currently being updated. /// </summary> public bool IsUpdating => blockingUpdateTokenCount > 0; const int WM_SETREDRAW = 0x0b; /// <summary> /// Suspends repainting of the <see cref="UpdatableRichTextBox"/> while it's being updated. /// </summary> public void BeginUpdate() { if (blockingUpdateTokenCount == 0) { WinAPI.HideCaret(new HandleRef(this, Handle)); WinAPI.SendMessage(new HandleRef(this, Handle), WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); } ++blockingUpdateTokenCount; } /// <summary> /// Resumes repainting of the <see cref="UpdatableRichTextBox"/> after it's being updated. /// </summary> public void EndUpdate() { --blockingUpdateTokenCount; if (blockingUpdateTokenCount == 0) { WinAPI.SendMessage(new HandleRef(this, Handle), WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); WinAPI.ShowCaret(new HandleRef(this, Handle)); Invalidate(); } } } }
/********************************************************************************* * UpdatableRichTextBox.cs * * Copyright (c) 2004-2017 Henk Nicolai * * 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.Runtime.InteropServices; using System.Windows.Forms; namespace Sandra.UI.WF { /// <summary> /// Standard Windows <see cref="RichTextBox"/> with <see cref="BeginUpdate"/> and <see cref="EndUpdate"/> /// methods which suspend repaints of the <see cref="RichTextBox"/>. /// </summary> public class UpdatableRichTextBox : RichTextBox { private bool isUpdating; /// <summary> /// Gets if the <see cref="UpdatableRichTextBox"/> is currently being updated. /// </summary> public bool IsUpdating => isUpdating; const int WM_SETREDRAW = 0x0b; /// <summary> /// Suspends repainting of the <see cref="UpdatableRichTextBox"/> while it's being updated. /// </summary> public void BeginUpdate() { if (!isUpdating) { isUpdating = true; WinAPI.HideCaret(new HandleRef(this, Handle)); WinAPI.SendMessage(new HandleRef(this, Handle), WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); } } /// <summary> /// Resumes repainting of the <see cref="UpdatableRichTextBox"/> after it's being updated. /// </summary> public void EndUpdate() { if (isUpdating) { WinAPI.SendMessage(new HandleRef(this, Handle), WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); WinAPI.ShowCaret(new HandleRef(this, Handle)); isUpdating = false; Invalidate(); } } } }
apache-2.0
C#
a40b72a79bf1f52f49aca73116c10edb13477c12
bump pause before running data tests to give db time to come online
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
tests/FilterLists.Data.Tests/SeedFilterListsDbContextTests.cs
tests/FilterLists.Data.Tests/SeedFilterListsDbContextTests.cs
using System.Threading; using FilterLists.Data.Seed.Extensions; using Microsoft.EntityFrameworkCore; using Xunit; namespace FilterLists.Data.Tests { public class SeedFilterListsDbContextTests { [Fact] public async void SeedOrUpdateAsync_DoesNotThrowException() { //TODO: replace with Polly or similar to optimize time waste // allow time for db to init Thread.Sleep(15000); const string connString = "Server=mariadb;Database=filterlists;Uid=filterlists;Pwd=filterlists;"; var options = new DbContextOptionsBuilder<FilterListsDbContext>() .UseMySql(connString, m => m.MigrationsAssembly("FilterLists.Api")) .Options; using (var context = new FilterListsDbContext(options)) { await context.Database.EnsureCreatedAsync(); await SeedFilterListsDbContext.SeedOrUpdateAsync(context, "../../../data"); } } } }
using System.Threading; using FilterLists.Data.Seed.Extensions; using Microsoft.EntityFrameworkCore; using Xunit; namespace FilterLists.Data.Tests { public class SeedFilterListsDbContextTests { [Fact] public async void SeedOrUpdateAsync_DoesNotThrowException() { //TODO: replace with Polly or similar to optimize time waste // allow time for db to init Thread.Sleep(10000); const string connString = "Server=mariadb;Database=filterlists;Uid=filterlists;Pwd=filterlists;"; var options = new DbContextOptionsBuilder<FilterListsDbContext>() .UseMySql(connString, m => m.MigrationsAssembly("FilterLists.Api")) .Options; using (var context = new FilterListsDbContext(options)) { await context.Database.EnsureCreatedAsync(); await SeedFilterListsDbContext.SeedOrUpdateAsync(context, "../../../data"); } } } }
mit
C#
c27b4bb33a50f375f211f150bf2c607e63dc48a7
Remove unused property.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Blockchain/BlockFilters/SyncInfo.cs
WalletWasabi/Blockchain/BlockFilters/SyncInfo.cs
using NBitcoin.RPC; using System; using WalletWasabi.Helpers; namespace WalletWasabi.Blockchain.BlockFilters { public class SyncInfo { public SyncInfo(BlockchainInfo bcinfo) { Guard.NotNull(nameof(bcinfo), bcinfo); BlockCount = (int)bcinfo.Blocks; int headerCount = (int)bcinfo.Headers; BlockchainInfoUpdated = DateTimeOffset.UtcNow; IsCoreSynchornized = BlockCount == headerCount; InitialBlockDownload = bcinfo.InitialBlockDownload; } public int BlockCount { get; } public DateTimeOffset BlockchainInfoUpdated { get; } public bool IsCoreSynchornized { get; } public bool InitialBlockDownload { get; } } }
using NBitcoin.RPC; using System; using WalletWasabi.Helpers; namespace WalletWasabi.Blockchain.BlockFilters { public class SyncInfo { public SyncInfo(BlockchainInfo bcinfo) { Guard.NotNull(nameof(bcinfo), bcinfo); BlockCount = (int)bcinfo.Blocks; int headerCount = (int)bcinfo.Headers; BlockchainInfoUpdated = DateTimeOffset.UtcNow; IsCoreSynchornized = BlockCount == headerCount; InitialBlockDownload = bcinfo.InitialBlockDownload; } public BlockchainInfo BlockchainInfo { get; } public int BlockCount { get; } public DateTimeOffset BlockchainInfoUpdated { get; } public bool IsCoreSynchornized { get; } public bool InitialBlockDownload { get; } } }
mit
C#
58266453419f965c3c104b18a3ac3060d83f0be5
Update GetServiceDirectory() API to use EndpointConfig
Ontica/Empiria.Extended
WebApi/Controllers/ServiceDirectoryController.cs
WebApi/Controllers/ServiceDirectoryController.cs
/* Empiria Extensions Framework ****************************************************************************** * * * Module : Empiria Web Api Component : Base controllers * * Assembly : Empiria.WebApi.dll Pattern : Web Api Controller * * Type : ServiceDirectoryController License : Please read LICENSE.txt file * * * * Summary : Web api methods to get information about the web service directory. * * * ************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/ using System; using System.Web.Http; using Empiria.Security; namespace Empiria.WebApi.Controllers { /// <summary>Web api methods to get information about the web service directory.</summary> public class ServiceDirectoryController : WebApiController { #region Public APIs /// <summary>Gets a list of available web services in the context of the client application.</summary> /// <returns>A list of services as instances of the type ServiceDirectoryItem.</returns> [HttpGet, AllowAnonymous] [Route("v1/system/service-directory")] public CollectionModel GetServiceDirectory() { try { ClientApplication clientApplication = base.GetClientApplication(); var endpointsList = EndpointConfig.GetList(clientApplication); return new CollectionModel(base.Request, endpointsList); } catch (Exception e) { throw base.CreateHttpException(e); } } #endregion Public APIs } // class ServiceDirectoryController } // namespace Empiria.WebApi.Controllers
/* Empiria Extensions Framework ****************************************************************************** * * * Module : Empiria Web Api Component : Base controllers * * Assembly : Empiria.WebApi.dll Pattern : Web Api Controller * * Type : ServiceDirectoryController License : Please read LICENSE.txt file * * * * Summary : Web api methods to get information about the web service directory. * * * ************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/ using System; using System.Web.Http; using Empiria.Security; namespace Empiria.WebApi.Controllers { /// <summary>Web api methods to get information about the web service directory.</summary> public class ServiceDirectoryController : WebApiController { #region Public APIs /// <summary>Gets a list of available web services in the context of the client application.</summary> /// <returns>A list of services as instances of the type ServiceDirectoryItem.</returns> [HttpGet, AllowAnonymous] [Route("v1/system/service-directory")] public CollectionModel GetServiceDirectory() { try { ClientApplication clientApplication = base.GetClientApplication(); var services = ServiceDirectoryItem.GetList(clientApplication); return new CollectionModel(base.Request, services); } catch (Exception e) { throw base.CreateHttpException(e); } } #endregion Public APIs } // class ServiceDirectoryController } // namespace Empiria.WebApi.Controllers
agpl-3.0
C#
7c688b1e55f4bc48de70612f59301bdc54c8a382
add a TODO
paladique/nodejstools,bossvn/nodejstools,paulvanbrenk/nodejstools,bossvn/nodejstools,necroscope/nodejstools,bowdenk7/nodejstools,munyirik/nodejstools,AustinHull/nodejstools,ahmad-farid/nodejstools,chanchaldabriya/nodejstools,np83/nodejstools,paulvanbrenk/nodejstools,paladique/nodejstools,kant2002/nodejstools,bossvn/nodejstools,lukedgr/nodejstools,redabakr/nodejstools,np83/nodejstools,kant2002/nodejstools,nareshjo/nodejstools,bossvn/nodejstools,hoanhtien/nodejstools,mjbvz/nodejstools,zhoffice/nodejstools,nareshjo/nodejstools,Microsoft/nodejstools,mauricionr/nodejstools,ahmad-farid/nodejstools,hagb4rd/nodejstools,bowdenk7/nodejstools,mauricionr/nodejstools,zhoffice/nodejstools,mjbvz/nodejstools,mousetraps/nodejstools,mauricionr/nodejstools,mousetraps/nodejstools,ahmad-farid/nodejstools,necroscope/nodejstools,lukedgr/nodejstools,mousetraps/nodejstools,munyirik/nodejstools,avitalb/nodejstools,chanchaldabriya/nodejstools,mousetraps/nodejstools,paladique/nodejstools,hagb4rd/nodejstools,Microsoft/nodejstools,bossvn/nodejstools,munyirik/nodejstools,AustinHull/nodejstools,zhoffice/nodejstools,paladique/nodejstools,paulvanbrenk/nodejstools,redabakr/nodejstools,ahmad-farid/nodejstools,chanchaldabriya/nodejstools,chanchaldabriya/nodejstools,hoanhtien/nodejstools,paulvanbrenk/nodejstools,mauricionr/nodejstools,ahmad-farid/nodejstools,hoanhtien/nodejstools,Microsoft/nodejstools,hoanhtien/nodejstools,Microsoft/nodejstools,zhoffice/nodejstools,avitalb/nodejstools,munyirik/nodejstools,lukedgr/nodejstools,kant2002/nodejstools,avitalb/nodejstools,lukedgr/nodejstools,necroscope/nodejstools,redabakr/nodejstools,redabakr/nodejstools,mousetraps/nodejstools,mauricionr/nodejstools,lukedgr/nodejstools,redabakr/nodejstools,mjbvz/nodejstools,kant2002/nodejstools,paulvanbrenk/nodejstools,nareshjo/nodejstools,kant2002/nodejstools,nareshjo/nodejstools,mjbvz/nodejstools,AustinHull/nodejstools,np83/nodejstools,nareshjo/nodejstools,mjbvz/nodejstools,avitalb/nodejstools,Microsoft/nodejstools,AustinHull/nodejstools,np83/nodejstools,avitalb/nodejstools,hoanhtien/nodejstools,chanchaldabriya/nodejstools,AustinHull/nodejstools,np83/nodejstools,bowdenk7/nodejstools,necroscope/nodejstools,munyirik/nodejstools,hagb4rd/nodejstools,bowdenk7/nodejstools,bowdenk7/nodejstools,necroscope/nodejstools,hagb4rd/nodejstools,paladique/nodejstools,zhoffice/nodejstools,hagb4rd/nodejstools
Nodejs/Product/TestAdapter/TestFrameworks/FrameworkDiscover.cs
Nodejs/Product/TestAdapter/TestFrameworks/FrameworkDiscover.cs
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.NodejsTools.TestAdapter.TestFrameworks { //TODO, this should be an application level global object, where to put it? class FrameworkDiscover { private List<TestFramework> _framworks; private TestFramework Default = null; public FrameworkDiscover() { string installFolder = GetExecutingAssemblyPath(); _framworks = new List<TestFramework>(); foreach (string directory in Directory.GetDirectories(installFolder + @"\TestFrameworks")) { TestFramework fx = new TestFramework(directory); _framworks.Add(fx); } Default = Search("generic"); } public TestFramework Get(string frameworkName) { TestFramework matched = Search(frameworkName); if (matched == null) { matched = Default; } return matched; } private TestFramework Search(string frameworkName) { TestFramework matched = _framworks.FirstOrDefault((p) => { return p.Name.Equals(frameworkName, StringComparison.OrdinalIgnoreCase); }); return matched; } private string GetExecutingAssemblyPath() { string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.NodejsTools.TestAdapter.TestFrameworks { class FrameworkDiscover { private List<TestFramework> _framworks; private TestFramework Default = null; public FrameworkDiscover() { string installFolder = GetExecutingAssemblyPath(); _framworks = new List<TestFramework>(); foreach (string directory in Directory.GetDirectories(installFolder + @"\TestFrameworks")) { TestFramework fx = new TestFramework(directory); _framworks.Add(fx); } Default = Search("generic"); } public TestFramework Get(string frameworkName) { TestFramework matched = Search(frameworkName); if (matched == null) { matched = Default; } return matched; } private TestFramework Search(string frameworkName) { TestFramework matched = _framworks.FirstOrDefault((p) => { return p.Name.Equals(frameworkName, StringComparison.OrdinalIgnoreCase); }); return matched; } private string GetExecutingAssemblyPath() { string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } }
apache-2.0
C#
39d361320bd1cd8e90a82df65e0460295cc9cdef
Update NumericLiteralTokenScanner.cs
Zebrina/PapyrusScriptEditorVSIX,Zebrina/PapyrusScriptEditorVSIX
PapyrusScriptEditorVSIX/Language/NumericLiteralTokenScanner.cs
PapyrusScriptEditorVSIX/Language/NumericLiteralTokenScanner.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Papyrus.Language.Components; using Papyrus.Common.Extensions; namespace Papyrus.Language { public class NumericLiteralTokenScanner : TokenScannerModule { public override bool Scan(SnapshotSpan sourceSnapshotSpan, int offset, ref TokenScannerState state, out Token token) { if (state == TokenScannerState.Text) { string text = sourceSnapshotSpan.GetText(); int length = Delimiter.FindNext(text, offset) - offset; NumericLiteral numericLiteral = NumericLiteral.Parse(text.Substring(offset, length)); if (numericLiteral != null) { token = new Token(numericLiteral, sourceSnapshotSpan.Subspan(offset, length)); return true; } } token = null; return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Papyrus.Language.Components; using Papyrus.Common.Extensions; namespace Papyrus.Language { public class NumericLiteralTokenScanner : TokenScannerModule { public override bool Scan(SnapshotSpan sourceSnapshotSpan, int offset, ref TokenScannerState state, out Token token) { string text = sourceSnapshotSpan.GetText(); int length = Delimiter.FindNext(text, offset) - offset; NumericLiteral numericLiteral = NumericLiteral.Parse(text.Substring(offset, length)); if (numericLiteral != null) { token = new Token(numericLiteral, sourceSnapshotSpan.Subspan(offset, length)); return true; } token = null; return false; } } }
mit
C#
5384e1883b02ff9f98f17fbf034c1fce42c53517
test for the endpoint exception
MassTransit/MassTransit,jacobpovar/MassTransit,phatboyg/MassTransit,SanSYS/MassTransit,MassTransit/MassTransit,jacobpovar/MassTransit,SanSYS/MassTransit,phatboyg/MassTransit
Transports/MassTransit.Transports.Msmq.Tests/As_an_endpoint.cs
Transports/MassTransit.Transports.Msmq.Tests/As_an_endpoint.cs
namespace MassTransit.Transports.Msmq.Tests { using System; using Configuration; using Exceptions; using MassTransit.Tests; using NUnit.Framework; [TestFixture] public class When_endpoint_doesnt_exist { [Test] [ExpectedException(typeof(EndpointException))] public void Should_throw_an_endpoint_exception() { new MsmqEndpoint("msmq://localhost/idontexist_tx"); } [Test] [ExpectedException(typeof(EndpointException))] public void Should_throw_an_endpoint_exception_from_the_factory() { var ef = EndpointFactoryConfigurator.New(x => { x.RegisterTransport<MsmqEndpoint>(); }); ef.GetEndpoint("msmq://localhost/idontexist_tx"); } } [TestFixture] public class When_instantiated_endpoints_via_uri { [Test] public void Should_get_conveted_into_a_fully_qualified_uri() { string endpointName = @"msmq://localhost/mt_client_tx"; MsmqEndpoint defaultEndpoint = new MsmqEndpoint(endpointName); string machineEndpointName = endpointName.Replace("localhost", Environment.MachineName.ToLowerInvariant()); defaultEndpoint.Uri.Equals(machineEndpointName) .ShouldBeTrue(); } } }
namespace MassTransit.Transports.Msmq.Tests { using System; using Exceptions; using MassTransit.Tests; using NUnit.Framework; [TestFixture] public class When_endpoint_doesnt_exist { [Test] [ExpectedException(typeof(EndpointException))] public void Should_throw_an_endpoint_exception() { new MsmqEndpoint("msmq://localhost/idontexist_tx"); } } [TestFixture] public class When_instantiated_endpoints_via_uri { [Test] public void Should_get_conveted_into_a_fully_qualified_uri() { string endpointName = @"msmq://localhost/mt_client_tx"; MsmqEndpoint defaultEndpoint = new MsmqEndpoint(endpointName); string machineEndpointName = endpointName.Replace("localhost", Environment.MachineName.ToLowerInvariant()); defaultEndpoint.Uri.Equals(machineEndpointName) .ShouldBeTrue(); } } }
apache-2.0
C#
37ac900b710c09452c62d8b198585c2d43a2add8
test for the endpoint exception
ccellar/MassTransit,ccellar/MassTransit,lahma/MassTransit,jsmale/MassTransit,D3-LucaPiombino/MassTransit,abombss/MassTransit,petedavis/MassTransit,ccellar/MassTransit,vebin/MassTransit,abombss/MassTransit,lahma/MassTransit,ccellar/MassTransit,lahma/MassTransit,vebin/MassTransit,lahma/MassTransit,abombss/MassTransit,petedavis/MassTransit,lahma/MassTransit
Transports/MassTransit.Transports.Msmq.Tests/As_an_endpoint.cs
Transports/MassTransit.Transports.Msmq.Tests/As_an_endpoint.cs
namespace MassTransit.Transports.Msmq.Tests { using System; using Configuration; using Exceptions; using MassTransit.Tests; using NUnit.Framework; [TestFixture] public class When_endpoint_doesnt_exist { [Test] [ExpectedException(typeof(EndpointException))] public void Should_throw_an_endpoint_exception() { new MsmqEndpoint("msmq://localhost/idontexist_tx"); } [Test] [ExpectedException(typeof(EndpointException))] public void Should_throw_an_endpoint_exception_from_the_factory() { var ef = EndpointFactoryConfigurator.New(x => { x.RegisterTransport<MsmqEndpoint>(); }); ef.GetEndpoint("msmq://localhost/idontexist_tx"); } } [TestFixture] public class When_instantiated_endpoints_via_uri { [Test] public void Should_get_conveted_into_a_fully_qualified_uri() { string endpointName = @"msmq://localhost/mt_client_tx"; MsmqEndpoint defaultEndpoint = new MsmqEndpoint(endpointName); string machineEndpointName = endpointName.Replace("localhost", Environment.MachineName.ToLowerInvariant()); defaultEndpoint.Uri.Equals(machineEndpointName) .ShouldBeTrue(); } } }
namespace MassTransit.Transports.Msmq.Tests { using System; using Exceptions; using MassTransit.Tests; using NUnit.Framework; [TestFixture] public class When_endpoint_doesnt_exist { [Test] [ExpectedException(typeof(EndpointException))] public void Should_throw_an_endpoint_exception() { new MsmqEndpoint("msmq://localhost/idontexist_tx"); } } [TestFixture] public class When_instantiated_endpoints_via_uri { [Test] public void Should_get_conveted_into_a_fully_qualified_uri() { string endpointName = @"msmq://localhost/mt_client_tx"; MsmqEndpoint defaultEndpoint = new MsmqEndpoint(endpointName); string machineEndpointName = endpointName.Replace("localhost", Environment.MachineName.ToLowerInvariant()); defaultEndpoint.Uri.Equals(machineEndpointName) .ShouldBeTrue(); } } }
apache-2.0
C#
184e2443bc4c70f5c6b570e906d8841f49aeed19
Add WTSQueryUserToken
jmelosegui/pinvoke,AArnott/pinvoke,vbfox/pinvoke
src/WtsApi32.Desktop/WtsApi32.cs
src/WtsApi32.Desktop/WtsApi32.cs
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using static Kernel32; using System; using System.Runtime.InteropServices; /// <content> /// Exported functions from the WtsApi32.dll Windows library /// that are available to Desktop apps only. /// </content> public static partial class WtsApi32 { /// <summary> /// Obtains the primary access token of the logged-on user specified by the session ID. To call this function successfully, /// the calling application must be running within the context of the LocalSystem account and have the SE_TCB_NAME privilege. /// Caution WTSQueryUserToken is intended for highly trusted services.Service providers must use caution that they do not /// leak user tokens when calling this function.Service providers must close token handles after they have finished using them. /// </summary> /// <param name="SessionId">A Remote Desktop Services session identifier. Any program running in the context of a service /// will have a session identifier of zero (0). You can use the WTSEnumerateSessions function to retrieve the identifiers of /// all sessions on a specified RD Session Host server. /// To be able to query information for another user's session, you need to have the Query Information permission. /// For more information, see Remote Desktop Services Permissions. To modify permissions on a session, use the /// Remote Desktop Services Configuration administrative tool.</param> /// <param name="phToken">If the function succeeds, receives a pointer to the token handle for the logged-on user. Note /// that you must call the CloseHandle function to close this handle.</param> /// <returns>f the function succeeds, the return value is a nonzero value, and the phToken parameter points to the primary /// token of the user.</returns> [DllImport(nameof(WtsApi32), SetLastError = true)] public static extern bool WTSQueryUserToken(int SessionId, out SafeObjectHandle phToken); } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Runtime.InteropServices; /// <content> /// Exported functions from the WtsApi32.dll Windows library /// that are available to Desktop apps only. /// </content> public static partial class WtsApi32 { } }
mit
C#
a05fe1fc8c514a633d42c464a59a047978306117
fix peverify order
Fody/Janitor
Tests/Verifier.cs
Tests/Verifier.cs
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using NUnit.Framework; public static class Verifier { static string exePath; static Verifier() { var windowsSdk = Environment.ExpandEnvironmentVariables(@"%programfiles(x86)%\Microsoft SDKs\Windows\"); exePath = Directory.EnumerateFiles(windowsSdk, "PEVerify.exe", SearchOption.AllDirectories) .OrderByDescending(x => { var fileVersionInfo = FileVersionInfo.GetVersionInfo(x); return new Version(fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart); }) .FirstOrDefault(); if (exePath == null) { throw new Exception("Could not find path to PEVerify"); } } public static void Verify(string beforeAssemblyPath, string afterAssemblyPath) { var before = Validate(beforeAssemblyPath); var after = Validate(afterAssemblyPath); var message = $"Failed processing {Path.GetFileName(afterAssemblyPath)}\r\n{after}"; Assert.AreEqual(TrimLineNumbers(before), TrimLineNumbers(after), message); } static string Validate(string assemblyPath2) { using (var process = Process.Start(new ProcessStartInfo(exePath, $"\"{assemblyPath2}\"") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true })) { process.WaitForExit(10000); return process.StandardOutput.ReadToEnd().Trim().Replace(assemblyPath2, ""); } } static string TrimLineNumbers(string foo) { return Regex.Replace(foo, "0x.*]", ""); } }
using System; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using NUnit.Framework; public static class Verifier { public static void Verify(string beforeAssemblyPath, string afterAssemblyPath) { var before = Validate(beforeAssemblyPath); var after = Validate(afterAssemblyPath); var message = $"Failed processing {Path.GetFileName(afterAssemblyPath)}\r\n{after}"; Assert.AreEqual(TrimLineNumbers(before), TrimLineNumbers(after), message); } static string Validate(string assemblyPath2) { var exePath = GetPathToPEVerify(); if (!File.Exists(exePath)) { return string.Empty; } var process = Process.Start(new ProcessStartInfo(exePath, "\"" + assemblyPath2 + "\"") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }); process.WaitForExit(10000); return process.StandardOutput.ReadToEnd().Trim().Replace(assemblyPath2, ""); } static string GetPathToPEVerify() { var exePath = Environment.ExpandEnvironmentVariables(@"%programfiles(x86)%\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\PEVerify.exe"); if (!File.Exists(exePath)) { exePath = Environment.ExpandEnvironmentVariables(@"%programfiles(x86)%\Microsoft SDKs\Windows\v8.0A\Bin\NETFX 4.0 Tools\PEVerify.exe"); } return exePath; } static string TrimLineNumbers(string foo) { return Regex.Replace(foo, @"0x.*]", ""); } }
mit
C#
78b02c183e32efd7099094c677d41bcf268852bc
Bump version
klesta490/BTDB,Bobris/BTDB,karasek/BTDB
BTDB/Properties/AssemblyInfo.cs
BTDB/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright Boris Letocha 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("2.13.0.0")] [assembly: AssemblyFileVersion("2.13.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright Boris Letocha 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("2.12.0.0")] [assembly: AssemblyFileVersion("2.12.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
mit
C#
94603c16f49161c9ca6dbb069f1cc3190dd4263a
Update XElementToTreeView.cs
phusband/SharpExtensions
Resources/XElementToTreeView.cs
Resources/XElementToTreeView.cs
namespace SharpExtensions { public static class XElementToTreeView { public static void FromXElement(this TreeView T_View, XElement XElem , TreeNode ParentNode = null) { // Create temporarty node var TempNode = new TreeNode(XElem.Name.LocalName); // Determine if recursive loop or initial entry if(ParentNode == null) // add root of tree T_View.Nodes.Add(TempNode); // add to parent tree node else ParentNode.Nodes.Add(TempNode); // for each attribute in the element foreach(XAttribute XAttr in XElem.Attributes()){ // create a tree node for the attribute var AttrNode = new TreeNode(XAttr.Name.LocalName); // add the value of the attribute as tree node AttrNode.Nodes.Add(new TreeNode(XAttr.Value)); // add the node to the tree TempNode.Nodes.Add(AttrNode); } // if Element has no child elements if(!XElem.HasElements && !XElem.Value.Equals(string.Empty)) { // add a node for the value if it hase one var ValueNode = new TreeNode("value"); // add the value as a node ValueNode.Nodes.Add(new TreeNode(XElem.Value)); // add the node to tree TempNode.Nodes.Add(ValueNode); } if(XElem.HasElements) { // Make element parent node var TempParentNode = TempNode; // recurse XElem.Elements().ForEach(XEChild => FromXElement(T_View, XEChild, TempParentNode)); } } } }
namespace SharpExtensions { public static class XElementToTreeView { public static void FromXElement(this TreeView T_View, XElement XElem , TreeNode ParentNode = null) { // Create temporarty node var TempNode = new TreeNode(XElem.Name.LocalName); // Determine if recursive loop or initial entry if(ParentNode == null) // add root of tree T_View.Nodes.Add(TempNode); // add to parent tree node else ParentNode.Nodes.Add(TempNode); // for each attribute in the element foreach(XAttribute XAttr in XElem.Attributes()){ // create a tree node for the attribute var AttrNode = new TreeNode(XAttr.Name.LocalName); // add the value of the attribute as tree node AttrNode.Nodes.Add(new TreeNode(XAttr.Value)); // add the node to the tree TempNode.Nodes.Add(AttrNode); } // if Element has no child elements if(!XElem.HasElements && !XElem.Value.Equals(string.Empty)) { // add a node for the value if it hase one var ValueNode = new TreeNode("value"); // add the value as a node ValueNode.Nodes.Add(new TreeNode(XElem.Value)); // add the node to tree TempNode.Nodes.Add(ValueNode); } if(XElem.HasElements) { // Make element parent node var TempParentNode = TempNode; // recurse XElem.Elements().ForEach(XEChild => FromXElement(T_View, XEChild, TempParentNode)); } } } }
mit
C#
8acd89809cafc6849b640eee68c9cc7836484714
Make headers less obnoxious
awseward/restivus
src/Restivus/Serilog/SerilogExtensions.cs
src/Restivus/Serilog/SerilogExtensions.cs
using Serilog; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Restivus.Serilog { public static class SerilogExtensions { public static LoggerConfiguration FilterRequestQueryParams( this LoggerConfiguration loggerConfig, params string[] queryParamKeys) { return loggerConfig.Destructure.ByTransforming<HttpRequestMessage>( request => new { request.Method.Method, Uri = request.RequestUri.FilterQueryParams(queryParamKeys), Headers = request.Headers._SlightlySimplified(), } ); } public static LoggerConfiguration DestructureHttpResponseMessages( this LoggerConfiguration loggerConfig) { return loggerConfig.Destructure.ByTransforming<HttpResponseMessage>( response => new { Status = (int) response.StatusCode, response.RequestMessage, Headers = response.Headers._SlightlySimplified(), } ); } static IDictionary<string, string> _SlightlySimplified(this HttpHeaders headers) => headers.ToDictionary( kvp => kvp.Key, kvp => string.Join(", ", kvp.Value) ); } }
using Serilog; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Restivus.Serilog { public static class SerilogExtensions { public static LoggerConfiguration FilterQueryParamsFromHttpRequestMessage( this LoggerConfiguration loggerConfig, params string[] queryParamKeys) { return loggerConfig.Destructure.ByTransforming<HttpRequestMessage>( msg => new { msg.Method.Method, Uri = msg.RequestUri.FilterQueryParams(queryParamKeys), msg.Headers, } ); } } }
mit
C#
ca454c1fcb2c7cbf1d71f4a8b0e6560225807914
Allow to specify font in the label constructor
k-t/SharpHaven
MonoHaven.Client/UI/Label.cs
MonoHaven.Client/UI/Label.cs
using System.Drawing; using MonoHaven.Graphics; namespace MonoHaven.UI { public class Label : Widget { private string text; private readonly TextBlock textBlock; public Label(Widget parent, SpriteFont font) : base(parent) { textBlock = new TextBlock(font); textBlock.TextColor = Color.White; SetSize(0, font.Height); } public Label(Widget parent) : this(parent, Fonts.Default) { } public string Text { get { return text; } set { text = value; textBlock.Clear(); textBlock.Append(text); } } public TextAlign TextAlign { get { return textBlock.TextAlign; } set { textBlock.TextAlign = value; } } public Color TextColor { get { return textBlock.TextColor; } set { textBlock.TextColor = value; } } protected override void OnDraw(DrawingContext dc) { dc.Draw(textBlock, 0, 0, Width, Height); } } }
using System.Drawing; using MonoHaven.Graphics; namespace MonoHaven.UI { public class Label : Widget { private string text; private readonly TextBlock textBlock; public Label(Widget parent) : base(parent) { textBlock = new TextBlock(Fonts.Default); } public string Text { get { return text; } set { text = value; textBlock.Clear(); textBlock.Append(text); } } public TextAlign TextAlign { get { return textBlock.TextAlign; } set { textBlock.TextAlign = value; } } public Color TextColor { get { return textBlock.TextColor; } set { textBlock.TextColor = value; } } protected override void OnDraw(DrawingContext dc) { dc.Draw(textBlock, 0, 0, Width, Height); } } }
mit
C#
dd7d4a6a5014b981915aa6e9724ce4f3b094d746
bump version to v1.1
Dalet/140-speedrun-timer,Dalet/140-speedrun-timer,Dalet/140-speedrun-timer
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
unlicense
C#
8c52789658c519fabdbd0644e932502b027d28c5
Refactor process to remove FormatException from trace log
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade/Core/Addml/Processes/AnalyseFindMinMaxValues.cs
src/Arkivverket.Arkade/Core/Addml/Processes/AnalyseFindMinMaxValues.cs
using System; using Arkivverket.Arkade.Tests; namespace Arkivverket.Arkade.Core.Addml.Processes { public class AnalyseFindMinMaxValues : IAddmlProcess { public const string Name = "Analyse_FindMinMaxValues"; private readonly TestRun _testRun; private int? _minValue; private int? _maxValue; public AnalyseFindMinMaxValues() { _testRun = new TestRun(Name, TestType.Content); } public string GetName() { return Name; } public void Run(FlatFile flatFile) { } public void Run(Record record) { } public TestRun GetTestRun() { return _testRun; } public void EndOfFile() { string minValueString = _minValue?.ToString() ?? "<no value>"; string maxValueString = _maxValue?.ToString() ?? "<no value>"; _testRun.Add(new TestResult(ResultType.Success, $"MinValue ({minValueString}). MaxValue {maxValueString}.")); } public void Run(Field field) { // TODO: Use type to decide wether field is int? // field.Definition.GetType() int value; if (!int.TryParse(field.Value, out value)) return; if (!_maxValue.HasValue || value > _maxValue) { _maxValue = value; } if (!_minValue.HasValue || value < _minValue) { _minValue = value; } } } }
using System; using Arkivverket.Arkade.Tests; namespace Arkivverket.Arkade.Core.Addml.Processes { public class AnalyseFindMinMaxValues : IAddmlProcess { public const string Name = "Analyse_FindMinMaxValues"; private readonly TestRun _testRun; private int? _minValue; private int? _maxValue; public AnalyseFindMinMaxValues() { _testRun = new TestRun(Name, TestType.Content); } public string GetName() { return Name; } public void Run(FlatFile flatFile) { } public void Run(Record record) { } public TestRun GetTestRun() { return _testRun; } public void EndOfFile() { string minValueString = _minValue?.ToString() ?? "<no value>"; string maxValueString = _maxValue?.ToString() ?? "<no value>"; _testRun.Add(new TestResult(ResultType.Success, $"MinValue ({minValueString}). MaxValue {maxValueString}.")); } public void Run(Field field) { // TODO: Use type to decide wether field is int? // field.Definition.GetType() try { int value = int.Parse(field.Value); if (!_maxValue.HasValue || value > _maxValue) { _maxValue = value; } if (!_minValue.HasValue || value < _minValue) { _minValue = value; } } catch (FormatException e) { // ignore } } } }
agpl-3.0
C#
61ca3d9db9a1085b6a1c0568094d48ef77aa6469
Fix styling for users download page
Orcomp/Orc.CheckForUpdates,Orcomp/Orc.CheckForUpdates,Orcomp/Orc.CheckForUpdates
src/samples/Orc.CheckForUpdate.BasicServer/Views/Releases/Index.cshtml
src/samples/Orc.CheckForUpdate.BasicServer/Views/Releases/Index.cshtml
@model Orc.CheckForUpdate.Web.Models.VersionsViewModel @{ ViewBag.Title = "Index"; } @section additionalstyles { @Styles.Render("~/Content/css/releases") } <h2>Releases</h2> <div> @{ Html.RenderPartial("ReleasesList", Model); } </div>
@model Orc.CheckForUpdate.Web.Models.VersionsViewModel @{ ViewBag.Title = "Index"; } @section additionalstyles { @Styles.Render("~/Content/css/downloads") } <h2>Releases</h2> <div> @{ Html.RenderPartial("ReleasesList", Model); } </div>
mit
C#
ab64769c59fae2a0942ded9e9242c2b4ee81b908
Fix compilation failure
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
testapps/ApplicationWithCustomInputFiles/Controllers/HomeController.cs
testapps/ApplicationWithCustomInputFiles/Controllers/HomeController.cs
using System; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Razor.Compilation; namespace ApplicationWithCustomInputFiles.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public string GetPrecompiledResourceNames([FromServices] ApplicationPartManager applicationManager) { var feature = new ViewsFeature(); applicationManager.PopulateFeature(feature); return string.Join(Environment.NewLine, feature.ViewDescriptors.Select(v => v.RelativePath)); } } }
using System; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Razor.Compilation; namespace ApplicationWithCustomInputFiles.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public string GetPrecompiledResourceNames([FromServices] ApplicationPartManager applicationManager) { var feature = new ViewsFeature(); applicationManager.PopulateFeature(feature); return string.Join(Environment.NewLine, feature.Views.Keys); } } }
apache-2.0
C#
680356c2348ace103f1ca565e1df718ce352b0dd
Add ShowException
AVPolyakov/SharpLayout
SharpLayout.Tests/Program.cs
SharpLayout.Tests/Program.cs
using System; using System.Diagnostics; using PdfSharp.Drawing; namespace SharpLayout.Tests { static class Program { static void Main() { try { var document = new Document { //CellsAreHighlighted = true, //R1C1AreVisible = true, //ParagraphsAreHighlighted = true, //CellLineNumbersAreVisible = true, //ExpressionVisible = true, }; PaymentOrder.AddSection(document, new PaymentData {IncomingDate = DateTime.Now, OutcomingDate = DateTime.Now}); //Svo.AddSection(document); //ContractDealPassport.AddSection(document); //LoanAgreementDealPassport.AddSection(document); document.SavePng(0, "Temp.png", 120).StartLiveViewer(true); //Process.Start(document.SavePng(0, "Temp2.png")); //open with Paint.NET //Process.Start(document.SavePdf($"Temp_{Guid.NewGuid():N}.pdf")); } catch (Exception e) { ShowException(e); } } private static void ShowException(Exception e) { var document = new Document(); var settings = new PageSettings(); settings.LeftMargin = settings.TopMargin = settings.RightMargin = settings.BottomMargin = Util.Cm(0.5); document.Add(new Section(settings).Add(new Paragraph() .Add($"{e}", new XFont("Consolas", 9.5)))); document.SavePng(0, "Temp.png", 120).StartLiveViewer(true); } public static void StartLiveViewer(this string fileName, bool alwaysShowWindow) { if (alwaysShowWindow || Process.GetProcessesByName("LiveViewer").Length <= 0) Process.Start("LiveViewer", fileName); } } }
using System; using System.Diagnostics; namespace SharpLayout.Tests { static class Program { static void Main() { var document = new Document { //CellsAreHighlighted = true, //R1C1AreVisible = true, //ParagraphsAreHighlighted = true, //CellLineNumbersAreVisible = true, //ExpressionVisible = true, }; PaymentOrder.AddSection(document, new PaymentData{IncomingDate = DateTime.Now, OutcomingDate = DateTime.Now}); //Svo.AddSection(document); //ContractDealPassport.AddSection(document); //LoanAgreementDealPassport.AddSection(document); document.SavePng(0, "Temp.png", 120).StartLiveViewer(true); //Process.Start(document.SavePng(0, "Temp2.png")); //open with Paint.NET //Process.Start(document.SavePdf($"Temp_{Guid.NewGuid():N}.pdf")); } public static void StartLiveViewer(this string fileName, bool alwaysShowWindow) { if (alwaysShowWindow || Process.GetProcessesByName("LiveViewer").Length <= 0) Process.Start("LiveViewer", fileName); } } }
mit
C#
3af940419038aa706675990ea7bc447ef0dcdd3b
Fix typo.
real-logic/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,PKRoma/simple-binary-encoding,real-logic/simple-binary-encoding,PKRoma/simple-binary-encoding,real-logic/simple-binary-encoding,real-logic/simple-binary-encoding,real-logic/simple-binary-encoding,real-logic/simple-binary-encoding,real-logic/simple-binary-encoding
csharp/sbe-tests/Issue560Tests.cs
csharp/sbe-tests/Issue560Tests.cs
// Copyright (C) 2018 Bill Segall // // 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 // // https://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 Microsoft.VisualStudio.TestTools.UnitTesting; using Org.SbeTool.Sbe.Dll; namespace Org.SbeTool.Sbe.Tests { [TestClass] public unsafe class Issue560Tests { private byte[] _buffer; private DirectBuffer _directBuffer; private Issue560.MessageHeader _messageHeader; private Issue560.Issue560 _issue560; //public Issue560.Issue560 Issue560 { get => _issue560; set => _issue560 = value; } [TestInitialize] public void SetUp() { _buffer = new Byte[4096]; _directBuffer = new DirectBuffer(_buffer); _issue560 = new Issue560.Issue560(); _messageHeader = new Issue560.MessageHeader(); _messageHeader.Wrap(_directBuffer, 0, Issue560.MessageHeader.SbeSchemaVersion); _messageHeader.BlockLength = Issue560.Issue560.BlockLength; _messageHeader.SchemaId = Issue560.Issue560.SchemaId; _messageHeader.TemplateId = Issue560.Issue560.TemplateId; _messageHeader.Version = Issue560.Issue560.SchemaVersion; } [TestMethod] public void Issue560Test() { Assert.AreEqual(_issue560.DiscountedModel, Issue560.Model.C, "Incorrect const enum valueref"); } } }
// Copyright (C) 2018 Bill Segall // // 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 // // https://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 Microsoft.VisualStudio.TestTools.UnitTesting; using Org.SbeTool.Sbe.Dll; namespace Org.SbeTool.Sbe.Tests { [TestClass] public unsafe class Issue560Tests { private byte[] _buffer; private DirectBuffer _directBuffer; private Issue560.MessageHeader _messageHeader; private Issue560.Issue560 _issue560; //public Issue560.Issue560 Issue560 { get => _issue560; set => _issue560 = value; } [TestInitialize] public void SetUp() { _buffer = new Byte[4096]; _directBuffer = new DirectBuffer(_buffer); _issue560 = new Issue560.Issue560(); _messageHeader = new Issue560.MessageHeader(); _messageHeader.Wrap(_directBuffer, 0, Issue560.MessageHeader.SbeSchemaVersion); _messageHeader.BlockLength = Issue560.Issue560.BlockLength; _messageHeader.SchemaId = Issue560.Issue560.SchemaId; _messageHeader.TemplateId = Issue560.Issue560.TemplateId; _messageHeader.Version = Issue560.Issue560.SchemaVersion; } [TestMethod] public void Issue560Test() { Assert.AreEqual(_issue560.DiscountedModel, Issue560.Model.C, "Incorrect const enum valueref"); } = } }
apache-2.0
C#
b6d3d99af1722eb2fa88f2c165c1139707298b5d
Set Client Provided Name when creating connection
simonbaas/EasyRabbitMQ,simonbaas/EasyRabbitMQ
src/EasyRabbitMQ/Infrastructure/ConnectionFactory.cs
src/EasyRabbitMQ/Infrastructure/ConnectionFactory.cs
using EasyRabbitMQ.Configuration; using RabbitMQ.Client; namespace EasyRabbitMQ.Infrastructure { internal class ConnectionFactory : IConnectionFactory { private readonly IConfiguration _configuration; private const string ClientProvidedName = "EasyRabbitMQ"; public ConnectionFactory(IConfiguration configuration) { _configuration = configuration; } public IConnection CreateConnection() { var factory = new RabbitMQ.Client.ConnectionFactory { Uri = _configuration.ConnectionString, AutomaticRecoveryEnabled = true }; var connection = factory.CreateConnection(ClientProvidedName); return connection; } } }
using EasyRabbitMQ.Configuration; using RabbitMQ.Client; namespace EasyRabbitMQ.Infrastructure { internal class ConnectionFactory : IConnectionFactory { private readonly IConfiguration _configuration; public ConnectionFactory(IConfiguration configuration) { _configuration = configuration; } public IConnection CreateConnection() { var factory = new RabbitMQ.Client.ConnectionFactory { Uri = _configuration.ConnectionString, AutomaticRecoveryEnabled = true }; var connection = factory.CreateConnection(); return connection; } } }
apache-2.0
C#
b50ed7a4b3a7ec58ce5bc76e49be86321b9cde62
fix nullability issue
acple/ParsecSharp
ParsecSharp/Data/Internal/Buffer.cs
ParsecSharp/Data/Internal/Buffer.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ParsecSharp.Internal { public sealed class Buffer<TToken> : IReadOnlyList<TToken> { public static Buffer<TToken> Empty { get; } = new(Array.Empty<TToken>(), () => Empty!); private readonly TToken[] _buffer; private readonly int _index; private readonly Lazy<Buffer<TToken>> _next; public TToken this[int index] => this._buffer[this._index + index]; public int Count { get; } public Buffer<TToken> Next => this._next.Value; public Buffer(TToken[] buffer, Func<Buffer<TToken>> next) : this(buffer, 0, buffer.Length, next) { } public Buffer(TToken[] buffer, int index, int length, Func<Buffer<TToken>> next) { this._buffer = buffer; this._index = index; this.Count = length; this._next = new(next, false); } IEnumerator<TToken> IEnumerable<TToken>.GetEnumerator() => new ArraySegment<TToken>(this._buffer, this._index, this.Count).AsEnumerable().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.AsEnumerable().GetEnumerator(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ParsecSharp.Internal { public sealed class Buffer<TToken> : IReadOnlyList<TToken> { public static Buffer<TToken> Empty { get; } = new(Array.Empty<TToken>(), () => Empty); private readonly TToken[] _buffer; private readonly int _index; private readonly Lazy<Buffer<TToken>> _next; public TToken this[int index] => this._buffer[this._index + index]; public int Count { get; } public Buffer<TToken> Next => this._next.Value; public Buffer(TToken[] buffer, Func<Buffer<TToken>> next) : this(buffer, 0, buffer.Length, next) { } public Buffer(TToken[] buffer, int index, int length, Func<Buffer<TToken>> next) { this._buffer = buffer; this._index = index; this.Count = length; this._next = new(next, false); } IEnumerator<TToken> IEnumerable<TToken>.GetEnumerator() => new ArraySegment<TToken>(this._buffer, this._index, this.Count).AsEnumerable().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.AsEnumerable().GetEnumerator(); } }
mit
C#
6e645551e71729b7e87dae5be7738834b974676b
Update Pixel.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/api/Pixel.cs
src/api/Pixel.cs
// Contributors: // James Domingo, Green Code LLC namespace Landis.SpatialModeling { /// <summary> /// Base class for types of pixels. /// <example> /// </example> /// </summary> public abstract class Pixel { PixelBand[] bands; /// <summary> /// Sets the bands for the pixel. Derived classes should call this /// method in their constructors. /// </summary> /// <remarks> /// <example> /// <code><![CDATA[ /// public class MyPixel : Pixel /// { /// public Band<float> Slope = "slope : tangent of inclination angle (rise / run)"; /// public Band<short> Aspect = "aspect : degrees clockwise from north (0 to 359)"; /// /// public MyPixel() /// { /// SetBands(Slope, Aspect); /// } /// } /// ]]></code> /// </example> /// </remarks> /// <param name="bands"> /// An array of <see cref="PixelBand"/> /// </param> protected void SetBands(params PixelBand[] bands) { this.bands = (PixelBand[]) bands.Clone(); // Assign band numbers for (int i = 0; i < this.bands.Length; i++) { this.bands[i].Number = i + 1; } } /// <summary> /// The number of bands in the pixel. /// </summary> public int Count { get { return bands.Length; } } /// <summary> /// Gets the pixel band by its band number. /// </summary> /// <param name="bandNumber"> /// A <see cref="System.Int32"/> /// </param> public PixelBand this[int bandNumber] { get { return bands[bandNumber - 1]; } } } }
// Copyright 2010 Green Code LLC // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, Green Code LLC namespace Landis.SpatialModeling { /// <summary> /// Base class for types of pixels. /// <example> /// </example> /// </summary> public abstract class Pixel { PixelBand[] bands; /// <summary> /// Sets the bands for the pixel. Derived classes should call this /// method in their constructors. /// </summary> /// <remarks> /// <example> /// <code><![CDATA[ /// public class MyPixel : Pixel /// { /// public Band<float> Slope = "slope : tangent of inclination angle (rise / run)"; /// public Band<short> Aspect = "aspect : degrees clockwise from north (0 to 359)"; /// /// public MyPixel() /// { /// SetBands(Slope, Aspect); /// } /// } /// ]]></code> /// </example> /// </remarks> /// <param name="bands"> /// An array of <see cref="PixelBand"/> /// </param> protected void SetBands(params PixelBand[] bands) { this.bands = (PixelBand[]) bands.Clone(); // Assign band numbers for (int i = 0; i < this.bands.Length; i++) { this.bands[i].Number = i + 1; } } /// <summary> /// The number of bands in the pixel. /// </summary> public int Count { get { return bands.Length; } } /// <summary> /// Gets the pixel band by its band number. /// </summary> /// <param name="bandNumber"> /// A <see cref="System.Int32"/> /// </param> public PixelBand this[int bandNumber] { get { return bands[bandNumber - 1]; } } } }
apache-2.0
C#
bbc9f77cc8a688825633db84500d60a035e46f95
clean up code
CupWorks/GGJ2016
Game.Client/Program.cs
Game.Client/Program.cs
using System; using System.IO; namespace Game.Client { public class Program { private const int windowHeight = 30; private const int windowWidth = 80; private static void Main(string[] args) { var commandsFileStream = new FileStream("Commands.xml", FileMode.Open); var storyStepsFileStream = new FileStream("StorySteps.xml", FileMode.Open); var input = new ConsoleInput(); var game = new Core.Game( input, new ConsoleOutput(), commandsFileStream, storyStepsFileStream); game.Start(); CheckWindowSize (); do { Console.Write("> "); input.Read(Console.ReadLine()); CheckWindowSize(); } while (game.IsRunning); commandsFileStream.Close(); storyStepsFileStream.Close(); } static void CheckWindowSize() { if (Console.WindowHeight != windowHeight || Console.WindowWidth != windowWidth) { Console.SetWindowSize(windowWidth, windowHeight); } } } }
using System; using System.IO; namespace Game.Client { public class Program { private static void Main(string[] args) { var commandsFileStream = new FileStream("Commands.xml", FileMode.Open); var storyStepsFileStream = new FileStream("StorySteps.xml", FileMode.Open); var input = new ConsoleInput(); var game = new Core.Game( input, new ConsoleOutput(), commandsFileStream, storyStepsFileStream); game.Start(); var windowHeight = 30; var windowWidth = 80; do { Console.Write("> "); input.Read(Console.ReadLine()); if (Console.WindowHeight != windowHeight || Console.WindowWidth != windowWidth) { Console.WriteLine("Resseting to {0} x {1}", windowWidth, windowHeight); Console.SetWindowSize(windowWidth, windowHeight); } } while (game.IsRunning); commandsFileStream.Close(); storyStepsFileStream.Close(); } } }
mit
C#
e4a3b0b79a35ccd25cd84864bd806ff7b2943087
Fix weird english in test ignore comment
peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework.Tests/Visual/Platform/TestSceneExecutionModes.cs
osu.Framework.Tests/Visual/Platform/TestSceneExecutionModes.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when run headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when ran headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } } }
mit
C#
b2c7921c12ee022323eaf366718ae15ed106601c
fix .net test
lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds,lboss75/vds
vds.net/tests/test_vds_embedded.net/ScenarioTests.cs
vds.net/tests/test_vds_embedded.net/ScenarioTests.cs
using System; using Xunit; using vds_embedded.net; using System.IO; namespace test_vds_embedded.net { public class ScenarioTests { [Fact] public void ScenarionTests() { var api = new vds_api(); api.root_folder(Path.Combine(Directory.GetCurrentDirectory(), "servers")); api.server_root("[email protected]", "123"); } } }
using System; using Xunit; using vds_embedded.net; using System.IO; namespace test_vds_embedded.net { public class ScenarioTests { [Fact] public void ScenarionTests() { var api = new vds_api(); api.root_folder(Directory.GetCurrentDirectory()); api.server_root("[email protected]", "123"); } } }
mit
C#
cf7e03e348c0128b7a2eda3e5dc2dfab620debb6
Fix bad merge
ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework.Android/AndroidGameHost.cs
osu.Framework.Android/AndroidGameHost.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using Android.App; using Android.Content; using osu.Framework.Android.Graphics.Textures; using osu.Framework.Android.Graphics.Video; using osu.Framework.Android.Input; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Video; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using Uri = Android.Net.Uri; namespace osu.Framework.Android { public class AndroidGameHost : GameHost { private readonly AndroidGameView gameView; public AndroidGameHost(AndroidGameView gameView) { this.gameView = gameView; } protected override void SetupForRun() { base.SetupForRun(); AndroidGameWindow.View = gameView; Window = new AndroidGameWindow(); } protected override bool LimitedMemoryEnvironment => true; public override bool CanExit => false; public override bool OnScreenKeyboardOverlapsGameWindow => true; public override ITextInputSource GetTextInput() => new AndroidTextInput(gameView); protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() => new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) }; protected override Storage GetStorage(string baseName) => new AndroidStorage(baseName, this); public override void OpenFileExternally(string filename) => throw new NotImplementedException(); public override void OpenUrlExternally(string url) { var activity = (Activity)gameView.Context; using (var intent = new Intent(Intent.ActionView, Uri.Parse(url))) if (intent.ResolveActivity(activity.PackageManager) != null) activity.StartActivity(intent); } public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => new AndroidTextureLoaderStore(underlyingStore); public override VideoDecoder CreateVideoDecoder(Stream stream) => new AndroidVideoDecoder(stream); protected override void PerformExit(bool immediately) { // Do not exit on Android, Window.Run() does not block } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Android.App; using Android.Content; using osu.Framework.Android.Graphics.Textures; using osu.Framework.Android.Graphics.Video; using osu.Framework.Android.Input; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Video; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using Uri = Android.Net.Uri; namespace osu.Framework.Android { public class AndroidGameHost : GameHost { private readonly AndroidGameView gameView; public AndroidGameHost(AndroidGameView gameView) { this.gameView = gameView; } protected override void SetupForRun() { base.SetupForRun(); AndroidGameWindow.View = gameView; Window = new AndroidGameWindow(); } protected override bool LimitedMemoryEnvironment => true; public override bool CanExit => false; public override bool OnScreenKeyboardOverlapsGameWindow => true; public override ITextInputSource GetTextInput() => new AndroidTextInput(gameView); protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() => new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) }; protected override Storage GetStorage(string baseName) => new AndroidStorage(baseName, this); public override void OpenFileExternally(string filename) => throw new NotImplementedException(); public override void OpenUrlExternally(string url) { var activity = (Activity)gameView.Context; using (var intent = new Intent(Intent.ActionView, Uri.Parse(url))) if (intent.ResolveActivity(activity.PackageManager) != null) activity.StartActivity(intent); } public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => new AndroidTextureLoaderStore(underlyingStore); public override VideoDecoder CreateVideoDecoder(Stream stream) => new AndroidVideoDecoder(stream); protected override void PerformExit(bool immediately) { // Do not exit on Android, Window.Run() does not block } } }
mit
C#
fbee268a76813b78eedab7cb305986ad6decfab9
Clarify IBindable xml-doc
EVAST9919/osu-framework,paparony03/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,default0/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,default0/osu-framework,peppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,paparony03/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework
osu.Framework/Configuration/IBindable.cs
osu.Framework/Configuration/IBindable.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Configuration { /// <summary> /// An interface which can be bound to in order to watch for (and react to) value changes. /// </summary> public interface IBindable : IParseable { } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Configuration { /// <summary> /// Respresents a class which can be bound to in order to watch for (and react to) value changes. /// </summary> public interface IBindable : IParseable { } }
mit
C#
bc152a0c2de02efae5f5bc890ae273863bffb219
Bump version to 0.30.7
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.30.7"; } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.30.6"; } }
mit
C#
2e0532aeb7a3cc919b399ea6b7cb6adb1df69df0
Remove extra paragraph
ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework/Graphics/Primitives/IPolygon.cs
osu.Framework/Graphics/Primitives/IPolygon.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osuTK; namespace osu.Framework.Graphics.Primitives { public interface IPolygon { /// <summary> /// The vertices for this polygon that define the axes spanned by the polygon. /// </summary> /// <remarks> /// Must be returned in a clockwise orientation. For best performance, colinear edges should not be included. /// </remarks> ReadOnlySpan<Vector2> GetAxisVertices(); /// <summary> /// Retrieves the vertices of this polygon. /// </summary> /// <remarks> /// Must be returned in a clockwise orientation. /// </remarks> /// <returns>The vertices of this polygon.</returns> ReadOnlySpan<Vector2> GetVertices(); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osuTK; namespace osu.Framework.Graphics.Primitives { public interface IPolygon { /// <summary> /// The vertices for this polygon that define the axes spanned by the polygon. /// <para> /// </para> /// </summary> /// <remarks> /// Must be returned in a clockwise orientation. For best performance, colinear edges should not be included. /// </remarks> ReadOnlySpan<Vector2> GetAxisVertices(); /// <summary> /// Retrieves the vertices of this polygon. /// </summary> /// <remarks> /// Must be returned in a clockwise orientation. /// </remarks> /// <returns>The vertices of this polygon.</returns> ReadOnlySpan<Vector2> GetVertices(); } }
mit
C#
6a85906a425d37d33a7e916baeef10fb1afe87a9
fix to small
autumn009/TanoCSharpSamples
Chap37/ConstantInterpolatedStrings/ConstantInterpolatedStrings/Program.cs
Chap37/ConstantInterpolatedStrings/ConstantInterpolatedStrings/Program.cs
using System; const string a = "dream"; const string b = $"We have new {a}!"; Console.WriteLine(b);
using System; class Program { static void Main() { const string a = "dream"; const string b = $"We have new {a}!"; Console.WriteLine(b); } }
mit
C#
2955ff58af0be728ccce76b44387bfc6f985db6f
Update logging message.
sirarsalih/Hackathons,sirarsalih/Hackathons,sirarsalih/Hackathons
Faghelg-2015/signalr-server/SignalRServer/Views/Home/ImageCarousel.cshtml
Faghelg-2015/signalr-server/SignalRServer/Views/Home/ImageCarousel.cshtml
 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <link href="~/Content/screen.css" rel="stylesheet" /> <script src="~/Scripts/lib.min.js"></script> <script src="~/Scripts/app.min.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script> <script src="~/signalr/hubs"></script> <title>| PhotoBooth</title> </head> <body> <header class="main-header"> <a href="#" data-action="snap">Ta nytt bilde</a> </header> <div class="container"> <div class="images"> @foreach (var imageContent in ViewBag.ImageContents) { <div class="image"><div class="maintain-aspect ratio4_3"><a href="@Url.Action("ShowImage", "Send", new { imageId = imageContent.ImageId })" class="swipebox" title="Photobooth"><img src="@Url.Action("ShowImage", "Send", new { imageId = imageContent.ImageId })" alt="image"></a></div></div> } </div> <button data-action="autoplay"> Autoplay </button> <a href="admin.html">admin</a> </div> </body> </html> <script type="text/javascript"> $.connection.hub.start(); $.connection.imageHub.client.addNewImageToPage = function (imageId) { var url = '@Url.Action("ShowImage", "Send")?imageId=' + imageId; $('.images').prepend('<div class="image"><div class="maintain-aspect ratio4_3"><a href=' + url + ' class="swipebox" title="Photobooth"><img src=' + url +' alt="image"></a></div></div>'); }; $("[data-action=snap]").click(function() { $.post('@Url.Action("TakePicture", "Send")', { }, function () { console.log("Picture taken") }); }); </script>
 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <link href="~/Content/screen.css" rel="stylesheet" /> <script src="~/Scripts/lib.min.js"></script> <script src="~/Scripts/app.min.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script> <script src="~/signalr/hubs"></script> <title>| PhotoBooth</title> </head> <body> <header class="main-header"> <a href="#" data-action="snap">Ta nytt bilde</a> </header> <div class="container"> <div class="images"> @foreach (var imageContent in ViewBag.ImageContents) { <div class="image"><div class="maintain-aspect ratio4_3"><a href="@Url.Action("ShowImage", "Send", new { imageId = imageContent.ImageId })" class="swipebox" title="Photobooth"><img src="@Url.Action("ShowImage", "Send", new { imageId = imageContent.ImageId })" alt="image"></a></div></div> } </div> <button data-action="autoplay"> Autoplay </button> <a href="admin.html">admin</a> </div> </body> </html> <script type="text/javascript"> $.connection.hub.start(); $.connection.imageHub.client.addNewImageToPage = function (imageId) { var url = '@Url.Action("ShowImage", "Send")?imageId=' + imageId; $('.images').prepend('<div class="image"><div class="maintain-aspect ratio4_3"><a href=' + url + ' class="swipebox" title="Photobooth"><img src=' + url +' alt="image"></a></div></div>'); }; $("[data-action=snap]").click(function() { $.post('@Url.Action("TakePicture", "Send")', { }, function () { console.log("Test") }); }); </script>
mit
C#
7b89068485dc846c8485e19b9f1e4a5f6128d0e3
Add note about EmployeeID property using
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Employee/components/EmployeeSettings.cs
R7.University.Employee/components/EmployeeSettings.cs
using System; using DotNetNuke.Entities.Modules; using DotNetNuke.UI.Modules; using DotNetNuke.Common.Utilities; using R7.University; namespace R7.University.Employee { /// <summary> /// Provides strong typed access to settings used by module /// </summary> public partial class EmployeeSettings : SettingsWrapper { public EmployeeSettings (IModuleControl module) : base (module) { } public EmployeeSettings (ModuleInfo module) : base (module) { } #region Properties for settings private int? employeeId; /// <summary> /// Gets or sets the EmployeeID setting value. /// Use <see cref="EmployeePortalModuleBase.GetEmployee()"/> /// and <see cref="EmployeePortalModuleBase.GetEmployeeId()"/> /// to get employee info in the view contols. /// </summary> /// <value>The employee Id.</value> public int EmployeeID { get { if (employeeId == null) employeeId = ReadSetting<int> ("Employee_EmployeeID", Null.NullInteger, false); return employeeId.Value; } set { WriteSetting<int> ("Employee_EmployeeID", value, false); employeeId = value; } } public bool ShowCurrentUser { get { return ReadSetting<bool> ("Employee_ShowCurrentUser", false, false); } set { WriteSetting<bool> ("Employee_ShowCurrentUser", value, false); } } public bool AutoTitle { get { return ReadSetting<bool> ("Employee_AutoTitle", true, false); } set { WriteSetting<bool> ("Employee_AutoTitle", value, false); } } public int PhotoWidth { // REVIEW: Need a way to customize default settings like PhotoWidth get { return ReadSetting<int> ("Employee_PhotoWidth", 192, true); } set { WriteSetting<int> ("Employee_PhotoWidth", value, true); } } private int? dataCacheTime; public int DataCacheTime { get { if (dataCacheTime == null) dataCacheTime = ReadSetting<int> ("Employee_DataCacheTime", 1200, true); return dataCacheTime.Value; } set { WriteSetting<int> ("Employee_DataCacheTime", value, true); dataCacheTime = value; } } #endregion } }
using System; using DotNetNuke.Entities.Modules; using DotNetNuke.UI.Modules; using DotNetNuke.Common.Utilities; using R7.University; namespace R7.University.Employee { /// <summary> /// Provides strong typed access to settings used by module /// </summary> public partial class EmployeeSettings : SettingsWrapper { public EmployeeSettings (IModuleControl module) : base (module) { } public EmployeeSettings (ModuleInfo module) : base (module) { } #region Properties for settings private int? employeeId; public int EmployeeID { get { if (employeeId == null) employeeId = ReadSetting<int> ("Employee_EmployeeID", Null.NullInteger, false); return employeeId.Value; } set { WriteSetting<int> ("Employee_EmployeeID", value, false); employeeId = value; } } public bool ShowCurrentUser { get { return ReadSetting<bool> ("Employee_ShowCurrentUser", false, false); } set { WriteSetting<bool> ("Employee_ShowCurrentUser", value, false); } } public bool AutoTitle { get { return ReadSetting<bool> ("Employee_AutoTitle", true, false); } set { WriteSetting<bool> ("Employee_AutoTitle", value, false); } } public int PhotoWidth { // REVIEW: Need a way to customize default settings like PhotoWidth get { return ReadSetting<int> ("Employee_PhotoWidth", 192, true); } set { WriteSetting<int> ("Employee_PhotoWidth", value, true); } } private int? dataCacheTime; public int DataCacheTime { get { if (dataCacheTime == null) dataCacheTime = ReadSetting<int> ("Employee_DataCacheTime", 1200, true); return dataCacheTime.Value; } set { WriteSetting<int> ("Employee_DataCacheTime", value, true); dataCacheTime = value; } } #endregion } }
agpl-3.0
C#
7f7ad46c678a9c72b4a443d7ee1627cb6e2c50d8
Update ClassesToStringConverter.cs
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
samples/BehaviorsTestApplication/Converters/ClassesToStringConverter.cs
samples/BehaviorsTestApplication/Converters/ClassesToStringConverter.cs
using System; using System.Collections.Generic; using System.Globalization; using Avalonia; using Avalonia.Controls; using Avalonia.Data.Converters; namespace BehaviorsTestApplication.Converters; public class ClassesToStringConverter : IMultiValueConverter { public static ClassesToStringConverter Instance = new(); public object Convert(IList<object?>? values, Type targetType, object? parameter, CultureInfo culture) { if (values?.Count == 2 && values[0] is int && values[1] is Classes classes) { return string.Join(" ", classes); } return AvaloniaProperty.UnsetValue; } }
using System; using System.Collections.Generic; using System.Globalization; using Avalonia; using Avalonia.Controls; using Avalonia.Data.Converters; namespace BehaviorsTestApplication.Converters; public class ClassesToStringConverter : IMultiValueConverter { public static ClassesToStringConverter Instance = new(); public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture) { if (values.Count == 2 && values[0] is int && values[1] is Classes classes) { return string.Join(" ", classes); } return AvaloniaProperty.UnsetValue; } }
mit
C#
494cfee5bee542c9e32c5beafff1d223faf9d638
Remove broken Sequence
sharper-library/Sharper.C.Chain
Sharper.C.Chain.Testing/Testing/ChainTestingModule.cs
Sharper.C.Chain.Testing/Testing/ChainTestingModule.cs
using System; using System.Collections.Generic; using System.Linq; using FsCheck; using Fuchu; namespace Sharper.C.Testing { using static Data.ChainModule; using static SystemArbitraryModule; public static class ChainTestingModule { public static Test WithoutOverflow<A>(this string label, Func<Chain<A>> f) => label.Group ( Test.Case("Build", () => f()) , Test.Case("Evaluate", () => f().Eval().Skip(1000000)) ); public static Arbitrary<Chain<A>> AnyChain<A>(Arbitrary<A> arbA) => AnySeq(arbA).Convert ( xs => xs.Aggregate(EndChain<A>(), (s, a) => YieldLink(a, s)) , s => s.Eval() ); } }
using System; using System.Collections.Generic; using System.Linq; using FsCheck; using Fuchu; namespace Sharper.C.Testing { using static Data.ChainModule; using static Data.EnumerableModule; using static SystemArbitraryModule; public static class ChainTestingModule { public static Test WithoutOverflow<A>(this string label, Func<Chain<A>> f) => label.Group ( Test.Case("Build", () => f()) , Test.Case("Evaluate", () => f().Eval().Skip(1000000)) ); public static Arbitrary<Chain<A>> AnyChain<A>(Arbitrary<A> arbA) => AnySeq(arbA).Convert ( xs => xs.Aggregate(EndChain<A>(), (s, a) => YieldLink(a, s)) , s => s.Eval() ); public static Gen<Chain<A>> Sequence<A>(Chain<Gen<A>> xs) => xs.Eval().FoldRight ( Gen.Constant(EndChain<A>()) , (ga, x) => x.Map ( gsa => from sa in gsa from a in ga select YieldLink(a, sa) ) ) .Eval(); public static Gen<IEnumerable<A>> Sequence<A>(IEnumerable<Gen<A>> xs) => Sequence(xs.ToChain()).Select(sa => sa.Eval()); } }
mit
C#
41be9b3f8f08dd691a38ab1ff50872d126fe9f2e
Add asserts to the test scene
ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu
osu.Game.Tests/Visual/UserInterface/TestScenePageSelector.cs
osu.Game.Tests/Visual/UserInterface/TestScenePageSelector.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Game.Graphics.UserInterface; using osu.Framework.Graphics; namespace osu.Game.Tests.Visual.UserInterface { public class TestScenePageSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(PageSelector) }; private readonly PageSelector pageSelector; public TestScenePageSelector() { Child = pageSelector = new PageSelector { Anchor = Anchor.Centre, Origin = Anchor.Centre, }; AddStep("10 max pages", () => setMaxPages(10)); AddStep("200 max pages, current 199", () => { setMaxPages(200); setCurrentPage(199); }); AddStep("200 max pages, current 201", () => { setMaxPages(200); setCurrentPage(201); }); AddAssert("Current equals max", () => pageSelector.CurrentPage.Value == pageSelector.MaxPages.Value); AddStep("200 max pages, current -10", () => { setMaxPages(200); setCurrentPage(-10); }); AddAssert("Current is 1", () => pageSelector.CurrentPage.Value == 1); AddStep("-10 max pages", () => { setMaxPages(-10); }); AddAssert("Current is 1, max is 1", () => pageSelector.CurrentPage.Value == 1 && pageSelector.MaxPages.Value == 1); } private void setMaxPages(int maxPages) => pageSelector.MaxPages.Value = maxPages; private void setCurrentPage(int currentPage) => pageSelector.CurrentPage.Value = currentPage; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Game.Graphics.UserInterface; using osu.Framework.Graphics; namespace osu.Game.Tests.Visual.UserInterface { public class TestScenePageSelector : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(PageSelector) }; private readonly PageSelector pageSelector; public TestScenePageSelector() { Child = pageSelector = new PageSelector { Anchor = Anchor.Centre, Origin = Anchor.Centre, }; AddStep("10 max pages", () => setMaxPages(10)); AddStep("200 max pages, current 199", () => { setMaxPages(200); setCurrentPage(199); }); AddStep("200 max pages, current 201", () => { setMaxPages(200); setCurrentPage(201); }); AddStep("200 max pages, current -10", () => { setMaxPages(200); setCurrentPage(-10); }); AddStep("-10 max pages", () => { setMaxPages(-10); }); } private void setMaxPages(int maxPages) => pageSelector.MaxPages.Value = maxPages; private void setCurrentPage(int currentPage) => pageSelector.CurrentPage.Value = currentPage; } }
mit
C#
200592114f9e20d0f2ede64a70135f50f0319e00
Make protected variables private
peppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu
osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.cs
osu.Game/Graphics/Containers/Markdown/OsuMarkdownLinkText.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using Markdig.Syntax.Inlines; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Online.Chat; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownLinkText : MarkdownLinkText { [Resolved(canBeNull: true)] private OsuGame game { get; set; } private readonly string text; private readonly string title; public OsuMarkdownLinkText(string text, LinkInline linkInline) : base(text, linkInline) { this.text = text; title = linkInline.Title; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { var textDrawable = CreateSpriteText().With(t => t.Text = text); InternalChildren = new Drawable[] { textDrawable, new OsuMarkdownLinkCompiler(new[] { textDrawable }) { RelativeSizeAxes = Axes.Both, Action = OnLinkPressed, TooltipText = title ?? Url, } }; } protected override void OnLinkPressed() => game?.HandleLink(Url); private class OsuMarkdownLinkCompiler : DrawableLinkCompiler { public OsuMarkdownLinkCompiler(IEnumerable<Drawable> parts) : base(parts) { } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { IdleColour = colourProvider.Light2; HoverColour = colourProvider.Light1; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using Markdig.Syntax.Inlines; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers.Markdown; using osu.Game.Online.Chat; using osu.Game.Overlays; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownLinkText : MarkdownLinkText { [Resolved(canBeNull: true)] private OsuGame game { get; set; } protected string Text; protected string Title; public OsuMarkdownLinkText(string text, LinkInline linkInline) : base(text, linkInline) { Text = text; Title = linkInline.Title; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { var text = CreateSpriteText().With(t => t.Text = Text); InternalChildren = new Drawable[] { text, new OsuMarkdownLinkCompiler(new[] { text }) { RelativeSizeAxes = Axes.Both, Action = OnLinkPressed, TooltipText = Title ?? Url, } }; } protected override void OnLinkPressed() => game?.HandleLink(Url); private class OsuMarkdownLinkCompiler : DrawableLinkCompiler { public OsuMarkdownLinkCompiler(IEnumerable<Drawable> parts) : base(parts) { } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { IdleColour = colourProvider.Light2; HoverColour = colourProvider.Light1; } } } }
mit
C#
45b58341b67c86dad12d46267215527ba3d1dee2
Update Index.cshtml
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Home/Index.cshtml
Anlab.Mvc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p> <p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and waste water, and feed in support of agricultural and environmental research.</p> <p>For new clients, please note the drop-down menu under “Lab Information” which contains an “Order Completion Help” section to help guide you in creating a work order. Also helpful under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides brief descriptions of our current methods.</p> <p>Please feel free to contact the lab with any questions.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:[email protected]">[email protected]</a></p> <p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br> Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p> </address> <p><a href="/media/pdf/UC-Davis-Analytical-Laboratory-Handout.pdf" target="_blank" title="Anlab Flyer"><div><img src="~/Images/AnlabFlyerThumb.png"/><br/>Lab Flyer</div> </a></p> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> Update posted: June 29, 2021<br /><br /> <strong>Please Note Holiday Closure Information:</strong><br /><br /> The Lab will be closed on July 5, 2021<br /> </div> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>The laboratory is located in Hoagland Hall with a Sample Receiving area in nearby Hoagland Annex. </p> <p>The laboratory performs analyses on selected chemical constituents of soil, plant, water and waste water, and feed in support of agricultural and environmental research.</p> <p>For new clients, please note the drop-down menu under “Lab Information” which contains an “Order Completion Help” section to help guide you in creating a work order. Also helpful under the “Lab Information” drop-down menu is the “Methods of Analysis” section which provides brief descriptions of our current methods.</p> <p>Please feel free to contact the lab with any questions.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:[email protected]">[email protected]</a></p> <p>Receiving Hours: 8am - 5pm M - F, </br> except University holidays </br> Sample Receiving Area: Hoagland Annex, </br>Phone: 530-752-0266</p> </address> <p><a href="/media/pdf/UC-Davis-Analytical-Laboratory-Handout.pdf" target="_blank" title="Anlab Flyer"><div><img src="~/Images/AnlabFlyerThumb.png"/><br/>Lab Flyer</div> </a></p> </div>
mit
C#
cca9e2e87d2f456c29b5e5bad518a137c541a1bd
Remove annoying unnecessary logging
knexer/TimeLoopIncremental
Assets/Scripts/Grid/GridOutput.cs
Assets/Scripts/Grid/GridOutput.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GridPositionComponent))] [RequireComponent(typeof(ResourceSink))] public class GridOutput : MonoBehaviour { private ResourceStorage ItemDestination; private ResourceSink ItemSource; // Use this for initialization void Start () { ItemDestination = GetComponentInParent<ResourceStorage>(); ItemSource = GetComponent<ResourceSink>(); ItemSource.DeliverItem = (item) => { ItemDestination.AddResource(item.ResourceType, 1); Destroy(item.gameObject); return true; }; } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(GridPositionComponent))] [RequireComponent(typeof(ResourceSink))] public class GridOutput : MonoBehaviour { private ResourceStorage ItemDestination; private ResourceSink ItemSource; // Use this for initialization void Start () { ItemDestination = GetComponentInParent<ResourceStorage>(); ItemSource = GetComponent<ResourceSink>(); ItemSource.DeliverItem = (item) => { Debug.Log(new System.Diagnostics.StackTrace()); Debug.Log(ItemDestination); Debug.Log(item); ItemDestination.AddResource(item.ResourceType, 1); Destroy(item.gameObject); return true; }; } // Update is called once per frame void Update () { } }
mit
C#
73bc2733143b2f7d27ab04dd6fdc2da571c603e4
Remove Utilities.GetRelativePieceValue
ProgramFOX/Chess.NET
ChessDotNet/Utilities.cs
ChessDotNet/Utilities.cs
using System; namespace ChessDotNet { public static class Utilities { public static void ThrowIfNull(object value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } } public static Player GetOpponentOf(Player player) { if (player == Player.None) throw new ArgumentException("`player` cannot be Player.None."); return player == Player.White ? Player.Black : Player.White; } } }
using System; namespace ChessDotNet { public static class Utilities { public static void ThrowIfNull(object value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } } public static Player GetOpponentOf(Player player) { if (player == Player.None) throw new ArgumentException("`player` cannot be Player.None."); return player == Player.White ? Player.Black : Player.White; } public static int GetRelativePieceValue(ChessPiece piece) { return GetRelativePieceValue(piece.Piece); } public static int GetRelativePieceValue(Piece piece) { switch (piece) { case Piece.King: return int.MaxValue; case Piece.Queen: return 9; case Piece.Rook: return 5; case Piece.Knight: case Piece.Bishop: return 3; case Piece.Pawn: return 1; default: return 0; } } } }
mit
C#
2a7c2921cd12d16190d3bb7f8d9cc358fa4dce9a
Split out message printing into PrintMessage()
mono/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,arfbtwn/dbus-sharp
src/Monitor.cs
src/Monitor.cs
// Copyright 2006 Alp Toker <[email protected]> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr = Address.SessionBus; if (args.Length == 1) { string arg = args[0]; switch (arg) { case "--system": addr = Address.SystemBus; break; case "--session": addr = Address.SessionBus; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]"); Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used."); return; } } Connection conn = new Connection (false); conn.Open (addr); conn.Authenticate (); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; Bus bus = conn.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; bus.Hello (); //hack to process the NameAcquired signal synchronously conn.HandleSignal (conn.ReadMessage ()); if (args.Length > 1) { //install custom match rules only for (int i = 1 ; i != args.Length ; i++) bus.AddMatch (args[i]); } else { //no custom match rules, install the defaults bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); } while (true) { Message msg = conn.ReadMessage (); PrintMessage (msg); Console.WriteLine (); } } public static void PrintMessage (Message msg) { Console.WriteLine ("Message:"); Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine ("\t" + hf.Code + ": " + hf.Value); foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields) Console.WriteLine ("\t" + field.Key + ": " + field.Value); if (msg.Body != null) { Console.WriteLine ("\tBody:"); MessageReader reader = new MessageReader (msg); //TODO: this needs to be done more intelligently try { foreach (DType dtype in msg.Signature.Data) { if (dtype == DType.Invalid) continue; object arg; reader.GetValue (dtype, out arg); Console.WriteLine ("\t\t" + dtype + ": " + arg); } } catch { Console.WriteLine ("\t\tmonitor is too dumb to decode message body"); } } } }
// Copyright 2006 Alp Toker <[email protected]> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr = Address.SessionBus; if (args.Length == 1) { string arg = args[0]; switch (arg) { case "--system": addr = Address.SystemBus; break; case "--session": addr = Address.SessionBus; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]"); Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used."); return; } } Connection conn = new Connection (false); conn.Open (addr); conn.Authenticate (); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; Bus bus = conn.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; bus.Hello (); //hack to process the NameAcquired signal synchronously conn.HandleSignal (conn.ReadMessage ()); if (args.Length > 1) { //install custom match rules only for (int i = 1 ; i != args.Length ; i++) bus.AddMatch (args[i]); } else { //no custom match rules, install the defaults bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); } while (true) { Message msg = conn.ReadMessage (); Console.WriteLine ("Message:"); Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine ("\t" + hf.Code + ": " + hf.Value); foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields) Console.WriteLine ("\t" + field.Key + ": " + field.Value); if (msg.Body != null) { Console.WriteLine ("\tBody:"); MessageReader reader = new MessageReader (msg); //TODO: this needs to be done more intelligently try { foreach (DType dtype in msg.Signature.Data) { if (dtype == DType.Invalid) continue; object arg; reader.GetValue (dtype, out arg); Console.WriteLine ("\t\t" + dtype + ": " + arg); } } catch { Console.WriteLine ("\t\tmonitor is too dumb to decode message body"); } } Console.WriteLine (); } } }
mit
C#
9bc50936435663f8d27091e65bf886cb1f6a3c2f
Remove unused constructor.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Tor/Socks5/Models/Messages/VersionMethodRequest.cs
WalletWasabi/Tor/Socks5/Models/Messages/VersionMethodRequest.cs
using System; using System.Linq; using WalletWasabi.Helpers; using WalletWasabi.Tor.Socks5.Models.Bases; using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields; using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields; namespace WalletWasabi.Tor.Socks5.Models.Messages { public class VersionMethodRequest : ByteArraySerializableBase { #region Constructors public VersionMethodRequest(MethodsField methods) { Methods = Guard.NotNull(nameof(methods), methods); Ver = VerField.Socks5; // The NMETHODS field contains the number of method identifier octets that appear in the METHODS field. NMethods = new NMethodsField(methods); } #endregion Constructors #region PropertiesAndMembers public VerField Ver { get; set; } public NMethodsField NMethods { get; set; } public MethodsField Methods { get; set; } #endregion PropertiesAndMembers #region Serialization public override void FromBytes(byte[] bytes) { Guard.NotNullOrEmpty(nameof(bytes), bytes); Guard.InRangeAndNotNull($"{nameof(bytes)}.{nameof(bytes.Length)}", bytes.Length, 3, 257); Ver = new VerField(bytes[0]); NMethods = new NMethodsField(bytes[1]); if (NMethods.Value != bytes.Length - 2) { throw new FormatException($"{nameof(NMethods)}.{nameof(NMethods.Value)} must be {nameof(bytes)}.{nameof(bytes.Length)} - 2 = {bytes.Length - 2}. Actual: {NMethods.Value}."); } Methods = new MethodsField(); Methods.FromBytes(bytes.Skip(2).ToArray()); } public override byte[] ToBytes() => ByteHelpers.Combine( new byte[] { Ver.ToByte(), NMethods.ToByte() }, Methods.ToBytes()); #endregion Serialization } }
using System; using System.Linq; using WalletWasabi.Helpers; using WalletWasabi.Tor.Socks5.Models.Bases; using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields; using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields; namespace WalletWasabi.Tor.Socks5.Models.Messages { public class VersionMethodRequest : ByteArraySerializableBase { #region Constructors public VersionMethodRequest() { } public VersionMethodRequest(MethodsField methods) { Methods = Guard.NotNull(nameof(methods), methods); Ver = VerField.Socks5; // The NMETHODS field contains the number of method identifier octets that appear in the METHODS field. NMethods = new NMethodsField(methods); } #endregion Constructors #region PropertiesAndMembers public VerField Ver { get; set; } public NMethodsField NMethods { get; set; } public MethodsField Methods { get; set; } #endregion PropertiesAndMembers #region Serialization public override void FromBytes(byte[] bytes) { Guard.NotNullOrEmpty(nameof(bytes), bytes); Guard.InRangeAndNotNull($"{nameof(bytes)}.{nameof(bytes.Length)}", bytes.Length, 3, 257); Ver = new VerField(bytes[0]); NMethods = new NMethodsField(bytes[1]); if (NMethods.Value != bytes.Length - 2) { throw new FormatException($"{nameof(NMethods)}.{nameof(NMethods.Value)} must be {nameof(bytes)}.{nameof(bytes.Length)} - 2 = {bytes.Length - 2}. Actual: {NMethods.Value}."); } Methods = new MethodsField(); Methods.FromBytes(bytes.Skip(2).ToArray()); } public override byte[] ToBytes() => ByteHelpers.Combine( new byte[] { Ver.ToByte(), NMethods.ToByte() }, Methods.ToBytes()); #endregion Serialization } }
mit
C#
4524e790f28fd176682bc1986122336fc71217fc
Test all node types
turtle-box-games/leaf-csharp
Leaf/Leaf.Tests/ContainerTests.cs
Leaf/Leaf.Tests/ContainerTests.cs
using System; using System.Collections.Generic; using System.Linq; using Leaf.Nodes; using NUnit.Framework; namespace Leaf.Tests { [TestFixture(TestOf = typeof(Container))] public class ContainerTests { [Test(Description = "Verify that the constructor throws an exception when the root node is null.")] public void NullRootTest() { Assert.That(() => { new Container(null); }, Throws.ArgumentNullException); } [Test(Description = "Verify that the root node property is set properly.")] [TestCaseSource(nameof(AllNodes))] public Node RootNodeTest(Node root) { var container = new Container(root); return container.Root; } private static IEnumerable<TestCaseData> AllNodes() { var randomizer = TestContext.CurrentContext.Random; foreach (var type in Enum.GetValues(typeof(NodeType)).Cast<NodeType>()) { if (type == NodeType.End) continue; var node = randomizer.NextNodeOfType(type); yield return new TestCaseData(node).Returns(node); } } } }
using Leaf.Nodes; using NUnit.Framework; namespace Leaf.Tests { [TestFixture(TestOf = typeof(Container))] public class ContainerTests { [Test(Description = "Verify that the constructor throws an exception when the root node is null.")] public void NullRootTest() { Assert.That(() => { new Container(null); }, Throws.ArgumentNullException); } [Test(Description = "Verify that the root node property is set properly.")] public void RootNodeTest() { var root = new Int32Node(50); var container = new Container(root); Assert.That(container.Root, Is.EqualTo(root)); } } }
mit
C#
b8f21bee0313c747bc7482dc313a7ea87f6d7bf6
Update warning code for obsolete property in #pragma.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.Server.KestrelTests/KestrelServerOptionsTests.cs
test/Microsoft.AspNetCore.Server.KestrelTests/KestrelServerOptionsTests.cs
// Copyright (c) .NET Foundation. 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.Linq; using System.Reflection; using Microsoft.AspNetCore.Server.Kestrel; using Xunit; namespace Microsoft.AspNetCore.Server.KestrelTests { public class KestrelServerInformationTests { #pragma warning disable CS0618 [Fact] public void MaxRequestBufferSizeIsMarkedObsolete() { Assert.NotNull(typeof(KestrelServerOptions) .GetProperty(nameof(KestrelServerOptions.MaxRequestBufferSize)) .GetCustomAttributes(false) .OfType<ObsoleteAttribute>() .SingleOrDefault()); } [Fact] public void MaxRequestBufferSizeGetsLimitsProperty() { var o = new KestrelServerOptions(); o.Limits.MaxRequestBufferSize = 42; Assert.Equal(42, o.MaxRequestBufferSize); } [Fact] public void MaxRequestBufferSizeSetsLimitsProperty() { var o = new KestrelServerOptions(); o.MaxRequestBufferSize = 42; Assert.Equal(42, o.Limits.MaxRequestBufferSize); } #pragma warning restore CS0612 [Fact] public void SetThreadCountUsingProcessorCount() { // Ideally we'd mock Environment.ProcessorCount to test edge cases. var expected = Clamp(Environment.ProcessorCount >> 1, 1, 16); var information = new KestrelServerOptions(); Assert.Equal(expected, information.ThreadCount); } private static int Clamp(int value, int min, int max) { return value < min ? min : value > max ? max : value; } } }
// Copyright (c) .NET Foundation. 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.Linq; using System.Reflection; using Microsoft.AspNetCore.Server.Kestrel; using Xunit; namespace Microsoft.AspNetCore.Server.KestrelTests { public class KestrelServerInformationTests { #pragma warning disable CS0612 [Fact] public void MaxRequestBufferSizeIsMarkedObsolete() { Assert.NotNull(typeof(KestrelServerOptions) .GetProperty(nameof(KestrelServerOptions.MaxRequestBufferSize)) .GetCustomAttributes(false) .OfType<ObsoleteAttribute>() .SingleOrDefault()); } [Fact] public void MaxRequestBufferSizeGetsLimitsProperty() { var o = new KestrelServerOptions(); o.Limits.MaxRequestBufferSize = 42; Assert.Equal(42, o.MaxRequestBufferSize); } [Fact] public void MaxRequestBufferSizeSetsLimitsProperty() { var o = new KestrelServerOptions(); o.MaxRequestBufferSize = 42; Assert.Equal(42, o.Limits.MaxRequestBufferSize); } #pragma warning restore CS0612 [Fact] public void SetThreadCountUsingProcessorCount() { // Ideally we'd mock Environment.ProcessorCount to test edge cases. var expected = Clamp(Environment.ProcessorCount >> 1, 1, 16); var information = new KestrelServerOptions(); Assert.Equal(expected, information.ThreadCount); } private static int Clamp(int value, int min, int max) { return value < min ? min : value > max ? max : value; } } }
apache-2.0
C#
89cd8ed597c12947447183f8e08a395b99409d88
Correct tabs to spaces in test.
eylvisaker/AgateLib
AgateLib.Tests/UnitTests/UserInterface/DataModel/ConfigFacetReadingTests.cs
AgateLib.Tests/UnitTests/UserInterface/DataModel/ConfigFacetReadingTests.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AgateLib.DisplayLib.BitmapFont; using AgateLib.IO; using AgateLib.UserInterface; using AgateLib.UserInterface.DataModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using YamlDotNet.Serialization; namespace AgateLib.UnitTests.UserInterface.DataModel { [TestClass] public class ConfigFacetReadingTests { string filename = "test.yaml"; string yaml = @" facets: TestGui: window_1: type: window x: 10 y: 10 width: 250 height: 400 window_2: type: window x: 270 y: 10 width: 275 height: 300 children: menu_1: type: menu dock: fill "; [TestInitialize] public void Initialize() { var fileProvider = new Mock<IReadFileProvider>(); fileProvider .Setup(x => x.OpenReadAsync(filename)) .Returns(() => Task.FromResult((Stream)new MemoryStream(Encoding.UTF8.GetBytes(yaml)))); Assets.UserInterfaceAssets = fileProvider.Object; } [TestMethod] public void ReadFacetModel() { var configModel = UserInterfaceDataLoader.Config(filename); Assert.AreEqual(1, configModel.Facets.Count); Assert.AreEqual("TestGui", configModel.Facets.Keys.First()); var gui = configModel.Themes["TestGui"]; var window1 = gui["window_1"]; var window2 = gui["window_2"]; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AgateLib.DisplayLib.BitmapFont; using AgateLib.IO; using AgateLib.UserInterface; using AgateLib.UserInterface.DataModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using YamlDotNet.Serialization; namespace AgateLib.UnitTests.UserInterface.DataModel { [TestClass] public class ConfigFacetReadingTests { string filename = "test.yaml"; string yaml = @" facets: TestGui: window_1: type: window x: 10 y: 10 width: 250 height: 400 window_2: type: window x: 270 y: 10 width: 275 height: 300 children: - menu_1: type: menu dock: fill "; [TestInitialize] public void Initialize() { var fileProvider = new Mock<IReadFileProvider>(); fileProvider .Setup(x => x.OpenReadAsync(filename)) .Returns(() => Task.FromResult((Stream)new MemoryStream(Encoding.UTF8.GetBytes(yaml)))); Assets.UserInterfaceAssets = fileProvider.Object; } [TestMethod] public void ReadFacetModel() { var configModel = UserInterfaceDataLoader.Config(filename); Assert.AreEqual(1, configModel.Facets.Count); Assert.AreEqual("TestGui", configModel.Facets.Keys.First()); var gui = configModel.Themes["TestGui"]; var window1 = gui["window_1"]; var window2 = gui["window_2"]; } } }
mit
C#
1402a920f6a97807c65c3167681e59f7f7e41f94
Fix - forgot to commit version change to 0.2.1.
VictorZakharov/pinwin
PinWin/Properties/AssemblyInfo.cs
PinWin/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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // 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.2.1")] [assembly: AssemblyFileVersion("0.2.1")]
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("PinWin")] [assembly: AssemblyDescription("Allows user to make desktop windows top most")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PinWin")] [assembly: AssemblyCopyright("Copyright © Victor Zakharov 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ae6966c-0686-4ac4-afbb-9ffd7bf7b81c")] // 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.2.0")] [assembly: AssemblyFileVersion("0.2.0")]
mit
C#
91152d3a65dcdbc989602c57379bbb5462a95303
Add additional tests to delegate call data flow
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
csharp/ql/test/library-tests/dataflow/delegates/DelegateFlow.cs
csharp/ql/test/library-tests/dataflow/delegates/DelegateFlow.cs
using System; class DelegateFlow { void M1(int i) { } static void M2(Action<int> a) { a(0); a = _ => { }; a(1); } void M3() { M2(_ => { }); M2(M1); } void M4(Action<int> a) { M2(a); } void M5() { M4(_ => { }); M4(M1); } void M6(Action<Action<int>> aa, Action<int> a) { aa(a); } void M7() { M6(a => { a(1); }, M1); } Action<int> Prop { get { return _ => { }; } set { value(0); } } void M8() { dynamic d = this; d.Prop = d.Prop; } static Func<Action<int>> F = () => _ => { }; void M9() { F()(0); } Action<int> M10() { return _ => { }; } void M11() { M10()(0); } public delegate void EventHandler(); public event EventHandler Click; public void M12() { Click += M11; Click(); M13(M9); } public void M13(EventHandler eh) { Click += eh; Click(); } public void M13() { void M14(MyDelegate d) => d(); M14(new MyDelegate(M9)); M14(new MyDelegate(new MyDelegate(M11))); M14(M12); M14(() => { }); } public void M14() { void LocalFunction(int i) { }; M2(LocalFunction); } public void M15() { Func<int> f = () => 42; new Lazy<int>(f); f = () => 43; new Lazy<int>(f); } public delegate void MyDelegate(); public unsafe void M16(delegate*<Action<int>, void> fnptr, Action<int> a) { fnptr(a); } public unsafe void M17() { M16(&M2, (i) => {}); // MISSING: a(0) in M2 is calling this lambda } public unsafe void M18() { delegate*<Action<int>, void> fnptr = &M2; fnptr((i) => {}); // MISSING: a(0) in M2 is calling this lambda } }
using System; class DelegateFlow { void M1(int i) { } void M2(Action<int> a) { a(0); a = _ => { }; a(0); } void M3() { M2(_ => { }); M2(M1); } void M4(Action<int> a) { M2(a); } void M5() { M4(_ => { }); M4(M1); } void M6(Action<Action<int>> aa, Action<int> a) { aa(a); } void M7() { M6(a => { a(1); }, M1); } Action<int> Prop { get { return _ => { }; } set { value(0); } } void M8() { dynamic d = this; d.Prop = d.Prop; } static Func<Action<int>> F = () => _ => { }; void M9() { F()(0); } Action<int> M10() { return _ => { }; } void M11() { M10()(0); } public delegate void EventHandler(); public event EventHandler Click; public void M12() { Click += M11; Click(); M13(M9); } public void M13(EventHandler eh) { Click += eh; Click(); } public void M13() { void M14(MyDelegate d) => d(); M14(new MyDelegate(M9)); M14(new MyDelegate(new MyDelegate(M11))); M14(M12); M14(() => { }); } public void M14() { void LocalFunction(int i) { }; M2(LocalFunction); } public void M15() { Func<int> f = () => 42; new Lazy<int>(f); f = () => 43; new Lazy<int>(f); } public delegate void MyDelegate(); }
mit
C#
4de9e71e6b3d9bbdb32334a9091027d196674dbf
Update ApplicationConstants.cs
tjscience/RoboSharp,tjscience/RoboSharp
RoboSharp/ApplicationConstants.cs
RoboSharp/ApplicationConstants.cs
using System.Collections.Generic; namespace RoboSharp { internal class ApplicationConstants { internal static Dictionary<string, string> ErrorCodes = new Dictionary<string, string>() { { "ERROR 33 (0x00000021)", "The process cannot access the file because another process has locked a portion of the file." }, { "ERROR 32 (0x00000020)", "The process cannot access the file because it is being used by another process." }, { "ERROR 5 (0x00000005)", "Access is denied." } }; } }
using System.Collections.Generic; namespace RoboSharp { internal class ApplicationConstants { internal static Dictionary<string, string> ErrorCodes = new Dictionary<string, string>() { { "ERROR 32 (0x00000020)", "The process cannot access the file because it is being used by another process." }, { "ERROR 5 (0x00000005)", "Access is denied." } }; } }
mit
C#
d293c4053cb3f451ab07445a9dfc816df4a4f3ce
Add class XML comment
CamTechConsultants/CvsntGitImporter
RepositoryConsistencyException.cs
RepositoryConsistencyException.cs
/* * John Hall <[email protected]> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System; using System.Runtime.Serialization; namespace CvsGitConverter { /// <summary> /// Thrown when the CVS repository is inconsistent. /// </summary> class RepositoryConsistencyException : Exception { /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class. /// </summary> public RepositoryConsistencyException() { } /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class with a /// specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public RepositoryConsistencyException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class with a /// specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="inner">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> public RepositoryConsistencyException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected RepositoryConsistencyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
/* * John Hall <[email protected]> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System; using System.Runtime.Serialization; namespace CvsGitConverter { /// <summary> /// /// </summary> class RepositoryConsistencyException : Exception { /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class. /// </summary> public RepositoryConsistencyException() { } /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class with a /// specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public RepositoryConsistencyException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class with a /// specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="inner">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> public RepositoryConsistencyException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <cref>CvsGitConverter.RepositoryConsistencyException</cref> class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected RepositoryConsistencyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
C#
f3f5df0bb2683fb1f01fc27496164891c5728e22
Add using block
EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework
osu.Framework.Tests/Exceptions/TestAddRemoveExceptions.cs
osu.Framework.Tests/Exceptions/TestAddRemoveExceptions.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; namespace osu.Framework.Tests.Exceptions { [TestFixture] public class TestAddRemoveExceptions { [Test] public void TestNonStableComparer() { Assert.Throws<InvalidOperationException>(() => { using (var broken = new BrokenFillFlowContainer()) { var candidate = new Box(); var candidate2 = new Box(); broken.Add(candidate); broken.Add(candidate2); broken.Remove(candidate); } }); } internal class BrokenFillFlowContainer : FillFlowContainer { protected override int Compare(Drawable x, Drawable y) => 0; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; namespace osu.Framework.Tests.Exceptions { [TestFixture] public class TestAddRemoveExceptions { [Test] public void TestNonStableComparer() { Assert.Throws<InvalidOperationException>(() => { var broken = new BrokenFillFlowContainer(); var candidate = new Box(); var candidate2 = new Box(); broken.Add(candidate); broken.Add(candidate2); broken.Remove(candidate); }); } internal class BrokenFillFlowContainer : FillFlowContainer { protected override int Compare(Drawable x, Drawable y) => 0; } } }
mit
C#
b1c6eda80ded4ba239b9ecef40bbae3edf38eb47
Reset Y postiions of TabItems before performing layout.
ppy/osu-framework,DrabWeb/osu-framework,default0/osu-framework,smoogipooo/osu-framework,RedNesto/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,default0/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,paparony03/osu-framework,ppy/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework
osu.Framework/Graphics/Containers/TabFillFlowContainer.cs
osu.Framework/Graphics/Containers/TabFillFlowContainer.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics.UserInterface.Tab; using OpenTK; namespace osu.Framework.Graphics.Containers { public class TabFillFlowContainer<T> : FillFlowContainer<T> where T : TabItem { public Action<T, bool> TabVisibilityChanged; protected override IEnumerable<Vector2> ComputeLayoutPositions() { foreach (var child in Children) child.Y = 0; var result = base.ComputeLayoutPositions().ToArray(); int i = 0; foreach (var child in FlowingChildren) { updateChildIfNeeded(child, result[i].Y == 0); ++i; } return result; } private Dictionary<T, bool> tabVisibility = new Dictionary<T, bool>(); private void updateChildIfNeeded(T child, bool isVisible) { if (!tabVisibility.ContainsKey(child) || tabVisibility[child] != isVisible) { TabVisibilityChanged?.Invoke(child, isVisible); tabVisibility[child] = isVisible; } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics.UserInterface.Tab; using OpenTK; namespace osu.Framework.Graphics.Containers { public class TabFillFlowContainer<T> : FillFlowContainer<T> where T : TabItem { public Action<T, bool> TabVisibilityChanged; protected override IEnumerable<Vector2> ComputeLayoutPositions() { var result = base.ComputeLayoutPositions().ToArray(); int i = 0; foreach (var child in FlowingChildren) { updateChildIfNeeded(child, result[i].Y == 0); ++i; } return result; } private Dictionary<T, bool> previousValues = new Dictionary<T, bool>(); private void updateChildIfNeeded(T child, bool isVisible) { if (!previousValues.ContainsKey(child) || previousValues[child] != isVisible) { TabVisibilityChanged?.Invoke(child, isVisible); previousValues[child] = isVisible; } } } }
mit
C#
d602072ee3ddb834899295a7c664b6f170d73175
Use SingleOrDefault where feasible
smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu
osu.Game.Tests/Visual/Editing/TestSceneEditorBeatmapCreation.cs
osu.Game.Tests/Visual/Editing/TestSceneEditorBeatmapCreation.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Edit.Setup; using osu.Game.Tests.Resources; using SharpCompress.Archives; using SharpCompress.Archives.Zip; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorBeatmapCreation : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); protected override bool EditorComponentsReady => Editor.ChildrenOfType<SetupScreen>().SingleOrDefault()?.IsLoaded == true; public override void SetUpSteps() { AddStep("set dummy", () => Beatmap.Value = new DummyWorkingBeatmap(Audio, null)); base.SetUpSteps(); } [Test] public void TestCreateNewBeatmap() { AddStep("add random hitobject", () => EditorBeatmap.Metadata.Title = Guid.NewGuid().ToString()); AddStep("save beatmap", () => Editor.Save()); AddAssert("new beatmap persisted", () => EditorBeatmap.BeatmapInfo.ID > 0); } [Test] public void TestAddAudioTrack() { AddAssert("switch track to real track", () => { var setup = Editor.ChildrenOfType<SetupScreen>().First(); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); bool success = setup.ChangeAudioTrack(Path.Combine(extractedFolder, "03. Renatus - Soleily 192kbps.mp3")); File.Delete(temp); Directory.Delete(extractedFolder, true); return success; }); AddAssert("track length changed", () => Beatmap.Value.Track.Length > 60000); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Edit.Setup; using osu.Game.Tests.Resources; using SharpCompress.Archives; using SharpCompress.Archives.Zip; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorBeatmapCreation : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); protected override bool EditorComponentsReady => Editor.ChildrenOfType<SetupScreen>().FirstOrDefault()?.IsLoaded == true; public override void SetUpSteps() { AddStep("set dummy", () => Beatmap.Value = new DummyWorkingBeatmap(Audio, null)); base.SetUpSteps(); } [Test] public void TestCreateNewBeatmap() { AddStep("add random hitobject", () => EditorBeatmap.Metadata.Title = Guid.NewGuid().ToString()); AddStep("save beatmap", () => Editor.Save()); AddAssert("new beatmap persisted", () => EditorBeatmap.BeatmapInfo.ID > 0); } [Test] public void TestAddAudioTrack() { AddAssert("switch track to real track", () => { var setup = Editor.ChildrenOfType<SetupScreen>().First(); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); bool success = setup.ChangeAudioTrack(Path.Combine(extractedFolder, "03. Renatus - Soleily 192kbps.mp3")); File.Delete(temp); Directory.Delete(extractedFolder, true); return success; }); AddAssert("track length changed", () => Beatmap.Value.Track.Length > 60000); } } }
mit
C#
85a3027f1ba4107bee90ee3d2c7492d93b1546f4
Add failing test
UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu
osu.Game.Tests/Visual/Online/TestSceneAccountCreationOverlay.cs
osu.Game.Tests/Visual/Online/TestSceneAccountCreationOverlay.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Overlays; using osu.Game.Overlays.AccountCreation; using osu.Game.Overlays.Settings; using osu.Game.Users; namespace osu.Game.Tests.Visual.Online { public class TestSceneAccountCreationOverlay : OsuTestScene { private readonly Container userPanelArea; private readonly AccountCreationOverlay accountCreation; private IBindable<User> localUser; public TestSceneAccountCreationOverlay() { Children = new Drawable[] { accountCreation = new AccountCreationOverlay(), userPanelArea = new Container { Padding = new MarginPadding(10), AutoSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, }; } [BackgroundDependencyLoader] private void load() { API.Logout(); localUser = API.LocalUser.GetBoundCopy(); localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true); } [Test] public void TestOverlayVisibility() { AddStep("start hidden", () => accountCreation.Hide()); AddStep("log out", API.Logout); AddStep("show manually", () => accountCreation.Show()); AddUntilStep("overlay is visible", () => accountCreation.State.Value == Visibility.Visible); AddStep("click button", () => accountCreation.ChildrenOfType<SettingsButton>().Single().Click()); AddUntilStep("warning screen is present", () => accountCreation.ChildrenOfType<ScreenWarning>().Single().IsPresent); AddStep("log back in", () => API.Login("dummy", "password")); AddUntilStep("overlay is hidden", () => accountCreation.State.Value == Visibility.Hidden); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Users; namespace osu.Game.Tests.Visual.Online { public class TestSceneAccountCreationOverlay : OsuTestScene { private readonly Container userPanelArea; private readonly AccountCreationOverlay accountCreation; private IBindable<User> localUser; public TestSceneAccountCreationOverlay() { Children = new Drawable[] { accountCreation = new AccountCreationOverlay(), userPanelArea = new Container { Padding = new MarginPadding(10), AutoSizeAxes = Axes.Both, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, }; } [BackgroundDependencyLoader] private void load() { API.Logout(); localUser = API.LocalUser.GetBoundCopy(); localUser.BindValueChanged(user => { userPanelArea.Child = new UserGridPanel(user.NewValue) { Width = 200 }; }, true); } [Test] public void TestOverlayVisibility() { AddStep("start hidden", () => accountCreation.Hide()); AddStep("log out", API.Logout); AddStep("show manually", () => accountCreation.Show()); AddUntilStep("overlay is visible", () => accountCreation.State.Value == Visibility.Visible); AddStep("log back in", () => API.Login("dummy", "password")); AddUntilStep("overlay is hidden", () => accountCreation.State.Value == Visibility.Hidden); } } }
mit
C#
77b25e7e91e0312f4c6f6ff482847b055efa2937
initialize command scheduler db
jonsequitur/Alluvial
Alluvial.ForItsCqrs.Tests/DatabaseSetup.cs
Alluvial.ForItsCqrs.Tests/DatabaseSetup.cs
using System.Data.Entity; using Microsoft.Its.Domain.Sql; using Microsoft.Its.Domain.Sql.CommandScheduler; namespace Alluvial.Streams.ItsDomainSql.Tests { public static class DatabaseSetup { private static bool databasesInitialized; private static readonly object lockObj = new object(); public static void Run() { SetConnectionStrings(); Database.SetInitializer(new CreateAndMigrate<CommandSchedulerDbContext>()); lock (lockObj) { if (databasesInitialized) { return; } databasesInitialized = true; } } private static void SetConnectionStrings() { // local EventStoreDbContext.NameOrConnectionString = @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=BankingEventStore"; CommandSchedulerDbContext.NameOrConnectionString = @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=BankingScheduledCommands"; } } }
using Microsoft.Its.Domain.Sql; using Microsoft.Its.Domain.Sql.CommandScheduler; namespace Alluvial.Streams.ItsDomainSql.Tests { public static class DatabaseSetup { private static bool databasesInitialized; private static readonly object lockObj = new object(); public static void Run() { SetConnectionStrings(); lock (lockObj) { if (databasesInitialized) { return; } databasesInitialized = true; } } private static void SetConnectionStrings() { // local EventStoreDbContext.NameOrConnectionString = @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=BankingEventStore"; CommandSchedulerDbContext.NameOrConnectionString = @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=BankingScheduledCommands"; } } }
mit
C#
d3b416dfd53ac6af5906e203788416a92fbf3116
Fix eval type display
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Evaluation.cs
Battery-Commander.Web/Models/Evaluation.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace BatteryCommander.Web.Models { public class Evaluation { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int RateeId { get; set; } public virtual Soldier Ratee { get; set; } [Required] public int RaterId { get; set; } public virtual Soldier Rater { get; set; } [Required] public int SeniorRaterId { get; set; } public virtual Soldier SeniorRater { get; set; } [Required, DataType(DataType.Date), Column(TypeName = "date")] public DateTime StartDate { get; set; } = DateTime.Today; [Required, DataType(DataType.Date), Column(TypeName = "date")] public DateTime ThruDate { get; set; } [Required] public EvaluationStatus Status { get; set; } = EvaluationStatus.Unknown; [Required] public EvaluationType Type { get; set; } = EvaluationType.Annual; [NotMapped] public Boolean IsCompleted => EvaluationStatus.Completed == Status; [NotMapped, DisplayFormat(DataFormatString = "{0:%d}d")] public TimeSpan Delinquency => (ThruDate - DateTime.Today); [NotMapped, DataType(DataType.Date)] public DateTimeOffset? LastUpdated => Events.OrderByDescending(e => e.Timestamp).Select(e => (DateTimeOffset?)e.Timestamp).FirstOrDefault(); public virtual ICollection<Event> Events { get; set; } = new List<Event>(); public class Event { // Could represent a state transition or a manual comment added, perhaps we need to flag that? [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [DataType(DataType.DateTime)] public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow; // Username? Printed name? public string Author { get; set; } public string Message { get; set; } } } public enum EvaluationType : byte { Annual, [Display(Name = "Change of Rater")] Change_of_Rater, [Display(Name = "Complete the Record")] Complete_the_Record } public enum EvaluationStatus : byte { Unknown, Completed = 100 } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace BatteryCommander.Web.Models { public class Evaluation { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int RateeId { get; set; } public virtual Soldier Ratee { get; set; } [Required] public int RaterId { get; set; } public virtual Soldier Rater { get; set; } [Required] public int SeniorRaterId { get; set; } public virtual Soldier SeniorRater { get; set; } [Required, DataType(DataType.Date), Column(TypeName = "date")] public DateTime StartDate { get; set; } = DateTime.Today; [Required, DataType(DataType.Date), Column(TypeName = "date")] public DateTime ThruDate { get; set; } [Required] public EvaluationStatus Status { get; set; } = EvaluationStatus.Unknown; [Required] public EvaluationType Type { get; set; } = EvaluationType.Annual; [NotMapped] public Boolean IsCompleted => EvaluationStatus.Completed == Status; [NotMapped, DisplayFormat(DataFormatString = "{0:%d}d")] public TimeSpan Delinquency => (ThruDate - DateTime.Today); [NotMapped, DataType(DataType.Date)] public DateTimeOffset? LastUpdated => Events.OrderByDescending(e => e.Timestamp).Select(e => (DateTimeOffset?)e.Timestamp).FirstOrDefault(); public virtual ICollection<Event> Events { get; set; } = new List<Event>(); public class Event { // Could represent a state transition or a manual comment added, perhaps we need to flag that? [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [DataType(DataType.DateTime)] public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow; // Username? Printed name? public string Author { get; set; } public string Message { get; set; } } } public enum EvaluationType : byte { Annual, Change_of_Rater, Complete_the_Record } public enum EvaluationStatus : byte { Unknown, Completed = 100 } }
mit
C#
a5a1e01c2ac4fd68931e4ebf7cb7ba0c5c7848d3
Check if credit card payment received
ucdavis/CRP,ucdavis/CRP,ucdavis/CRP
CRP.Mvc/Views/Payments/Confirmation.cshtml
CRP.Mvc/Views/Payments/Confirmation.cshtml
@using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Transaction: </label> @Model.Transaction.TransactionNumber </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> @if (Model.Transaction.Paid) { <div class="alert alert-danger"> <button type="button" class="close" data-dismiss="alert">×</button> It appears this has been paid. If you think it hasn't you may still pay. </div> } else { <p>Payment is still due:</p> } <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> <input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/> </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div>
@using Microsoft.Web.Mvc @model CRP.Controllers.ViewModels.PaymentConfirmationViewModel @{ ViewBag.Title = "Confirmation"; } <div class="boundary"> <h2>Registration Confirmation</h2> <p>You have successfully registered for the following event:</p> <div> <label>Item: </label> @Model.Transaction.Item.Name </div> <div> <label>Transaction: </label> @Model.Transaction.TransactionNumber </div> <div> <label>Amount: </label> @($"{Model.Transaction.Total:C}") </div> @if (Model.Transaction.Credit) { <div> <p>Payment is still due:</p> <form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px"> @foreach (var pair in Model.PaymentDictionary) { <input type="hidden" name="@pair.Key" value="@pair.Value"/> } <input type="hidden" name="signature" value="@Model.Signature"/> <input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/> </form> </div> } else if (Model.Transaction.Total > 0) { <div> @Html.Raw(Model.Transaction.Item.CheckPaymentInstructions) </div> } </div>
mit
C#
ed26e371605bef12c04c9c3490e7b3465377652c
use Location of assembly instead of CodeBase
haithemaraissia/FAKE,MiloszKrajewski/FAKE,neoeinstein/FAKE,leflings/FAKE,ilkerde/FAKE,dmorgan3405/FAKE,tpetricek/FAKE,ctaggart/FAKE,mat-mcloughlin/FAKE,darrelmiller/FAKE,naveensrinivasan/FAKE,beeker/FAKE,ovu/FAKE,ArturDorochowicz/FAKE,warnergodfrey/FAKE,warnergodfrey/FAKE,yonglehou/FAKE,ovu/FAKE,wooga/FAKE,philipcpresley/FAKE,xavierzwirtz/FAKE,philipcpresley/FAKE,daniel-chambers/FAKE,pmcvtm/FAKE,daniel-chambers/FAKE,NaseUkolyCZ/FAKE,warnergodfrey/FAKE,NaseUkolyCZ/FAKE,MiloszKrajewski/FAKE,gareth-evans/FAKE,mglodack/FAKE,jayp33/FAKE,RMCKirby/FAKE,hitesh97/FAKE,satsuper/FAKE,xavierzwirtz/FAKE,featuresnap/FAKE,ArturDorochowicz/FAKE,MichalDepta/FAKE,yonglehou/FAKE,dmorgan3405/FAKE,brianary/FAKE,modulexcite/FAKE,pacificIT/FAKE,xavierzwirtz/FAKE,modulexcite/FAKE,mfalda/FAKE,featuresnap/FAKE,tpetricek/FAKE,dlsteuer/FAKE,MiloszKrajewski/FAKE,RMCKirby/FAKE,pacificIT/FAKE,wooga/FAKE,mglodack/FAKE,ArturDorochowicz/FAKE,JonCanning/FAKE,pacificIT/FAKE,wooga/FAKE,hitesh97/FAKE,mat-mcloughlin/FAKE,MichalDepta/FAKE,tpetricek/FAKE,daniel-chambers/FAKE,modulexcite/FAKE,naveensrinivasan/FAKE,ctaggart/FAKE,rflechner/FAKE,NaseUkolyCZ/FAKE,rflechner/FAKE,beeker/FAKE,ovu/FAKE,JonCanning/FAKE,ilkerde/FAKE,pacificIT/FAKE,philipcpresley/FAKE,rflechner/FAKE,gareth-evans/FAKE,ovu/FAKE,Kazark/FAKE,ctaggart/FAKE,featuresnap/FAKE,darrelmiller/FAKE,mfalda/FAKE,molinch/FAKE,dmorgan3405/FAKE,RMCKirby/FAKE,ilkerde/FAKE,gareth-evans/FAKE,jayp33/FAKE,Kazark/FAKE,ilkerde/FAKE,neoeinstein/FAKE,JonCanning/FAKE,JonCanning/FAKE,mfalda/FAKE,leflings/FAKE,brianary/FAKE,darrelmiller/FAKE,xavierzwirtz/FAKE,leflings/FAKE,naveensrinivasan/FAKE,modulexcite/FAKE,brianary/FAKE,daniel-chambers/FAKE,hitesh97/FAKE,ArturDorochowicz/FAKE,ctaggart/FAKE,haithemaraissia/FAKE,molinch/FAKE,MiloszKrajewski/FAKE,brianary/FAKE,philipcpresley/FAKE,pmcvtm/FAKE,yonglehou/FAKE,pmcvtm/FAKE,haithemaraissia/FAKE,NaseUkolyCZ/FAKE,hitesh97/FAKE,jayp33/FAKE,featuresnap/FAKE,satsuper/FAKE,Kazark/FAKE,molinch/FAKE,dlsteuer/FAKE,mat-mcloughlin/FAKE,yonglehou/FAKE,mglodack/FAKE,MichalDepta/FAKE,neoeinstein/FAKE,beeker/FAKE,neoeinstein/FAKE,Kazark/FAKE,dmorgan3405/FAKE,mat-mcloughlin/FAKE,leflings/FAKE,dlsteuer/FAKE,darrelmiller/FAKE,satsuper/FAKE,MichalDepta/FAKE,tpetricek/FAKE,naveensrinivasan/FAKE,gareth-evans/FAKE,wooga/FAKE,molinch/FAKE,dlsteuer/FAKE,mglodack/FAKE,warnergodfrey/FAKE,RMCKirby/FAKE,jayp33/FAKE,satsuper/FAKE,haithemaraissia/FAKE,mfalda/FAKE,rflechner/FAKE,pmcvtm/FAKE,beeker/FAKE
src/test/Test.FAKECore/MSBuild/LoggerSpecs.cs
src/test/Test.FAKECore/MSBuild/LoggerSpecs.cs
using System.IO; using Fake; using Machine.Specifications; namespace Test.FAKECore.MSBuild { public class when_using_a_logger { It should_find_the_error_logger = () => MSBuildHelper.ErrorLoggerName.ShouldEqual("Fake.MsBuildLogger+ErrorLogger"); It should_find_the_teamcity_logger = () => MSBuildHelper.TeamCityLoggerName.ShouldEqual("Fake.MsBuildLogger+TeamCityLogger"); } }
using System.IO; using Fake; using Machine.Specifications; namespace Test.FAKECore.MSBuild { public class when_using_a_logger { It should_build_the_logger_from_filepath_with_hash = () => MSBuildHelper.buildErrorLoggerParam("file:///C:/Test#/asd") .ShouldEqual( string.Format( "/logger:Fake.MsBuildLogger+TeamCityLogger,\"C:{0}Test#{0}asd\" /logger:Fake.MsBuildLogger+ErrorLogger,\"C:{0}Test#{0}asd\"", Path.DirectorySeparatorChar)); It should_build_the_logger_from_simple_folder = () => MSBuildHelper.buildErrorLoggerParam("file:///C:/Test") .ShouldEqual( string.Format( "/logger:Fake.MsBuildLogger+TeamCityLogger,\"C:{0}Test\" /logger:Fake.MsBuildLogger+ErrorLogger,\"C:{0}Test\"", Path.DirectorySeparatorChar)); It should_find_the_error_logger = () => MSBuildHelper.ErrorLoggerName.ShouldEqual("Fake.MsBuildLogger+ErrorLogger"); It should_find_the_teamcity_logger = () => MSBuildHelper.TeamCityLoggerName.ShouldEqual("Fake.MsBuildLogger+TeamCityLogger"); } }
apache-2.0
C#
3dc15bd52054ecb6150807ae740e75171bd78bcc
Enable NRT
sharwell/roslyn,dotnet/roslyn,weltkante/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,dotnet/roslyn,diryboy/roslyn,KevinRansom/roslyn,sharwell/roslyn,weltkante/roslyn,sharwell/roslyn,KevinRansom/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,mavasani/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn
src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersHelper.cs
src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersHelper.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.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { internal class CSharpOrderModifiersHelper : AbstractOrderModifiersHelpers { public static readonly CSharpOrderModifiersHelper Instance = new(); private CSharpOrderModifiersHelper() { } protected override int GetKeywordKind(string trimmed) { var kind = SyntaxFacts.GetKeywordKind(trimmed); return (int)(kind == SyntaxKind.None ? SyntaxFacts.GetContextualKeywordKind(trimmed) : kind); } protected override bool TryParse(string value, [NotNullWhen(true)] out Dictionary<int, int>? parsed) { if (!base.TryParse(value, out parsed)) return false; // 'partial' must always go at the end in C#. parsed[(int)SyntaxKind.PartialKeyword] = int.MaxValue; return true; } } }
// 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. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { internal class CSharpOrderModifiersHelper : AbstractOrderModifiersHelpers { public static readonly CSharpOrderModifiersHelper Instance = new(); private CSharpOrderModifiersHelper() { } protected override int GetKeywordKind(string trimmed) { var kind = SyntaxFacts.GetKeywordKind(trimmed); return (int)(kind == SyntaxKind.None ? SyntaxFacts.GetContextualKeywordKind(trimmed) : kind); } protected override bool TryParse(string value, out Dictionary<int, int> parsed) { if (!base.TryParse(value, out parsed)) { return false; } // 'partial' must always go at the end in C#. parsed[(int)SyntaxKind.PartialKeyword] = int.MaxValue; return true; } } }
mit
C#
b8960219b4ee4d4481ddb88a14edc1ab468b407b
Fix Stylecop failure - long line
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Mvc.Core/Formatters/DefaultOutputFormattersProvider.cs
src/Microsoft.AspNet.Mvc.Core/Formatters/DefaultOutputFormattersProvider.cs
// Copyright (c) Microsoft Open Technologies, Inc. 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.Collections.Generic; using Microsoft.AspNet.Mvc.OptionDescriptors; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Mvc { /// <inheritdoc /> public class DefaultOutputFormattersProvider : OptionDescriptorBasedProvider<IOutputFormatter>, IOutputFormattersProvider { /// <summary> /// Initializes a new instance of the DefaultOutputFormattersProvider class. /// </summary> /// <param name="options">An accessor to the <see cref="MvcOptions"/> configured for this application.</param> /// <param name="typeActivator">An <see cref="ITypeActivator"/> instance used to instantiate types.</param> /// <param name="serviceProvider">A <see cref="IServiceProvider"/> instance that retrieves services from the /// service collection.</param> public DefaultOutputFormattersProvider(IOptionsAccessor<MvcOptions> optionsAccessor, ITypeActivator typeActivator, IServiceProvider serviceProvider) : base(optionsAccessor.Options.OutputFormatters, typeActivator, serviceProvider) { } /// <inheritdoc /> public IReadOnlyList<IOutputFormatter> OutputFormatters { get { return Options; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Collections.Generic; using Microsoft.AspNet.Mvc.OptionDescriptors; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Mvc { /// <inheritdoc /> public class DefaultOutputFormattersProvider : OptionDescriptorBasedProvider<IOutputFormatter>, IOutputFormattersProvider { /// <summary> /// Initializes a new instance of the DefaultOutputFormattersProvider class. /// </summary> /// <param name="options">An accessor to the <see cref="MvcOptions"/> configured for this application.</param> /// <param name="typeActivator">An <see cref="ITypeActivator"/> instance used to instantiate types.</param> /// <param name="serviceProvider">A <see cref="IServiceProvider"/> instance that retrieves services from the /// service collection.</param> public DefaultOutputFormattersProvider(IOptionsAccessor<MvcOptions> optionsAccessor, ITypeActivator typeActivator, IServiceProvider serviceProvider) : base(optionsAccessor.Options.OutputFormatters, typeActivator, serviceProvider) { } /// <inheritdoc /> public IReadOnlyList<IOutputFormatter> OutputFormatters { get { return Options; } } } }
apache-2.0
C#
8fc4ba8202d1488daa89abc2a4ef2c3e33b63245
Remove test code.
modulexcite/msgpack-cli,msgpack/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli
test/NUnitLiteRunner/Program.cs
test/NUnitLiteRunner/Program.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using NUnitLite.Runner; namespace MsgPack.NUnitLiteRunner { /// <summary> /// Lightweight test runner for NUnit Lite with <c>mono --full-aot</c>. /// </summary> internal class Program { private static readonly string AssemblyName = typeof( PackUnpackTest ).Assembly.FullName; private static void Main( string[] args ) { var adjustedArgs = new List<string>( args.Length + 1 ); adjustedArgs.AddRange( args ); adjustedArgs.Add( AssemblyName ); new TextUI().Execute( adjustedArgs.ToArray() ); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using NUnitLite.Runner; namespace MsgPack.NUnitLiteRunner { /// <summary> /// Lightweight test runner for NUnit Lite with <c>mono --full-aot</c>. /// </summary> internal class Program { private static readonly string AssemblyName = typeof( PackUnpackTest ).Assembly.FullName; private static void Main( string[] args ) { Console.WriteLine( "Init:{0}:{1}", CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture ); var adjustedArgs = new List<string>( args.Length + 1 ); adjustedArgs.AddRange( args ); adjustedArgs.Add( AssemblyName ); // Avoid JIT error Thread.CurrentThread.CurrentCulture = new CultureInfo( "en-US" ); Thread.CurrentThread.CurrentUICulture = new CultureInfo( "en-US" ); new TextUI().Execute( adjustedArgs.ToArray() ); } } }
apache-2.0
C#
875121b1bbdeab8b2385df4c0578990471114ad2
Handle null values
ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
osu.Framework/Statistics/GlobalStatistic.cs
osu.Framework/Statistics/GlobalStatistic.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Statistics { public class GlobalStatistic<T> : IGlobalStatistic { public string Group { get; } public string Name { get; } public GlobalStatistic(string group, string name) { Group = group; Name = name; } public string DisplayValue { get { switch (value) { case double d: return d.ToString("#,0.##"); case int i: return i.ToString("#,0"); case long l: return l.ToString("#,0"); case null: return string.Empty; default: return value.ToString(); } } } private T value; public T Value { get => value; set => this.value = value; } public virtual void Clear() => Value = default; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Statistics { public class GlobalStatistic<T> : IGlobalStatistic { public string Group { get; } public string Name { get; } public GlobalStatistic(string group, string name) { Group = group; Name = name; } public string DisplayValue { get { switch (value) { case double d: return d.ToString("#,0.##"); case int i: return i.ToString("#,0"); case long l: return l.ToString("#,0"); default: return value.ToString(); } } } private T value; public T Value { get => value; set => this.value = value; } public virtual void Clear() => Value = default; } }
mit
C#
e8ef518438ae6497bf797a1ffd75eda963f40af2
Fix bug with inserting new item
JasonBock/csla,MarimerLLC/csla,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,rockfordlhotka/csla,JasonBock/csla,JasonBock/csla,rockfordlhotka/csla
Samples/MvcExample/MvcExample/Controllers/PersonController.cs
Samples/MvcExample/MvcExample/Controllers/PersonController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Csla; using BusinessLibrary; namespace CslaMvcExample.Controllers { public class PersonController : Csla.Web.Mvc.Controller { // GET: Person public async Task<ActionResult> Index() { var list = await DataPortal.FetchAsync<PersonList>(); return View(list); } // GET: Person/Details/5 public async Task<ActionResult> Details(int id) { var obj = await DataPortal.FetchAsync<PersonInfo>(id); return View(obj); } // GET: Person/Create public async Task<ActionResult> Create() { var obj = await DataPortal.CreateAsync<PersonEdit>(); return View(obj); } // POST: Person/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(PersonEdit person) { try { if (await SaveObjectAsync<PersonEdit>(person, false)) return RedirectToAction(nameof(Index)); else return View(person); } catch { return View(person); } } // GET: Person/Edit/5 public async Task<ActionResult> Edit(int id) { var obj = await DataPortal.FetchAsync<PersonEdit>(id); return View(obj); } // POST: Person/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit(int id, PersonEdit person) { try { LoadProperty(person, PersonEdit.IdProperty, id); if (await SaveObjectAsync<PersonEdit>(person, true)) return RedirectToAction(nameof(Index)); else return View(person); } catch { return View(person); } } // GET: Person/Delete/5 public async Task<ActionResult> Delete(int id) { var obj = await DataPortal.FetchAsync<PersonInfo>(id); return View(obj); } // POST: Person/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Delete(int id, PersonInfo person) { try { await DataPortal.DeleteAsync<PersonEdit>(id); return RedirectToAction(nameof(Index)); } catch { return View(person); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Csla; using BusinessLibrary; namespace CslaMvcExample.Controllers { public class PersonController : Csla.Web.Mvc.Controller { // GET: Person public async Task<ActionResult> Index() { var list = await DataPortal.FetchAsync<PersonList>(); return View(list); } // GET: Person/Details/5 public async Task<ActionResult> Details(int id) { var obj = await DataPortal.FetchAsync<PersonInfo>(id); return View(obj); } // GET: Person/Create public async Task<ActionResult> Create() { var obj = await DataPortal.CreateAsync<PersonEdit>(); return View(obj); } // POST: Person/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(PersonEdit person) { try { if (await SaveObjectAsync<PersonEdit>(person, true)) return RedirectToAction(nameof(Index)); else return View(person); } catch { return View(person); } } // GET: Person/Edit/5 public async Task<ActionResult> Edit(int id) { var obj = await DataPortal.FetchAsync<PersonEdit>(id); return View(obj); } // POST: Person/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit(int id, PersonEdit person) { try { LoadProperty(person, PersonEdit.IdProperty, id); if (await SaveObjectAsync<PersonEdit>(person, true)) return RedirectToAction(nameof(Index)); else return View(person); } catch { return View(person); } } // GET: Person/Delete/5 public async Task<ActionResult> Delete(int id) { var obj = await DataPortal.FetchAsync<PersonInfo>(id); return View(obj); } // POST: Person/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Delete(int id, PersonInfo person) { try { await DataPortal.DeleteAsync<PersonEdit>(id); return RedirectToAction(nameof(Index)); } catch { return View(person); } } } }
mit
C#
ac1a9260857109a3e0a91eeb6d09edefc3df8635
fix implementation of convertback.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Converters/LurkingWifeModeStringConverter.cs
WalletWasabi.Gui/Converters/LurkingWifeModeStringConverter.cs
using Avalonia; using Avalonia.Data.Converters; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace WalletWasabi.Gui.Converters { public class LurkingWifeModeStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var uiConfig = Application.Current.Resources[Global.UiConfigResourceKey] as UiConfig; if (uiConfig.LurkingWifeMode is true) { int len = 10; if (int.TryParse(parameter.ToString(), out int newLength)) { len = newLength; } return new string(Enumerable.Repeat('#', len).ToArray()); } return value.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value?.ToString() ?? ""; } } }
using Avalonia; using Avalonia.Data.Converters; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace WalletWasabi.Gui.Converters { public class LurkingWifeModeStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var uiConfig = Application.Current.Resources[Global.UiConfigResourceKey] as UiConfig; if (uiConfig.LurkingWifeMode is true) { int len = 10; if (int.TryParse(parameter.ToString(), out int newLength)) { len = newLength; } return new string(Enumerable.Repeat('#', len).ToArray()); } return value.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString(); } } }
mit
C#
6d5c7030dadbea3b129fd2154b1c1e7905c1e3f8
Update ProtectingSpecificCellsinaWorksheet.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Worksheets/Security/ProtectingSpecificCellsinaWorksheet.cs
Examples/CSharp/Worksheets/Security/ProtectingSpecificCellsinaWorksheet.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Security { public class ProtectingSpecificCellsinaWorksheet { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); // Create a new workbook. Workbook wb = new Workbook(); // Create a worksheet object and obtain the first sheet. Worksheet sheet = wb.Worksheets[0]; // Define the style object. Style style; //Define the styleflag object StyleFlag styleflag; // Loop through all the columns in the worksheet and unlock them. for (int i = 0; i <= 255; i++) { style = sheet.Cells.Columns[(byte)i].Style; style.IsLocked = false; styleflag = new StyleFlag(); styleflag.Locked = true; sheet.Cells.Columns[(byte)i].ApplyStyle(style, styleflag); } // Lock the three cells...i.e. A1, B1, C1. style = sheet.Cells["A1"].GetStyle(); style.IsLocked = true; sheet.Cells["A1"].SetStyle(style); style = sheet.Cells["B1"].GetStyle(); style.IsLocked = true; sheet.Cells["B1"].SetStyle(style); style = sheet.Cells["C1"].GetStyle(); style.IsLocked = true; sheet.Cells["C1"].SetStyle(style); // Finally, Protect the sheet now. sheet.Protect(ProtectionType.All); // Save the excel file. wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Worksheets.Security { public class ProtectingSpecificCellsinaWorksheet { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create directory if it is not already present. bool IsExists = System.IO.Directory.Exists(dataDir); if (!IsExists) System.IO.Directory.CreateDirectory(dataDir); // Create a new workbook. Workbook wb = new Workbook(); // Create a worksheet object and obtain the first sheet. Worksheet sheet = wb.Worksheets[0]; // Define the style object. Style style; //Define the styleflag object StyleFlag styleflag; // Loop through all the columns in the worksheet and unlock them. for (int i = 0; i <= 255; i++) { style = sheet.Cells.Columns[(byte)i].Style; style.IsLocked = false; styleflag = new StyleFlag(); styleflag.Locked = true; sheet.Cells.Columns[(byte)i].ApplyStyle(style, styleflag); } // Lock the three cells...i.e. A1, B1, C1. style = sheet.Cells["A1"].GetStyle(); style.IsLocked = true; sheet.Cells["A1"].SetStyle(style); style = sheet.Cells["B1"].GetStyle(); style.IsLocked = true; sheet.Cells["B1"].SetStyle(style); style = sheet.Cells["C1"].GetStyle(); style.IsLocked = true; sheet.Cells["C1"].SetStyle(style); // Finally, Protect the sheet now. sheet.Protect(ProtectionType.All); // Save the excel file. wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003); } } }
mit
C#
6c885f122068453560af9d7a7593009646afa525
Fix Guid Id
bubavanhalen/XamarinMediaManager,mike-rowley/XamarinMediaManager,modplug/XamarinMediaManager,martijn00/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager
MediaManager/Plugin.MediaManager.Abstractions/Implementations/MediaFile.cs
MediaManager/Plugin.MediaManager.Abstractions/Implementations/MediaFile.cs
using System; using System.ComponentModel; using Plugin.MediaManager.Abstractions.EventArguments; namespace Plugin.MediaManager.Abstractions.Implementations { public class MediaFile : IMediaFile { public MediaFile() : this(String.Empty, MediaFileType.Other) { } public MediaFile(string url, MediaFileType type) { Url = url; Type = type; Metadata = new MediaFileMetadata(); } public Guid Id { get; set; } = Guid.NewGuid(); public MediaFileType Type { get; set; } public IMediaFileMetadata Metadata { get; set; } public string Url { get; set; } private bool _metadataExtracted; public bool MetadataExtracted { get { return _metadataExtracted; } set { _metadataExtracted = value; MetadataUpdated?.Invoke(this, new MetadataChangedEventArgs(Metadata)); } } public event MetadataUpdatedEventHandler MetadataUpdated; } }
using System; using System.ComponentModel; using Plugin.MediaManager.Abstractions.EventArguments; namespace Plugin.MediaManager.Abstractions.Implementations { public class MediaFile : IMediaFile { public MediaFile() : this(String.Empty, MediaFileType.Other) { } public MediaFile(string url, MediaFileType type) { Url = url; Type = type; Metadata = new MediaFileMetadata(); } public Guid Id { get; set; } = new Guid(); public MediaFileType Type { get; set; } public IMediaFileMetadata Metadata { get; set; } public string Url { get; set; } private bool _metadataExtracted; public bool MetadataExtracted { get { return _metadataExtracted; } set { _metadataExtracted = value; MetadataUpdated?.Invoke(this, new MetadataChangedEventArgs(Metadata)); } } public event MetadataUpdatedEventHandler MetadataUpdated; } }
mit
C#
f274edeafa1a9e2d442caf48f6fec748e51c7541
Test Cases
jefking/King.B-Trak
King.BTrak.Unit.Test/SqlDataWriterTests.cs
King.BTrak.Unit.Test/SqlDataWriterTests.cs
namespace King.BTrak.Unit.Test { using King.Data.Sql.Reflection; using King.Mapper.Data; using NSubstitute; using NUnit.Framework; using System; [TestFixture] public class SqlDataWriterTests { [Test] public void Constructor() { var reader = Substitute.For<ISchemaReader>(); var executor = Substitute.For<IExecutor>(); var tableName = Guid.NewGuid().ToString(); new SqlDataWriter(reader, executor, tableName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ConstructorReaderNull() { var executor = Substitute.For<IExecutor>(); var tableName = Guid.NewGuid().ToString(); new SqlDataWriter(null, executor, tableName); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ConstructorExecutorNull() { var reader = Substitute.For<ISchemaReader>(); var tableName = Guid.NewGuid().ToString(); new SqlDataWriter(reader, null, tableName); } [Test] [ExpectedException(typeof(ArgumentException))] public void ConstructorTableNameNull() { var reader = Substitute.For<ISchemaReader>(); var executor = Substitute.For<IExecutor>(); new SqlDataWriter(reader, executor, null); } } }
namespace King.BTrak.Unit.Test { using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; [TestFixture] public class SqlDataWriterTests { } }
mit
C#
e76cea5a8bd1cded0bf589ee69182bf8e8e7b192
add better issue handling to PodMetadataProvider
IUMDPI/IUMediaHelperApps
Packager/Providers/IPodMetadataProvider.cs
Packager/Providers/IPodMetadataProvider.cs
using System; using System.Net; using System.Threading.Tasks; using Packager.Deserializers; using Packager.Models; using Packager.Models.PodMetadataModels; using RestSharp; namespace Packager.Providers { public interface IPodMetadataProvider { Task<ConsolidatedPodMetadata> Get(string barcode); } internal class PodMetadataProvider : IPodMetadataProvider { public PodMetadataProvider(IProgramSettings programSettings, ILookupsProvider lookupsProvider) { ProgramSettings = programSettings; LookupsProvider = lookupsProvider; } private IProgramSettings ProgramSettings { get; set; } private ILookupsProvider LookupsProvider { get; set; } public async Task<ConsolidatedPodMetadata> Get(string barcode) { var client = new RestClient(string.Format(ProgramSettings.BaseWebServiceUrlFormat, barcode)) { Authenticator = new HttpBasicAuthenticator(ProgramSettings.PodAuth.UserName, ProgramSettings.PodAuth.Password), }; // use custom deserializer var serializer = new PodMetadataDeserializer(LookupsProvider); client.AddHandler("text/xml", serializer); client.AddHandler("application/xml", serializer); var request = new RestRequest {DateFormat = "yyyy-MM-ddTHH:mm:sszzz"}; var response = await client.ExecuteGetTaskAsync<ConsolidatedPodMetadata>(request); VerifyResponse(response); return response.Data; } private void VerifyResponse(IRestResponse response) { if (response.ResponseStatus != ResponseStatus.Completed) { throw new Exception("Could not retrieve metadata from Pod", response.ErrorException); } if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Could not retrieve metadata from Pod", new Exception(response.ErrorMessage)); } } } }
using System.Threading.Tasks; using Packager.Deserializers; using Packager.Models; using Packager.Models.PodMetadataModels; using RestSharp; namespace Packager.Providers { public interface IPodMetadataProvider { Task<ConsolidatedPodMetadata> Get(string barcode); } internal class PodMetadataProvider : IPodMetadataProvider { public PodMetadataProvider(IProgramSettings programSettings, ILookupsProvider lookupsProvider) { ProgramSettings = programSettings; LookupsProvider = lookupsProvider; } private IProgramSettings ProgramSettings { get; set; } private ILookupsProvider LookupsProvider { get; set; } public async Task<ConsolidatedPodMetadata> Get(string barcode) { var client = new RestClient(string.Format(ProgramSettings.BaseWebServiceUrlFormat, barcode)) { Authenticator = new HttpBasicAuthenticator(ProgramSettings.PodAuth.UserName, ProgramSettings.PodAuth.Password), }; // use custom deserializer var serializer = new PodMetadataDeserializer(LookupsProvider); client.AddHandler("text/xml", serializer); client.AddHandler("application/xml", serializer); var request = new RestRequest {DateFormat = "yyyy-MM-ddTHH:mm:sszzz"}; var response = await client.ExecuteGetTaskAsync<ConsolidatedPodMetadata>(request); return response.Data; } } }
apache-2.0
C#
671b3d01ff83d9550fcf1b65cfcccdf5d352181d
Fix OsuClickableContainer's local content geting overwritten
EVAST9919/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,DrabWeb/osu,smoogipoo/osu,Nabile-Rahmani/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,Frontear/osuKyzer,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,DrabWeb/osu,peppy/osu-new,DrabWeb/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,naoey/osu,ppy/osu,naoey/osu,smoogipooo/osu,peppy/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,ZLima12/osu
osu.Game/Graphics/Containers/OsuClickableContainer.cs
osu.Game/Graphics/Containers/OsuClickableContainer.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; namespace osu.Game.Graphics.Containers { public class OsuClickableContainer : ClickableContainer { private readonly HoverSampleSet sampleSet; private readonly Container content = new Container { RelativeSizeAxes = Axes.Both }; protected override Container<Drawable> Content => content; public OsuClickableContainer(HoverSampleSet sampleSet = HoverSampleSet.Normal) { this.sampleSet = sampleSet; } [BackgroundDependencyLoader] private void load() { if (AutoSizeAxes != Axes.None) { content.RelativeSizeAxes = RelativeSizeAxes; content.AutoSizeAxes = AutoSizeAxes; } InternalChildren = new Drawable[] { content, new HoverClickSounds(sampleSet) }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; namespace osu.Game.Graphics.Containers { public class OsuClickableContainer : ClickableContainer { private readonly HoverSampleSet sampleSet; public OsuClickableContainer(HoverSampleSet sampleSet = HoverSampleSet.Normal) { this.sampleSet = sampleSet; } [BackgroundDependencyLoader] private void load() { AddInternal(new HoverClickSounds(sampleSet)); } } }
mit
C#
8264b50cca27b3a72f1426cb91b7402df0ffef5d
Remove unused field
cake-build/cake,cake-build/cake,patriksvensson/cake,devlead/cake,patriksvensson/cake,devlead/cake,gep13/cake,gep13/cake
src/Cake.Common/Tools/DotNet/SDKCheck/DotNetSDKChecker.cs
src/Cake.Common/Tools/DotNet/SDKCheck/DotNetSDKChecker.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 Cake.Core; using Cake.Core.IO; using Cake.Core.Tooling; namespace Cake.Common.Tools.DotNet.SDKCheck { /// <summary> /// .NET SDK checker. /// </summary> public sealed class DotNetSDKChecker : DotNetTool<DotNetSDKCheckSettings> { /// <summary> /// Initializes a new instance of the <see cref="DotNetSDKChecker" /> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="tools">The tool locator.</param> public DotNetSDKChecker( IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { } /// <summary> /// Lists the latest available version of the .NET SDK and .NET Runtime, for each feature band. /// </summary> public void Check() { var settings = new DotNetSDKCheckSettings(); RunCommand(settings, GetArguments(settings)); } private ProcessArgumentBuilder GetArguments(DotNetSDKCheckSettings settings) { var builder = CreateArgumentBuilder(settings); builder.Append("sdk check"); return builder; } } }
// 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 Cake.Core; using Cake.Core.IO; using Cake.Core.Tooling; namespace Cake.Common.Tools.DotNet.SDKCheck { /// <summary> /// .NET SDK checker. /// </summary> public sealed class DotNetSDKChecker : DotNetTool<DotNetSDKCheckSettings> { private readonly ICakeEnvironment _environment; /// <summary> /// Initializes a new instance of the <see cref="DotNetSDKChecker" /> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="tools">The tool locator.</param> public DotNetSDKChecker( IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { _environment = environment; } /// <summary> /// Lists the latest available version of the .NET SDK and .NET Runtime, for each feature band. /// </summary> public void Check() { var settings = new DotNetSDKCheckSettings(); RunCommand(settings, GetArguments(settings)); } private ProcessArgumentBuilder GetArguments(DotNetSDKCheckSettings settings) { var builder = CreateArgumentBuilder(settings); builder.Append("sdk check"); return builder; } } }
mit
C#
b7fc350b4ddaffa17933262b9c25dd7c2cf11141
refactor code
Structed/claimini,Structed/claimini
src/Claimini.Api/Repository/Pdf/BackgroundEventHandler.cs
src/Claimini.Api/Repository/Pdf/BackgroundEventHandler.cs
// <copyright file="Invoice.cs" company="Johannes Ebner"> // Copyright (c) Johannes Ebner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root or https://spdx.org/licenses/MIT.html for full license information. // </copyright> using iText.Kernel.Events; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Layout; using iText.Layout.Element; namespace Claimini.Api.Repository.Pdf { public class BackgroundEventHandler : IEventHandler { private readonly Image image; public BackgroundEventHandler(Image image) { this.image = image; } public void HandleEvent(Event docEvent) { this.AddBackgroundImage(docEvent); } private void AddBackgroundImage(Event docEvent) { var documentEvent = docEvent as PdfDocumentEvent; PdfDocument pdfDocument = documentEvent?.GetDocument(); PdfPage page = documentEvent?.GetPage(); PdfCanvas pdfCanvas = new PdfCanvas(page?.NewContentStreamBefore(), page?.GetResources(), pdfDocument); Rectangle area = page?.GetPageSize(); var canvas = new Canvas(pdfCanvas, pdfDocument, area); canvas.Add(this.image); } } }
// <copyright file="Invoice.cs" company="Johannes Ebner"> // Copyright (c) Johannes Ebner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root or https://spdx.org/licenses/MIT.html for full license information. // </copyright> using iText.Kernel.Events; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Layout; using iText.Layout.Element; namespace Claimini.Api.Repository.Pdf { public class BackgroundEventHandler : IEventHandler { private readonly Image image; public BackgroundEventHandler(Image image) { this.image = image; } public void HandleEvent(Event docEvent) { var documentEvent = docEvent as PdfDocumentEvent; PdfDocument pdfDocument = documentEvent?.GetDocument(); PdfPage page = documentEvent?.GetPage(); PdfCanvas canvas = new PdfCanvas(page?.NewContentStreamBefore(), page?.GetResources(), pdfDocument); Rectangle area = page?.GetPageSize(); new Canvas(canvas, pdfDocument, area).Add(this.image); } } }
mit
C#
be78dae5de677053b8c58398b9ecf3d5d7b5ba65
Update IScriptBuilder interface
Ackara/Daterpillar
src/Daterpillar.Core/TextTransformation/IScriptBuilder.cs
src/Daterpillar.Core/TextTransformation/IScriptBuilder.cs
namespace Gigobyte.Daterpillar.TextTransformation { public interface IScriptBuilder { string GetContent(); void Append(string text); void AppendLine(string text); void Create(Table table); void Create(Column column); void Create(Index index); void Create(ForeignKey foreignKey); void Drop(Table table); void Drop(Column column); void Drop(Index index); void Drop(ForeignKey foreignKey); void AlterTable(Table oldTable, Table newTable); void AlterTable(Column oldColumn, Column newColumn); } }
namespace Gigobyte.Daterpillar.TextTransformation { public interface IScriptBuilder { void Append(string text); void AppendLine(string text); void Create(Table table); void Create(Index index); void Create(ForeignKey foreignKey); void Drop(Table table); void Drop(Index index); void Drop(ForeignKey foreignKey); void AlterTable(Table tableA, Table tableB); byte[] GetContentAsBytes(); string GetContentAsString(); } }
mit
C#
b7d6559e570e367f3a5bfc186abad1207c0b3464
Disable command debugging for now, and clean up.
MrJoy/UnityGit
ShellHelpers.cs
ShellHelpers.cs
//define DEBUG_COMMANDS using System.Diagnostics; public class ShellHelpers { public static Process StartProcess(string filename, string arguments) { #if DEBUG_COMMANDS UnityEngine.Debug.Log("Running: " + filename + " " + arguments); #endif Process p = new Process(); p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = filename; p.Start(); return p; } public static string OutputFromCommand(string filename, string arguments) { var p = StartProcess(filename, arguments); var output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if(output.EndsWith("\n")) output = output.Substring(0, output.Length - 1); return output; } }
#define DEBUG_COMMANDS //using UnityEditor; //using UnityEngine; //using System.Collections; using System.Diagnostics; public class ShellHelpers { public static Process StartProcess(string filename, string arguments) { #if DEBUG_COMMANDS UnityEngine.Debug.Log("Running: " + filename + " " + arguments); #endif Process p = new Process(); p.StartInfo.Arguments = arguments; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = filename; p.Start(); return p; } public static string OutputFromCommand(string filename, string arguments) { var p = StartProcess(filename, arguments); var output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if(output.EndsWith("\n")) output = output.Substring(0, output.Length - 1); return output; } }
mit
C#
650c65a9a8a55a708b17ea588ae3385bcfc21734
Remove default title
demyanenko/hutel,demyanenko/hutel,demyanenko/hutel
server/Views/Shared/_Layout.cshtml
server/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" /> <environment names="Staging,Production"> <link rel="stylesheet" href="~/dist/site.css" asp-append-version="true" /> </environment> </head> <body> @RenderBody() <script src="~/dist/vendor.js" asp-append-version="true"></script> @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - dotnet_react</title> <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" /> <environment names="Staging,Production"> <link rel="stylesheet" href="~/dist/site.css" asp-append-version="true" /> </environment> </head> <body> @RenderBody() <script src="~/dist/vendor.js" asp-append-version="true"></script> @RenderSection("scripts", required: false) </body> </html>
apache-2.0
C#
3b4556c44a7c9416e8437c0b9eec78197726c4e1
Fix for #3, error message incorrectly refers to profile instead of to do list
skwan/WebApp-GroupClaims-DotNet,AzureADSamples/WebApp-GroupClaims-DotNet,wvdd007/WebApp-GroupClaims-DotNet,Azure-Samples/active-directory-dotnet-webapp-groupclaims,Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect,Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect,AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet,AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet,wvdd007/WebApp-GroupClaims-DotNet,AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet,skwan/WebApp-GroupClaims-DotNet,AzureADSamples/WebApp-GroupClaims-DotNet,jkorell/WebApp-WebAPI-OpenIDConnect-DotNet,Azure-Samples/active-directory-dotnet-webapp-groupclaims,wvdd007/WebApp-GroupClaims-DotNet,jkorell/WebApp-WebAPI-OpenIDConnect-DotNet,Azure-Samples/active-directory-dotnet-webapp-groupclaims,AzureADSamples/WebApp-GroupClaims-DotNet,jkorell/WebApp-WebAPI-OpenIDConnect-DotNet,skwan/WebApp-GroupClaims-DotNet,Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
TodoListWebApp/Views/TodoList/Index.cshtml
TodoListWebApp/Views/TodoList/Index.cshtml
@model IEnumerable<TodoListWebApp.Models.TodoItem> @{ ViewBag.Title = "To Do List"; } <h3>Add an Item</h3> @if (ViewBag.ErrorMessage == null) { <form name="input" action="TodoList" method="post"> New Item: <input type="text" name="item"> <input type="submit" value="Submit"> </form> } <table class="table table-bordered table-striped"> <tr> <th>Item Name</th> </tr> @foreach (var i in Model) { <tr> <td>@i.Title</td> </tr> } </table> @if (ViewBag.ErrorMessage == "AuthorizationRequired") { <p>You have to sign-in to see your to do list. Click @Html.ActionLink("here", "Index", "TodoList", new { reauth = true }, null) to sign-in.</p> } @if (ViewBag.ErrorMessage == "UnexpectedError") { <p>An unexpected error occurred while retrieving your to do list. Please try again. You may need to sign-in.</p> }
@model IEnumerable<TodoListWebApp.Models.TodoItem> @{ ViewBag.Title = "To Do List"; } <h3>Add an Item</h3> @if (ViewBag.ErrorMessage == null) { <form name="input" action="TodoList" method="post"> New Item: <input type="text" name="item"> <input type="submit" value="Submit"> </form> } <table class="table table-bordered table-striped"> <tr> <th>Item Name</th> </tr> @foreach (var i in Model) { <tr> <td>@i.Title</td> </tr> } </table> @if (ViewBag.ErrorMessage == "AuthorizationRequired") { <p>You have to sign-in to see your profile. Click @Html.ActionLink("here", "Index", "TodoList", new { reauth = true }, null) to sign-in.</p> } @if (ViewBag.ErrorMessage == "UnexpectedError") { <p>An unexpected error occurred while retrieving your to do list. Please try again. You may need to sign-in.</p> }
apache-2.0
C#
f255b45b176faa4b468765fcf14587dff662f52f
Update ValuesController.cs
cayodonatti/TopGearApi
TopGearApi/Controllers/ValuesController.cs
TopGearApi/Controllers/ValuesController.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace TopGearApi.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } [HttpGet] [Route("Test")] public IHttpActionResult Obter() { var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " }); return base.Json(content); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; namespace TopGearApi.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } [System.Web.Http.HttpGet] [System.Web.Http.Route("Test")] public ActionResult Obter() { /*var content = JsonConvert.SerializeObject(new { ab = "teste1", cd = "teste2 " }); return base.Json(content);*/ // Then I return the list return new JsonResult { Data = new { ab = "teste1", cd = "teste2 " } }; } } }
mit
C#
bdfa15927b4ac5c55d28ca2fbb147075fccefb35
Fix namespace in NameAggregationReflectionVisitor
riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy
test/DotvvmAcademy.Validation.CSharp.Tests/NameAggregationReflectionVisitor.cs
test/DotvvmAcademy.Validation.CSharp.Tests/NameAggregationReflectionVisitor.cs
using System; using System.Collections.Generic; using System.Reflection; namespace DotvvmAcademy.Validation.CSharp.Tests { public class NameAggregationReflectionVisitor : ReflectionVisitor { public List<string> FullNames { get; set; } = new List<string>(); public override void VisitAssembly(Assembly assembly) { FullNames.Add(assembly.FullName); foreach (var type in assembly.GetTypes()) { Visit(type); } } public override void VisitEvent(EventInfo member) { FullNames.Add(member.Name); if (member.AddMethod != null) { Visit(member.AddMethod); } if (member.RemoveMethod != null) { Visit(member.RemoveMethod); } } public override void VisitField(FieldInfo member) { FullNames.Add(member.Name); } public override void VisitMethod(MethodBase member) { FullNames.Add(member.Name); } public override void VisitProperty(PropertyInfo member) { FullNames.Add(member.Name); if (member.GetMethod != null) { Visit(member.GetMethod); } if (member.SetMethod != null) { Visit(member.SetMethod); } } public override void VisitType(Type member) { FullNames.Add(member.FullName); foreach (var descendant in member.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) { Visit(descendant); } } } }
using System; using System.Collections.Generic; using System.Reflection; namespace DotvvmAcademy.Validation.Tests { public class NameAggregationReflectionVisitor : ReflectionVisitor { public List<string> FullNames { get; set; } = new List<string>(); public override void VisitAssembly(Assembly assembly) { FullNames.Add(assembly.FullName); foreach (var type in assembly.GetTypes()) { Visit(type); } } public override void VisitEvent(EventInfo member) { FullNames.Add(member.Name); if (member.AddMethod != null) { Visit(member.AddMethod); } if (member.RemoveMethod != null) { Visit(member.RemoveMethod); } } public override void VisitField(FieldInfo member) { FullNames.Add(member.Name); } public override void VisitMethod(MethodBase member) { FullNames.Add(member.Name); } public override void VisitProperty(PropertyInfo member) { FullNames.Add(member.Name); if (member.GetMethod != null) { Visit(member.GetMethod); } if (member.SetMethod != null) { Visit(member.SetMethod); } } public override void VisitType(Type member) { FullNames.Add(member.FullName); foreach (var descendant in member.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) { Visit(descendant); } } } }
apache-2.0
C#
1ccf20fd5db51857ccb30b393ec0df90a78976e7
Remove Console.Read
gregsochanik/7d-feedmunch
src/FeedMuncher/Program.cs
src/FeedMuncher/Program.cs
using FeedMuncher.IOC.StructureMap; namespace FeedMuncher { class Program { static void Main(string[] args) { Bootstrap.ConfigureDependencies(); var feedMunchConfig = FeedMunch.Configure.FromConsoleArgs(args); FeedMunch.Download .WithConfig(feedMunchConfig) .Invoke(); } } }
using System; using FeedMuncher.IOC.StructureMap; namespace FeedMuncher { class Program { static void Main(string[] args) { Bootstrap.ConfigureDependencies(); var feedMunchConfig = FeedMunch.Configure.FromConsoleArgs(args); FeedMunch.Download .WithConfig(feedMunchConfig) .Invoke(); Console.Read(); } } }
mit
C#
40ee51846cb59d04c194642c3770e18cf5f07e87
Add allocations column (#1422)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.Server.Kestrel.Performance/configs/CoreConfig.cs
test/Microsoft.AspNetCore.Server.Kestrel.Performance/configs/CoreConfig.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Validators; namespace Microsoft.AspNetCore.Server.Kestrel.Performance { public class CoreConfig : ManualConfig { public CoreConfig() { Add(JitOptimizationsValidator.FailOnError); Add(MemoryDiagnoser.Default); Add(new RpsColumn()); Add(Job.Default .With(BenchmarkDotNet.Environments.Runtime.Core) .WithRemoveOutliers(false) .With(new GcMode() { Server = true }) .With(RunStrategy.Throughput) .WithLaunchCount(3) .WithWarmupCount(5) .WithTargetCount(10)); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using BenchmarkDotNet.Configs; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Validators; namespace Microsoft.AspNetCore.Server.Kestrel.Performance { public class CoreConfig : ManualConfig { public CoreConfig() { Add(JitOptimizationsValidator.FailOnError); Add(new RpsColumn()); Add(Job.Default .With(BenchmarkDotNet.Environments.Runtime.Core) .WithRemoveOutliers(false) .With(new GcMode() { Server = true }) .With(RunStrategy.Throughput) .WithLaunchCount(3) .WithWarmupCount(5) .WithTargetCount(10)); } } }
apache-2.0
C#
224e9694a4e3b7fec22d907f6bfdba4985220178
Set OperationId via annotations in test project
domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy
test/WebSites/Basic/Controllers/SwaggerAnnotationsController.cs
test/WebSites/Basic/Controllers/SwaggerAnnotationsController.cs
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using Basic.Swagger; namespace Basic.Controllers { [SwaggerTag("Manipulate Carts to your heart's content", "http://www.tempuri.org")] public class SwaggerAnnotationsController { [HttpPost("/carts")] [SwaggerResponse(201, "The cart was created", typeof(Cart))] [SwaggerResponse(400, "The cart data is invalid")] public Cart Create([FromBody]Cart cart) { return new Cart { Id = 1 }; } [HttpGet("/carts/{id}")] [SwaggerOperationFilter(typeof(AddCartsByIdGetExternalDocs))] public Cart GetById(int id) { return new Cart { Id = id }; } [HttpDelete("/carts/{id}")] [SwaggerOperation( OperationId = "DeleteCart", Summary = "Deletes a specific cart", Description = "Requires admin privileges", Consumes = new string[] { "test/plain", "application/json" }, Produces = new string[] { "application/javascript", "application/xml" })] public Cart Delete([FromRoute(Name = "id"), SwaggerParameter("The cart identifier")]int cartId) { return new Cart { Id = cartId }; } } public class Cart { public int Id { get; internal set; } } }
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using Basic.Swagger; namespace Basic.Controllers { [SwaggerTag("Manipulate Carts to your heart's content", "http://www.tempuri.org")] public class SwaggerAnnotationsController { [HttpPost("/carts")] [SwaggerResponse(201, "The cart was created", typeof(Cart))] [SwaggerResponse(400, "The cart data is invalid")] public Cart Create([FromBody]Cart cart) { return new Cart { Id = 1 }; } [HttpGet("/carts/{id}")] [SwaggerOperationFilter(typeof(AddCartsByIdGetExternalDocs))] public Cart GetById(int id) { return new Cart { Id = id }; } [HttpDelete("/carts/{id}")] [SwaggerOperation( Summary = "Deletes a specific cart", Description = "Requires admin privileges", Consumes = new string[] { "test/plain", "application/json" }, Produces = new string[] { "application/javascript", "application/xml" })] public Cart Delete([FromRoute(Name = "id"), SwaggerParameter("The cart identifier")]int cartId) { return new Cart { Id = cartId }; } } public class Cart { public int Id { get; internal set; } } }
mit
C#
ae1a0c3094bafb0d77db5e9465e4c86465721d2e
Update ZoomBorderTests.cs
wieslawsoltes/PanAndZoom,wieslawsoltes/MatrixPanAndZoomDemo,PanAndZoom/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/PanAndZoom
tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomBorderTests.cs
tests/Avalonia.Controls.PanAndZoom.UnitTests/ZoomBorderTests.cs
using Xunit; namespace Avalonia.Controls.PanAndZoom.UnitTests { public class ZoomBorderTests { [Fact(Skip = "The CI tests are failing.")] public void ZoomBorder_Ctor() { var target = new ZoomBorder(); Assert.NotNull(target); Assert.Equal(ButtonName.Middle, target.PanButton); Assert.Equal(1.2, target.ZoomSpeed); Assert.Equal(StretchMode.Uniform, target.Stretch); Assert.Equal(1.0, target.ZoomX); Assert.Equal(1.0, target.ZoomY); Assert.Equal(0.0, target.OffsetX); Assert.Equal(0.0, target.OffsetY); Assert.True(target.EnableConstrains); Assert.Equal(double.NegativeInfinity, target.MinZoomX); Assert.Equal(double.PositiveInfinity, target.MaxZoomX); Assert.Equal(double.NegativeInfinity, target.MinZoomY); Assert.Equal(double.PositiveInfinity, target.MaxZoomY); Assert.Equal(double.NegativeInfinity, target.MinOffsetX); Assert.Equal(double.PositiveInfinity, target.MaxOffsetX); Assert.Equal(double.NegativeInfinity, target.MinOffsetY); Assert.Equal(double.PositiveInfinity, target.MaxOffsetY); Assert.True(target.EnablePan); Assert.True(target.EnableZoom); Assert.True(target.EnableGestureZoom); Assert.True(target.EnableGestureRotation); Assert.True(target.EnableGestureTranslation); } } }
using Xunit; namespace Avalonia.Controls.PanAndZoom.UnitTests { public class ZoomBorderTests { [Fact] public void ZoomBorder_Ctor() { var target = new ZoomBorder(); Assert.NotNull(target); Assert.Equal(ButtonName.Middle, target.PanButton); Assert.Equal(1.2, target.ZoomSpeed); Assert.Equal(StretchMode.Uniform, target.Stretch); Assert.Equal(1.0, target.ZoomX); Assert.Equal(1.0, target.ZoomY); Assert.Equal(0.0, target.OffsetX); Assert.Equal(0.0, target.OffsetY); Assert.True(target.EnableConstrains); Assert.Equal(double.NegativeInfinity, target.MinZoomX); Assert.Equal(double.PositiveInfinity, target.MaxZoomX); Assert.Equal(double.NegativeInfinity, target.MinZoomY); Assert.Equal(double.PositiveInfinity, target.MaxZoomY); Assert.Equal(double.NegativeInfinity, target.MinOffsetX); Assert.Equal(double.PositiveInfinity, target.MaxOffsetX); Assert.Equal(double.NegativeInfinity, target.MinOffsetY); Assert.Equal(double.PositiveInfinity, target.MaxOffsetY); Assert.True(target.EnablePan); Assert.True(target.EnableZoom); Assert.True(target.EnableGestureZoom); Assert.True(target.EnableGestureRotation); Assert.True(target.EnableGestureTranslation); } } }
mit
C#
970e1b39c1aa8ecd745a550d04a0c6f1efcd0e78
更新版本号到4.1,发布nuget程序集
xiaobudian/osharp
src/VersionAssemblyInfo.cs
src/VersionAssemblyInfo.cs
 // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] using System.Reflection; [assembly: AssemblyVersion("4.0")] [assembly: AssemblyFileVersion("4.1")] [assembly: AssemblyInformationalVersion("4.1")]
 // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] using System.Reflection; [assembly: AssemblyVersion("4.0")] [assembly: AssemblyFileVersion("4.0.30")] [assembly: AssemblyInformationalVersion("4.0.30")]
apache-2.0
C#
6f813cf8f472b1f25faf7e389ff6088d2ccc67b2
Patch from Rduerden to use the correct value on timer repeats.
jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos
src/Manos/Libev/TimerWatcher.cs
src/Manos/Libev/TimerWatcher.cs
using System; using System.Runtime.InteropServices; namespace Libev { public class TimerWatcher : Watcher { private TimerWatcherCallback callback; private UnmanagedTimerWatcher unmanaged_watcher; private static IntPtr unmanaged_callback_ptr; private static UnmanagedWatcherCallback unmanaged_callback; static TimerWatcher () { unmanaged_callback = new UnmanagedWatcherCallback (StaticCallback); unmanaged_callback_ptr = Marshal.GetFunctionPointerForDelegate (unmanaged_callback); } public TimerWatcher (TimeSpan repeat, Loop loop, TimerWatcherCallback callback) : this (TimeSpan.Zero, repeat, loop, callback) { } public TimerWatcher (TimeSpan after, TimeSpan repeat, Loop loop, TimerWatcherCallback callback) : base (loop) { this.callback = callback; unmanaged_watcher = new UnmanagedTimerWatcher (); unmanaged_watcher.callback = unmanaged_callback_ptr; unmanaged_watcher.after = after.TotalSeconds; unmanaged_watcher.repeat = repeat.TotalSeconds; InitializeUnmanagedWatcher (unmanaged_watcher); } private static void StaticCallback (IntPtr loop, IntPtr watcher, EventTypes revents) { UnmanagedTimerWatcher iow = (UnmanagedTimerWatcher) Marshal.PtrToStructure (watcher, typeof (UnmanagedTimerWatcher)); GCHandle gchandle = GCHandle.FromIntPtr (iow.data); TimerWatcher w = (TimerWatcher) gchandle.Target; w.callback (w.Loop, w, revents); } /* public TimeSpan Repeat { get { return TimeSpan.FromSeconds (unmanaged_watcher.repeat); } set { unmanaged_watcher.repeat = value.TotalSeconds; } } */ protected override void StartImpl () { unmanaged_watcher.data = GCHandle.ToIntPtr (gc_handle); Marshal.StructureToPtr (unmanaged_watcher, watcher_ptr, false); ev_timer_start (Loop.Handle, WatcherPtr); } protected override void StopImpl () { ev_timer_stop (Loop.Handle, WatcherPtr); } protected override void UnmanagedCallbackHandler (IntPtr loop, IntPtr watcher, EventTypes revents) { callback (Loop, this, revents); } [DllImport ("libev", CallingConvention = CallingConvention.Cdecl)] private static extern void ev_timer_start (IntPtr loop, IntPtr watcher); [DllImport ("libev", CallingConvention = CallingConvention.Cdecl)] private static extern void ev_timer_stop (IntPtr loop, IntPtr watcher); } [UnmanagedFunctionPointer (System.Runtime.InteropServices.CallingConvention.Cdecl)] public delegate void TimerWatcherCallback (Loop loop, TimerWatcher watcher, EventTypes revents); [StructLayout (LayoutKind.Sequential)] internal struct UnmanagedTimerWatcher { public int active; public int pending; public int priority; public IntPtr data; public IntPtr callback; public double after; public double repeat; } }
using System; using System.Runtime.InteropServices; namespace Libev { public class TimerWatcher : Watcher { private TimerWatcherCallback callback; private UnmanagedTimerWatcher unmanaged_watcher; private static IntPtr unmanaged_callback_ptr; private static UnmanagedWatcherCallback unmanaged_callback; static TimerWatcher () { unmanaged_callback = new UnmanagedWatcherCallback (StaticCallback); unmanaged_callback_ptr = Marshal.GetFunctionPointerForDelegate (unmanaged_callback); } public TimerWatcher (TimeSpan repeat, Loop loop, TimerWatcherCallback callback) : this (TimeSpan.Zero, repeat, loop, callback) { } public TimerWatcher (TimeSpan after, TimeSpan repeat, Loop loop, TimerWatcherCallback callback) : base (loop) { this.callback = callback; unmanaged_watcher = new UnmanagedTimerWatcher (); unmanaged_watcher.callback = unmanaged_callback_ptr; unmanaged_watcher.after = after.TotalSeconds; unmanaged_watcher.repeat = after.TotalSeconds; InitializeUnmanagedWatcher (unmanaged_watcher); } private static void StaticCallback (IntPtr loop, IntPtr watcher, EventTypes revents) { UnmanagedTimerWatcher iow = (UnmanagedTimerWatcher) Marshal.PtrToStructure (watcher, typeof (UnmanagedTimerWatcher)); GCHandle gchandle = GCHandle.FromIntPtr (iow.data); TimerWatcher w = (TimerWatcher) gchandle.Target; w.callback (w.Loop, w, revents); } /* public TimeSpan Repeat { get { return TimeSpan.FromSeconds (unmanaged_watcher.repeat); } set { unmanaged_watcher.repeat = value.TotalSeconds; } } */ protected override void StartImpl () { unmanaged_watcher.data = GCHandle.ToIntPtr (gc_handle); Marshal.StructureToPtr (unmanaged_watcher, watcher_ptr, false); ev_timer_start (Loop.Handle, WatcherPtr); } protected override void StopImpl () { ev_timer_stop (Loop.Handle, WatcherPtr); } protected override void UnmanagedCallbackHandler (IntPtr loop, IntPtr watcher, EventTypes revents) { callback (Loop, this, revents); } [DllImport ("libev", CallingConvention = CallingConvention.Cdecl)] private static extern void ev_timer_start (IntPtr loop, IntPtr watcher); [DllImport ("libev", CallingConvention = CallingConvention.Cdecl)] private static extern void ev_timer_stop (IntPtr loop, IntPtr watcher); } [UnmanagedFunctionPointer (System.Runtime.InteropServices.CallingConvention.Cdecl)] public delegate void TimerWatcherCallback (Loop loop, TimerWatcher watcher, EventTypes revents); [StructLayout (LayoutKind.Sequential)] internal struct UnmanagedTimerWatcher { public int active; public int pending; public int priority; public IntPtr data; public IntPtr callback; public double after; public double repeat; } }
mit
C#
2be8afabc25ed562259fb9550cae539d0484efe6
修改 class SeedData.
NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie
src/MvcMovie/Models/SeedData.cs
src/MvcMovie/Models/SeedData.cs
using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; namespace MvcMovie.Models { public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { var context = serviceProvider.GetService<ApplicationDbContext>(); if (context.Database == null) { throw new Exception("DB is null"); } if (context.Movie.Any()) { return; // DB has been seeded } context.Movie.AddRange( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-1-11"), Genre = "Romantic Comedy", Price = 7.99M }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M }, new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M } ); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MvcMovie.Models { public class SeedData { } }
apache-2.0
C#
266bf621847a5b6fb9fb7da7968a97fccd9821b6
Use OnAttachedToVisualTree and OnDetachedFromVisualTree
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/BindTagToVisualRootDataContextBehavior.cs
src/Avalonia.Xaml.Interactions/Custom/BindTagToVisualRootDataContextBehavior.cs
using System; using Avalonia.Controls; using Avalonia.VisualTree; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// Binds AssociatedObject object Tag property to root visual DataContext. /// </summary> public class BindTagToVisualRootDataContextBehavior : Behavior<Control> { private IDisposable? _disposable; /// <inheritdoc/> protected override void OnAttachedToVisualTree() { base.OnAttachedToVisualTree(); _disposable = BindDataContextToTag((IControl)AssociatedObject.GetVisualRoot(), AssociatedObject); } /// <inheritdoc/> protected override void OnDetachedFromVisualTree() { base.OnDetachedFromVisualTree(); _disposable?.Dispose(); } private static IDisposable? BindDataContextToTag(IControl source, IControl? target) { if (source is null) throw new ArgumentNullException(nameof(source)); if (target is null) throw new ArgumentNullException(nameof(target)); var data = source.GetObservable(StyledElement.DataContextProperty); return data is { } ? target.Bind(Control.TagProperty, data) : null; } }
using System; using Avalonia.Controls; using Avalonia.VisualTree; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// Binds AssociatedObject object Tag property to root visual DataContext. /// </summary> public class BindTagToVisualRootDataContextBehavior : Behavior<Control> { private IDisposable? _disposable; /// <inheritdoc/> protected override void OnAttached() { base.OnAttached(); if (AssociatedObject is { }) { AssociatedObject.AttachedToVisualTree += AssociatedObject_AttachedToVisualTree; } } /// <inheritdoc/> protected override void OnDetaching() { base.OnDetaching(); if (AssociatedObject is { }) { AssociatedObject.AttachedToVisualTree -= AssociatedObject_AttachedToVisualTree; } _disposable?.Dispose(); } private void AssociatedObject_AttachedToVisualTree(object? sender, VisualTreeAttachmentEventArgs e) { _disposable = BindDataContextToTag((IControl)AssociatedObject.GetVisualRoot(), AssociatedObject); } private static IDisposable? BindDataContextToTag(IControl source, IControl? target) { if (source is null) throw new ArgumentNullException(nameof(source)); if (target is null) throw new ArgumentNullException(nameof(target)); var data = source.GetObservable(StyledElement.DataContextProperty); return data is { } ? target.Bind(Control.TagProperty, data) : null; } }
mit
C#
98aa44b2f6fe9cbfbd3f7f9a8a90a94d609dfb5b
Update LocalizedString.shared.cs (#1071)
FormsCommunityToolkit/FormsCommunityToolkit
src/CommunityToolkit/Xamarin.CommunityToolkit/Helpers/LocalizedString.shared.cs
src/CommunityToolkit/Xamarin.CommunityToolkit/Helpers/LocalizedString.shared.cs
using System; using Xamarin.CommunityToolkit.ObjectModel; using Xamarin.Forms.Internals; namespace Xamarin.CommunityToolkit.Helpers { #if !NETSTANDARD1_0 public class LocalizedString : ObservableObject { readonly Func<string> generator; public LocalizedString(Func<string> generator) : this(LocalizationResourceManager.Current, generator) { } public LocalizedString(LocalizationResourceManager localizationManager, Func<string> generator) { this.generator = generator; // This instance will be unsubscribed and GCed if no one references it // since LocalizationResourceManager uses WeekEventManger localizationManager.PropertyChanged += (sender, e) => OnPropertyChanged(null); } [Preserve(Conditional = true)] public string Localized => generator(); [Preserve(Conditional = true)] public static implicit operator LocalizedString(Func<string> func) => new LocalizedString(func); } #endif }
using System; using Xamarin.CommunityToolkit.ObjectModel; using Xamarin.Forms.Internals; namespace Xamarin.CommunityToolkit.Helpers { #if !NETSTANDARD1_0 public class LocalizedString : ObservableObject { readonly Func<string> generator; public LocalizedString(Func<string> generator) : this(LocalizationResourceManager.Current, generator) { } public LocalizedString(LocalizationResourceManager localizationManager, Func<string> generator) { this.generator = generator; // This instance will be unsubscribed and GCed if no one references it // since LocalizationResourceManager uses WeekEventManger localizationManager.PropertyChanged += (sender, e) => OnPropertyChanged(null); } public string Localized => generator(); [Preserve(Conditional = true)] public static implicit operator LocalizedString(Func<string> func) => new LocalizedString(func); } #endif }
mit
C#
dd0a986141ab2c84f1a1219be64808fe84f66e0f
Set nuget package version to 2.0.0
Jericho/CakeMail.RestClient
CakeMail.RestClient/Properties/AssemblyInfo.cs
CakeMail.RestClient/Properties/AssemblyInfo.cs
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0")]
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-beta03")]
mit
C#
758c5337e96bcb98021f7cbf7bc2fca0297c1943
Update Commit class
pfjason/GitLab-dot-NET
Types/Commit.cs
Types/Commit.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using unirest_net.http; using System.Web; namespace GitLab { public partial class GitLab { public partial class Project { /// <summary> /// Gitlab Project Commit object /// </summary> public class Commit { public string id , short_id , title , author_name , author_email , created_at , message , committer_name , committer_email , authored_date , committed_date; public string[] parent_ids; public bool allow_failure; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using unirest_net.http; using System.Web; namespace GitLab { public partial class GitLab { public partial class Project { public class Commit { public string id, short_id, title, author_name, author_email, created_at, message; public string[] parent_ids; public bool allow_failure; } } } }
mit
C#
03f02732a72661c7128367e8a5e16df1d2fd3194
add serialization between byte-stream and AccountStore data object
kingsamchen/EasyKeeper
VaultMarshal.cs
VaultMarshal.cs
/* @ Kingsley Chen */ using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace EasyKeeper { public static class VaultMarshal { private const uint ProtoclVersion = 1U; public static void Marshal(string pwd, AccountStore store, Stream outStream) {} public static AccountStore Unmarshal(Stream inStream, string pwd) { return null; } private static byte[] AccountStoreToBytes(AccountStore store) { using (MemoryStream mem = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(mem, store); return mem.ToArray(); } } private static AccountStore AccountStoreFromBytes(byte[] rawBytes) { using (MemoryStream mem = new MemoryStream(rawBytes)) { IFormatter formatter = new BinaryFormatter(); var accountStore = formatter.Deserialize(mem) as AccountStore; return accountStore; } } } }
/* @ Kingsley Chen */ using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace EasyKeeper { public static class VaultMarshal { private const uint ProtoclVersion = 1U; public static void Marshal(string pwd, AccountStore store, Stream outStream) {} public static AccountStore Unmarshal(Stream inStream, string pwd) { return null; } private static byte[] AccountStoreToBytes(AccountStore store) { using (MemoryStream mem = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(mem, store); return mem.ToArray(); } } private static AccountStore AccountStoreFromBytes(byte[] rawBytes) { return null; } } }
mit
C#
1484c923eca8ff492d21751b6ab305eed8755795
Switch direct handling by a asyncrhonous dispatching in core sample
Vtek/Bartender
samples/CoreApplication/Program.cs
samples/CoreApplication/Program.cs
using System; using System.Threading.Tasks; using Bartender; using ConsoleApplication.Registries; using CoreApplication.Domain.Personne.Create; using CoreApplication.Domain.Personne.Read; using StructureMap; namespace ConsoleApplication { public class Program { static IContainer Container { get; set; } public static void Main(string[] args) { var registry = new Registry(); registry.IncludeRegistry<InfrastructureRegistry>(); Container = new Container(registry); Task t = RunAsync(); t.Wait(); Console.ReadKey(); } static async Task RunAsync() { var dispatcher = Container.GetInstance<IAsyncDispatcher>(); await dispatcher.DispatchAsync(new CreatePersonCommand()); var person = await dispatcher.DispatchAsync<GetPersonQuery, GetPersonReadModel>(new GetPersonQuery()); Console.WriteLine($"Hello {person.Name} !"); } } }
using System; using System.Threading.Tasks; using Bartender; using ConsoleApplication.Registries; using CoreApplication.Domain.Personne.Create; using CoreApplication.Domain.Personne.Read; using StructureMap; namespace ConsoleApplication { public class Program { static IContainer Container { get; set; } public static void Main(string[] args) { var registry = new Registry(); registry.IncludeRegistry<InfrastructureRegistry>(); Container = new Container(registry); Task t = RunAsync(); t.Wait(); Console.ReadKey(); } static async Task RunAsync() { var createPersonCommandHandler = Container.GetInstance<IAsyncHandler<CreatePersonCommand>>(); await createPersonCommandHandler.HandleAsync(new CreatePersonCommand()); var getPersonQueryHandler = Container.GetInstance<IAsyncHandler<GetPersonQuery, GetPersonReadModel>>(); var person = await getPersonQueryHandler.HandleAsync(new GetPersonQuery()); Console.WriteLine($"Hello {person.Name} !"); } } }
mit
C#
b8b8e1d02de635f79633a6db5eb2c3320c88437f
Change to avoid modifying the database on publish.
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
MobileApp/smarttripsService/App_Start/Startup.MobileApp.cs
MobileApp/smarttripsService/App_Start/Startup.MobileApp.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Web.Http; using Microsoft.Azure.Mobile.Server; using Microsoft.Azure.Mobile.Server.Authentication; using Microsoft.Azure.Mobile.Server.Config; using MyTrips.DataObjects; using smarttripsService.Models; using Owin; using Microsoft.Azure.Mobile.Server.Tables; namespace smarttripsService { public partial class Startup { public static void ConfigureMobileApp(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686 config.EnableSystemDiagnosticsTracing(); new MobileAppConfiguration() .UseDefaultConfiguration() .ApplyTo(config); // Use Entity Framework Code First to create database tables based on your DbContext //Database.SetInitializer(new smarttripsInitializer()); // To prevent Entity Framework from modifying your database schema, use a null database initializer Database.SetInitializer<smarttripsContext>(null); MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings(); if (string.IsNullOrEmpty(settings.HostName)) { // This middleware is intended to be used locally for debugging. By default, HostName will // only have a value when running in an App Service application. app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions { SigningKey = ConfigurationManager.AppSettings["SigningKey"], ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] }, ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] }, TokenHandler = config.GetAppServiceTokenHandler() }); } app.UseWebApi(config); } } /* public class smarttripsInitializer : DropCreateDatabaseAlways<smarttripsContext> { public override void InitializeDatabase(smarttripsContext context) { base.InitializeDatabase(context); } } */ }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Web.Http; using Microsoft.Azure.Mobile.Server; using Microsoft.Azure.Mobile.Server.Authentication; using Microsoft.Azure.Mobile.Server.Config; using MyTrips.DataObjects; using smarttripsService.Models; using Owin; using Microsoft.Azure.Mobile.Server.Tables; namespace smarttripsService { public partial class Startup { public static void ConfigureMobileApp(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686 config.EnableSystemDiagnosticsTracing(); new MobileAppConfiguration() .UseDefaultConfiguration() .ApplyTo(config); // Use Entity Framework Code First to create database tables based on your DbContext Database.SetInitializer(new smarttripsInitializer()); // To prevent Entity Framework from modifying your database schema, use a null database initializer // Database.SetInitializer<smarttripsContext>(null); MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings(); if (string.IsNullOrEmpty(settings.HostName)) { // This middleware is intended to be used locally for debugging. By default, HostName will // only have a value when running in an App Service application. app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions { SigningKey = ConfigurationManager.AppSettings["SigningKey"], ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] }, ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] }, TokenHandler = config.GetAppServiceTokenHandler() }); } app.UseWebApi(config); } } public class smarttripsInitializer : DropCreateDatabaseAlways<smarttripsContext> { public override void InitializeDatabase(smarttripsContext context) { base.InitializeDatabase(context); } } }
mit
C#
cbe1cc1bc8d0da0a4dac3cc644d9df3bc94941da
refactor common setup in uuid gatherer test
ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,OpenSimian/opensimulator,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,N3X15/VoxelSim,rryk/omp-server,AlphaStaxLLC/taiga,justinccdev/opensim,allquixotic/opensim-autobackup,OpenSimian/opensimulator,justinccdev/opensim,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-extras,TomDataworks/opensim,allquixotic/opensim-autobackup,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,AlphaStaxLLC/taiga,RavenB/opensim,OpenSimian/opensimulator,AlphaStaxLLC/taiga,RavenB/opensim,AlexRa/opensim-mods-Alex,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip,justinccdev/opensim,justinccdev/opensim,cdbean/CySim,RavenB/opensim,Michelle-Argus/ArribasimExtract,AlphaStaxLLC/taiga,Michelle-Argus/ArribasimExtract,rryk/omp-server,justinccdev/opensim,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-extras,allquixotic/opensim-autobackup,allquixotic/opensim-autobackup,TechplexEngineer/Aurora-Sim,ft-/opensim-optimizations-wip,OpenSimian/opensimulator,QuillLittlefeather/opensim-1,cdbean/CySim,allquixotic/opensim-autobackup,N3X15/VoxelSim,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-extras,cdbean/CySim,cdbean/CySim,AlexRa/opensim-mods-Alex,BogusCurry/arribasim-dev,bravelittlescientist/opensim-performance,AlphaStaxLLC/taiga,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-extras,N3X15/VoxelSim,bravelittlescientist/opensim-performance,Michelle-Argus/ArribasimExtract,bravelittlescientist/opensim-performance,ft-/arribasim-dev-tests,AlphaStaxLLC/taiga,cdbean/CySim,ft-/opensim-optimizations-wip,AlphaStaxLLC/taiga,N3X15/VoxelSim,RavenB/opensim,ft-/opensim-optimizations-wip-tests,bravelittlescientist/opensim-performance,TomDataworks/opensim,cdbean/CySim,rryk/omp-server,TomDataworks/opensim,rryk/omp-server,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,TomDataworks/opensim,ft-/arribasim-dev-tests,N3X15/VoxelSim,ft-/opensim-optimizations-wip-tests,AlexRa/opensim-mods-Alex,RavenB/opensim,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,BogusCurry/arribasim-dev,ft-/arribasim-dev-tests,N3X15/VoxelSim,TomDataworks/opensim,rryk/omp-server,QuillLittlefeather/opensim-1,TechplexEngineer/Aurora-Sim,M-O-S-E-S/opensim,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,bravelittlescientist/opensim-performance,allquixotic/opensim-autobackup,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TechplexEngineer/Aurora-Sim,ft-/opensim-optimizations-wip-extras,BogusCurry/arribasim-dev,N3X15/VoxelSim,BogusCurry/arribasim-dev,AlexRa/opensim-mods-Alex,Michelle-Argus/ArribasimExtract,AlphaStaxLLC/taiga,AlexRa/opensim-mods-Alex,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip,justinccdev/opensim,OpenSimian/opensimulator,rryk/omp-server,RavenB/opensim,N3X15/VoxelSim,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,OpenSimian/opensimulator,BogusCurry/arribasim-dev,TechplexEngineer/Aurora-Sim,OpenSimian/opensimulator
OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs
OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class UuidGathererTests { protected UuidGatherer m_ug; [SetUp] public void Init() { m_ug = new UuidGatherer(new TestAssetService()); } /// <summary> /// Test requests made for non-existent assets /// </summary> [Test] public void TestMissingAsset() { TestHelper.InMethod(); UUID missingAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); IDictionary<UUID, int> foundAssetUuids = new Dictionary<UUID, int>(); m_ug.GatherAssetUuids(missingAssetUuid, AssetType.Object, foundAssetUuids); // We count the uuid as gathered even if the asset itself is missing. Assert.That(foundAssetUuids.Count, Is.EqualTo(1)); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class UuidGathererTests { /// <summary> /// Test requests made for non-existent assets /// </summary> [Test] public void TestMissingAsset() { TestHelper.InMethod(); UUID missingAssetUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); UuidGatherer ug = new UuidGatherer(new TestAssetService()); IDictionary<UUID, int> foundAssetUuids = new Dictionary<UUID, int>(); ug.GatherAssetUuids(missingAssetUuid, AssetType.Object, foundAssetUuids); // We count the uuid as gathered even if the asset itself is missing. Assert.That(foundAssetUuids.Count, Is.EqualTo(1)); } } }
bsd-3-clause
C#
3aacfd1c5e339f811c31a3970c9b2e3e0b0a5ac2
Rename and make the PastaPricer first acceptance test more readable.
dupdob/Michonne,dupdob/Michonne,dupdob/Michonne
PastaPricer.Tests/Acceptance/PastaPricerAcceptanceTests.cs
PastaPricer.Tests/Acceptance/PastaPricerAcceptanceTests.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PastaPricerAcceptanceTests.cs" company="No lock... no deadlock" product="Michonne"> // Copyright 2014 Cyrille DUPUYDAUBY (@Cyrdup), Thomas PIERRAIN (@tpierrain) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace PastaPricer.Tests.Acceptance { using NSubstitute; using NUnit.Framework; [TestFixture] public class PastaPricerAcceptanceTests { [Test] public void Should_Publish_Pasta_Price_Once_Started_And_When_MarketData_Is_Available() { // Mock and dependencies setup var publisher = Substitute.For<IPastaPricerPublisher>(); var marketDataProvider = new MarketDataProvider(); var pastaPricer = new PastaPricerEngine(marketDataProvider, publisher); CheckThatNoPriceHasBeenPublished(publisher); pastaPricer.Start(); CheckThatNoPriceHasBeenPublished(publisher); // Turns on market data marketDataProvider.Start(); // It has publish a price now! publisher.ReceivedWithAnyArgs().Publish(string.Empty, 0); } private static void CheckThatNoPriceHasBeenPublished(IPastaPricerPublisher publisher) { publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PastaPricerAcceptanceTests.cs" company="No lock... no deadlock" product="Michonne"> // Copyright 2014 Cyrille DUPUYDAUBY (@Cyrdup), Thomas PIERRAIN (@tpierrain) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace PastaPricer.Tests.Acceptance { using NSubstitute; using NUnit.Framework; [TestFixture] public class PastaPricerAcceptanceTests { [Test] public void Should_Publish_Pasta_Price_Once_Started_And_MarketData_Is_Available() { // Mocks instantiation var publisher = Substitute.For<IPastaPricerPublisher>(); var marketDataProvider = new MarketDataProvider(); var pastaPricer = new PastaPricerEngine(marketDataProvider, publisher); publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0); pastaPricer.Start(); publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0); marketDataProvider.Start(); // It publishes! publisher.ReceivedWithAnyArgs().Publish(string.Empty, 0); } } }
apache-2.0
C#
4777417f9b9546cebe7513e42fefdeccaed6f378
Add Easter monday to Lithuania
tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date
Nager.Date/PublicHolidays/LithuaniaProvider.cs
Nager.Date/PublicHolidays/LithuaniaProvider.cs
using Nager.Date.Model; using System.Collections.Generic; using System.Linq; namespace Nager.Date.PublicHolidays { public class LithuaniaProvider : CatholicBaseProvider { public override IEnumerable<PublicHoliday> Get(int year) { //Lithuania //https://en.wikipedia.org/wiki/Public_holidays_in_Lithuania var countryCode = CountryCode.LT; var easterSunday = base.EasterSunday(year); var items = new List<PublicHoliday>(); items.Add(new PublicHoliday(year, 1, 1, "Naujieji metai", "New Year's Day", countryCode)); items.Add(new PublicHoliday(year, 2, 16, "Lietuvos valstybės atkūrimo diena", "The Day of Restoration of the State of Lithuania", countryCode)); items.Add(new PublicHoliday(year, 3, 11, "Lietuvos nepriklausomybės atkūrimo diena", "Day of Restoration of Independence of Lithuania", countryCode)); items.Add(new PublicHoliday(easterSunday, "Velykos", "Easter Sunday", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(1), "Antroji Velykų diena", "Easter Monday", countryCode)); items.Add(new PublicHoliday(year, 5, 1, "Tarptautinė darbo diena", "International Working Day", countryCode)); items.Add(new PublicHoliday(year, 6, 24, "Joninės, Rasos", "St. John's Day", countryCode)); items.Add(new PublicHoliday(year, 7, 6, "Valstybės diena", "Statehood Day", countryCode)); items.Add(new PublicHoliday(year, 8, 15, "Žolinė", "Assumption Day", countryCode)); items.Add(new PublicHoliday(year, 11, 1, "Visų šventųjų diena", "All Saints' Day", countryCode)); items.Add(new PublicHoliday(year, 12, 24, "Šv. Kūčios", "Christmas Eve", countryCode)); items.Add(new PublicHoliday(year, 12, 25, "Šv. Kalėdos", "Christmas Day", countryCode)); items.Add(new PublicHoliday(year, 12, 26, "Šv. Kalėdos", "St. Stephen's Day", countryCode)); return items.OrderBy(o => o.Date); } } }
using Nager.Date.Model; using System.Collections.Generic; using System.Linq; namespace Nager.Date.PublicHolidays { public class LithuaniaProvider : CatholicBaseProvider { public override IEnumerable<PublicHoliday> Get(int year) { //Lithuania //https://en.wikipedia.org/wiki/Public_holidays_in_Lithuania var countryCode = CountryCode.LT; var easterSunday = base.EasterSunday(year); var items = new List<PublicHoliday>(); items.Add(new PublicHoliday(year, 1, 1, "Naujieji metai", "New Year's Day", countryCode)); items.Add(new PublicHoliday(year, 2, 16, "Lietuvos valstybės atkūrimo diena", "The Day of Restoration of the State of Lithuania", countryCode)); items.Add(new PublicHoliday(year, 3, 11, "Lietuvos nepriklausomybės atkūrimo diena", "Day of Restoration of Independence of Lithuania", countryCode)); items.Add(new PublicHoliday(easterSunday, "Velykos", "Easter Sunday", countryCode)); items.Add(new PublicHoliday(year, 5, 1, "Tarptautinė darbo diena", "International Working Day", countryCode)); items.Add(new PublicHoliday(year, 6, 24, "Joninės, Rasos", "St. John's Day", countryCode)); items.Add(new PublicHoliday(year, 7, 6, "Valstybės diena", "Statehood Day", countryCode)); items.Add(new PublicHoliday(year, 8, 15, "Žolinė", "Assumption Day", countryCode)); items.Add(new PublicHoliday(year, 11, 1, "Visų šventųjų diena", "All Saints' Day", countryCode)); items.Add(new PublicHoliday(year, 12, 24, "Šv. Kūčios", "Christmas Eve", countryCode)); items.Add(new PublicHoliday(year, 12, 25, "Šv. Kalėdos", "Christmas Day", countryCode)); items.Add(new PublicHoliday(year, 12, 26, "Šv. Kalėdos", "St. Stephen's Day", countryCode)); return items.OrderBy(o => o.Date); } } }
mit
C#
44986c4c4bbcd53de56af53f8576f47846050d82
Update location of stakepool API (#312)
decred/Paymetheus,jrick/Paymetheus
Paymetheus.StakePoolIntegration/PoolListApi.cs
Paymetheus.StakePoolIntegration/PoolListApi.cs
// Copyright (c) 2016 The Decred developers // Licensed under the ISC license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace Paymetheus.StakePoolIntegration { public static class PoolListApi { private static readonly Uri StakePoolInfoUri = new Uri("https://api.decred.org/?c=gsd"); public static async Task<Dictionary<string, StakePoolInfo>> QueryStakePoolInfoAsync(HttpClient client, JsonSerializer serializer) { if (client == null) throw new ArgumentNullException(nameof(client)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); using (var stream = await client.GetStreamAsync(StakePoolInfoUri)) using (var jsonReader = new JsonTextReader(new StreamReader(stream))) { return serializer.Deserialize<Dictionary<string, StakePoolInfo>>(jsonReader); } } } }
// Copyright (c) 2016 The Decred developers // Licensed under the ISC license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace Paymetheus.StakePoolIntegration { public static class PoolListApi { private static readonly Uri StakePoolInfoUri = new Uri("https://decred.org/api/?c=gsd"); public static async Task<Dictionary<string, StakePoolInfo>> QueryStakePoolInfoAsync(HttpClient client, JsonSerializer serializer) { if (client == null) throw new ArgumentNullException(nameof(client)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); using (var stream = await client.GetStreamAsync(StakePoolInfoUri)) using (var jsonReader = new JsonTextReader(new StreamReader(stream))) { return serializer.Deserialize<Dictionary<string, StakePoolInfo>>(jsonReader); } } } }
isc
C#
5d80d5908183c42c62a84edfe2d26bfafa2a2752
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.LastVisitedPidlMRU/ValuesOut.cs
RegistryPlugin.LastVisitedPidlMRU/ValuesOut.cs
using System; using System.IO; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.LastVisitedPidlMRU { public class ValuesOut:IValueOut { public ValuesOut(string ext, string absolutePath, string details, string valueName, int mruPosition, DateTimeOffset? openedOn) { Executable = ext; AbsolutePath = absolutePath; Details = details; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string ValueName { get; } public int MruPosition { get; } public string Executable { get; } public string AbsolutePath { get; } public DateTime? OpenedOn { get; } public string Details { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Exe: {Executable} Folder: {Executable} Absolute path: {AbsolutePath}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 => $"MRU: {MruPosition} Details: {Details}"; } }
using System; using System.IO; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.LastVisitedPidlMRU { public class ValuesOut:IValueOut { public ValuesOut(string ext, string absolutePath, string details, string valueName, int mruPosition, DateTimeOffset? openedOn) { Executable = ext; AbsolutePath = absolutePath; Details = details; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string ValueName { get; } public int MruPosition { get; } public string Executable { get; } public string AbsolutePath { get; } public DateTime? OpenedOn { get; } public string Details { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Exe: {Executable} Folder: {Executable} Absolute path: {AbsolutePath}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 => $"Mru: {MruPosition} Details: {Details}" ; } }
mit
C#
9a736daec74f96fecd168044cc370833cb985e80
Add another unit test for an MSBuild project (currently failing)
OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn
tests/OmniSharp.MSBuild.Tests/ProjectFileInfoTests.cs
tests/OmniSharp.MSBuild.Tests/ProjectFileInfoTests.cs
using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.MSBuild.ProjectFile; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.MSBuild.Tests { public class ProjectFileInfoTests { private readonly TestAssets _testAssets; private readonly ILogger _logger; public ProjectFileInfoTests(ITestOutputHelper output) { this._testAssets = TestAssets.Instance; this._logger = new TestLogger(output); MSBuildEnvironment.Initialize(this._logger); } [Fact] public void HelloWorld_has_correct_property_values() { var projectFolder = _testAssets.GetTestProjectFolder("HelloWorld"); var projectFilePath = Path.Combine(projectFolder, "HelloWorld.csproj"); var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger); Assert.NotNull(projectFileInfo); Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath); Assert.Equal(1, projectFileInfo.TargetFrameworks.Count); Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName); } [Fact] public void NetStandardAndNetCoreApp_has_correct_property_values() { var projectFolder = _testAssets.GetTestProjectFolder("NetStandardAndNetCoreApp"); var projectFilePath = Path.Combine(projectFolder, "NetStandardAndNetCoreApp.csproj"); var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger); Assert.NotNull(projectFileInfo); Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath); Assert.Equal(1, projectFileInfo.TargetFrameworks.Count); Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName); } } }
using System.IO; using Microsoft.Extensions.Logging; using OmniSharp.MSBuild.ProjectFile; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.MSBuild.Tests { public class ProjectFileInfoTests { private readonly TestAssets _testAssets; private readonly ILogger _logger; public ProjectFileInfoTests(ITestOutputHelper output) { this._testAssets = TestAssets.Instance; this._logger = new TestLogger(output); MSBuildEnvironment.Initialize(this._logger); } [Fact] public void Hello_world_has_correct_property_values() { var projectFolder = _testAssets.GetTestProjectFolder("HelloWorld"); var projectFilePath = Path.Combine(projectFolder, "HelloWorld.csproj"); var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger); Assert.NotNull(projectFileInfo); Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath); Assert.Equal(1, projectFileInfo.TargetFrameworks.Count); Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName); } } }
mit
C#
380058a4bd80ff92687eb1a823c25bc247ac9b93
Fix merge conflict (with + refactoring)
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/WithExpression.cs
csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/WithExpression.cs
using Microsoft.CodeAnalysis.CSharp.Syntax; using Semmle.Extraction.Kinds; using System.IO; namespace Semmle.Extraction.CSharp.Entities.Expressions { internal class WithExpression : Expression<WithExpressionSyntax> { private WithExpression(ExpressionNodeInfo info) : base(info.SetKind(ExprKind.WITH)) { } public static Expression Create(ExpressionNodeInfo info) => new WithExpression(info).TryPopulate(); protected override void PopulateExpression(TextWriter trapFile) { Create(Context, Syntax.Expression, this, 0); ObjectInitializer.Create(new ExpressionNodeInfo(Context, Syntax.Initializer, this, 1).SetType(Type)); } } }
using Microsoft.CodeAnalysis.CSharp.Syntax; using Semmle.Extraction.Kinds; using System.IO; namespace Semmle.Extraction.CSharp.Entities.Expressions { internal class WithExpression : Expression<WithExpressionSyntax> { private WithExpression(ExpressionNodeInfo info) : base(info.SetKind(ExprKind.WITH)) { } public static Expression Create(ExpressionNodeInfo info) => new WithExpression(info).TryPopulate(); protected override void PopulateExpression(TextWriter trapFile) { Create(cx, Syntax.Expression, this, 0); ObjectInitializer.Create(new ExpressionNodeInfo(cx, Syntax.Initializer, this, 1).SetType(Type)); } } }
mit
C#
ea54a9c9988aa6f05da16f36aa5835acb74c4466
Use FileOptions.DeleteOnClose instead of complex disposal pattern.
jherby2k/AudioWorks
AudioWorks/src/AudioWorks.Extensions/TempFileStream.cs
AudioWorks/src/AudioWorks.Extensions/TempFileStream.cs
using System.IO; using JetBrains.Annotations; namespace AudioWorks.Extensions { /// <summary> /// Wraps a temporary file. Suitable as a <see cref="MemoryStream"/> replacement for large data sets. /// </summary> /// <seealso cref="Stream" /> public sealed class TempFileStream : Stream { [NotNull] readonly FileStream _fileStream = File.Create(Path.GetTempFileName(), 4096, FileOptions.DeleteOnClose); /// <inheritdoc/> public override void Flush() => _fileStream.Flush(); /// <inheritdoc/> public override int Read(byte[] buffer, int offset, int count) => _fileStream.Read(buffer, offset, count); /// <inheritdoc/> public override long Seek(long offset, SeekOrigin origin) => _fileStream.Seek(offset, origin); /// <inheritdoc/> public override void SetLength(long value) => _fileStream.SetLength(value); /// <inheritdoc/> public override void Write(byte[] buffer, int offset, int count) => _fileStream.Write(buffer, offset, count); /// <inheritdoc/> public override bool CanRead => _fileStream.CanRead; /// <inheritdoc/> public override bool CanSeek => _fileStream.CanSeek; /// <inheritdoc/> public override bool CanWrite => _fileStream.CanWrite; /// <inheritdoc/> public override long Length => _fileStream.Length; /// <inheritdoc/> public override long Position { get => _fileStream.Position; set => _fileStream.Position = value; } /// <inheritdoc/> protected override void Dispose(bool disposing) { if (disposing) _fileStream.Dispose(); base.Dispose(disposing); } } }
using System; using System.IO; namespace AudioWorks.Extensions { /// <summary> /// Wraps a temporary file. Suitable as a <see cref="MemoryStream"/> replacement for large data sets. /// </summary> /// <seealso cref="Stream" /> public sealed class TempFileStream : Stream { readonly FileStream _fileStream = File.Open(Path.GetTempFileName(), FileMode.Truncate); /// <inheritdoc/> public override void Flush() => _fileStream.Flush(); /// <inheritdoc/> public override int Read(byte[] buffer, int offset, int count) => _fileStream.Read(buffer, offset, count); /// <inheritdoc/> public override long Seek(long offset, SeekOrigin origin) => _fileStream.Seek(offset, origin); /// <inheritdoc/> public override void SetLength(long value) => _fileStream.SetLength(value); /// <inheritdoc/> public override void Write(byte[] buffer, int offset, int count) => _fileStream.Write(buffer, offset, count); /// <inheritdoc/> public override bool CanRead => _fileStream.CanRead; /// <inheritdoc/> public override bool CanSeek => _fileStream.CanSeek; /// <inheritdoc/> public override bool CanWrite => _fileStream.CanWrite; /// <inheritdoc/> public override long Length => _fileStream.Length; /// <inheritdoc/> public override long Position { get => _fileStream.Position; set => _fileStream.Position = value; } /// <inheritdoc/> protected override void Dispose(bool disposing) { try { var fileName = _fileStream.Name; if (disposing) _fileStream.Dispose(); File.Delete(fileName); } catch (Exception) { // Ignore any errors during disposal } base.Dispose(disposing); } } }
agpl-3.0
C#
7ad927bdaf61fee797c1ba347f6cce119ee978d8
Use CreateSingleTickTimer in TweetScreenshotManager
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Core/Notification/Screenshot/TweetScreenshotManager.cs
Core/Notification/Screenshot/TweetScreenshotManager.cs
using System; using System.Drawing; using System.Windows.Forms; using TweetDck.Core.Controls; using TweetDck.Core.Utils; namespace TweetDck.Core.Notification.Screenshot{ sealed class TweetScreenshotManager : IDisposable{ private readonly FormBrowser browser; private readonly FormNotificationScreenshotable screenshot; private readonly Timer timeout; public TweetScreenshotManager(FormBrowser browser){ this.browser = browser; this.screenshot = new FormNotificationScreenshotable(browser, NotificationFlags.DisableScripts | NotificationFlags.DisableContextMenu | NotificationFlags.TopMost){ CanMoveWindow = () => false }; this.screenshot.PrepareNotificationForScreenshot(Callback); this.timeout = WindowsUtils.CreateSingleTickTimer(10000); this.timeout.Tick += (sender, args) => screenshot.Reset(); } public void Trigger(string html, int width, int height){ screenshot.LoadNotificationForScreenshot(new TweetNotification(html, string.Empty, 0), width, height); screenshot.Show(); timeout.Start(); } private void Callback(){ if (!timeout.Enabled){ return; } timeout.Stop(); FormNotification notification = browser.BrowserNotificationForm; Point? prevNotificationLocation = null; bool prevFreezeTimer = false; if (notification.IsNotificationVisible){ prevNotificationLocation = notification.Location; prevFreezeTimer = notification.FreezeTimer; notification.Location = ControlExtensions.InvisibleLocation; notification.FreezeTimer = true; } screenshot.TakeScreenshotAndHide(); if (prevNotificationLocation.HasValue){ notification.Location = prevNotificationLocation.Value; notification.FreezeTimer = prevFreezeTimer; } } public void Dispose(){ timeout.Dispose(); screenshot.Dispose(); } } }
using System; using System.Drawing; using System.Windows.Forms; using TweetDck.Core.Controls; namespace TweetDck.Core.Notification.Screenshot{ sealed class TweetScreenshotManager : IDisposable{ private readonly FormBrowser browser; private readonly FormNotificationScreenshotable screenshot; private readonly Timer timeout; public TweetScreenshotManager(FormBrowser browser){ this.browser = browser; this.timeout = new Timer{ Interval = 10000 }; this.timeout.Tick += safetyTimer_Tick; this.screenshot = new FormNotificationScreenshotable(browser, NotificationFlags.DisableScripts | NotificationFlags.DisableContextMenu | NotificationFlags.TopMost){ CanMoveWindow = () => false }; this.screenshot.PrepareNotificationForScreenshot(Callback); } public void Trigger(string html, int width, int height){ screenshot.LoadNotificationForScreenshot(new TweetNotification(html, string.Empty, 0), width, height); screenshot.Show(); timeout.Start(); } private void Callback(){ if (!timeout.Enabled){ return; } timeout.Stop(); FormNotification notification = browser.BrowserNotificationForm; Point? prevNotificationLocation = null; bool prevFreezeTimer = false; if (notification.IsNotificationVisible){ prevNotificationLocation = notification.Location; prevFreezeTimer = notification.FreezeTimer; notification.Location = ControlExtensions.InvisibleLocation; notification.FreezeTimer = true; } screenshot.TakeScreenshotAndHide(); if (prevNotificationLocation.HasValue){ notification.Location = prevNotificationLocation.Value; notification.FreezeTimer = prevFreezeTimer; } } private void safetyTimer_Tick(object sender, EventArgs e){ timeout.Stop(); screenshot.Reset(); } public void Dispose(){ timeout.Dispose(); screenshot.Dispose(); } } }
mit
C#
71d63776543fa1b21fa0181f50926b7251a8f585
Update InsertPictureCellReference.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Articles/InsertPictureCellReference.cs
Examples/CSharp/Articles/InsertPictureCellReference.cs
using System.IO; using Aspose.Cells; using Aspose.Cells.Drawing; namespace Aspose.Cells.Examples.Articles { public class InsertPictureCellReference { public static void Main() { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate a new Workbook Workbook workbook = new Workbook(); //Get the first worksheet's cells collection Cells cells = workbook.Worksheets[0].Cells; //Add string values to the cells cells["A1"].PutValue("A1"); cells["C10"].PutValue("C10"); //Add a blank picture to the D1 cell Picture pic = (Picture)workbook.Worksheets[0].Shapes.AddPicture(0, 3, 10, 6, null); //Specify the formula that refers to the source range of cells pic.Formula = "A1:C10"; //Update the shapes selected value in the worksheet workbook.Worksheets[0].Shapes.UpdateSelectedValue(); //Save the Excel file. workbook.Save(dataDir+ "referencedpicture.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using Aspose.Cells.Drawing; namespace Aspose.Cells.Examples.Articles { public class InsertPictureCellReference { public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate a new Workbook Workbook workbook = new Workbook(); //Get the first worksheet's cells collection Cells cells = workbook.Worksheets[0].Cells; //Add string values to the cells cells["A1"].PutValue("A1"); cells["C10"].PutValue("C10"); //Add a blank picture to the D1 cell Picture pic = (Picture)workbook.Worksheets[0].Shapes.AddPicture(0, 3, 10, 6, null); //Specify the formula that refers to the source range of cells pic.Formula = "A1:C10"; //Update the shapes selected value in the worksheet workbook.Worksheets[0].Shapes.UpdateSelectedValue(); //Save the Excel file. workbook.Save(dataDir+ "referencedpicture.out.xlsx"); } } }
mit
C#