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 |
|---|---|---|---|---|---|---|---|---|
15535b323a6ab2ddf39622eec0dde9b51da97707
|
Use StaticCompositeResolver instead of CompositeResolver.
|
neuecc/MagicOnion
|
samples/ChatApp/ChatApp.Unity/Assets/Scripts/InitialSettings.cs
|
samples/ChatApp/ChatApp.Unity/Assets/Scripts/InitialSettings.cs
|
using MessagePack;
using MessagePack.Resolvers;
using UnityEngine;
namespace Assets.Scripts
{
class InitialSettings
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void RegisterResolvers()
{
// NOTE: Currently, CompositeResolver doesn't work on Unity IL2CPP build. Use StaticCompositeResolver instead of it.
StaticCompositeResolver.Instance.Register(
MagicOnion.Resolvers.MagicOnionResolver.Instance,
MessagePack.Resolvers.GeneratedResolver.Instance,
BuiltinResolver.Instance,
PrimitiveObjectResolver.Instance
);
MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions
.WithResolver(StaticCompositeResolver.Instance);
}
}
}
|
using MessagePack;
using MessagePack.Resolvers;
using UnityEngine;
namespace Assets.Scripts
{
class InitialSettings
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void RegisterResolvers()
{
MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions
.WithResolver(
CompositeResolver.Create(
MagicOnion.Resolvers.MagicOnionResolver.Instance,
MessagePack.Resolvers.GeneratedResolver.Instance,
BuiltinResolver.Instance,
PrimitiveObjectResolver.Instance
)
);
}
}
}
|
mit
|
C#
|
fc46f6188c4a4262231622e0560eeddf85a69b15
|
Update EmailConnectionInfo.cs
|
chrisbrain/serilog-sinks-email,serilog/serilog-sinks-email,chrisbrain/serilog-sinks-email
|
src/Serilog.Sinks.Email/Sinks/Email/EmailConnectionInfo.cs
|
src/Serilog.Sinks.Email/Sinks/Email/EmailConnectionInfo.cs
|
// Copyright 2014 Serilog Contributors
//
// 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.ComponentModel;
using System.Net;
namespace Serilog.Sinks.Email
{
/// <summary>
/// Connection information for use by the Email sink.
/// </summary>
public class EmailConnectionInfo
{
/// <summary>
/// The default port used by for SMTP transfer.
/// </summary>
const int DefaultPort = 25;
/// <summary>
/// The default subject used for email messages.
/// </summary>
const string DefaultSubject = "Log Email";
/// <summary>
/// Constructs the <see cref="EmailConnectionInfo"/> with the default port and default email subject set.
/// </summary>
public EmailConnectionInfo()
{
Port = DefaultPort;
EmailSubject = DefaultSubject;
IsBodyHtml = false;
}
/// <summary>
/// Gets or sets the credentials used for authentication.
/// </summary>
public ICredentialsByHost NetworkCredentials { get; set; }
/// <summary>
/// Gets or sets the port used for the connection.
/// Default value is 25.
/// </summary>
[DefaultValue(DefaultPort)]
public int Port { get; set; }
/// <summary>
/// The email address emails will be sent from.
/// </summary>
public string FromEmail { get; set; }
/// <summary>
/// The email address(es) emails will be sent to. Accepts multiple email addresses separated by comma or semicolon.
/// </summary>
public string ToEmail { get; set; }
/// <summary>
/// The subject to use for the email.
/// </summary>
[DefaultValue(DefaultSubject)]
public string EmailSubject { get; set; }
/// <summary>
/// Flag as true to use SSL in the SMTP client.
/// </summary>
public bool EnableSsl { get; set; }
/// <summary>
/// The SMTP email server to use.
/// </summary>
public string MailServer { get; set; }
/// <summary>
/// Sets whether the body contents of the email is HTML. Defaults to false.
/// </summary>
public bool IsBodyHtml { get; set; }
}
}
|
// Copyright 2014 Serilog Contributors
//
// 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.ComponentModel;
using System.Net;
namespace Serilog.Sinks.Email
{
/// <summary>
/// Connection information for use by the Email sink.
/// </summary>
public class EmailConnectionInfo
{
/// <summary>
/// The default port used by for SMTP transfer.
/// </summary>
const int DefaultPort = 25;
/// <summary>
/// The default subject used for email messages.
/// </summary>
const string DefaultSubject = "Log Email";
/// <summary>
/// Constructs the <see cref="EmailConnectionInfo"/> with the default port and default email subject set.
/// </summary>
public EmailConnectionInfo()
{
Port = DefaultPort;
EmailSubject = DefaultSubject;
}
/// <summary>
/// Gets or sets the credentials used for authentication.
/// </summary>
public ICredentialsByHost NetworkCredentials { get; set; }
/// <summary>
/// Gets or sets the port used for the connection.
/// Default value is 25.
/// </summary>
[DefaultValue(DefaultPort)]
public int Port { get; set; }
/// <summary>
/// The email address emails will be sent from.
/// </summary>
public string FromEmail { get; set; }
/// <summary>
/// The email address(es) emails will be sent to. Accepts multiple email addresses separated by comma or semicolon.
/// </summary>
public string ToEmail { get; set; }
/// <summary>
/// The subject to use for the email.
/// </summary>
[DefaultValue(DefaultSubject)]
public string EmailSubject { get; set; }
/// <summary>
/// Flag as true to use SSL in the SMTP client.
/// </summary>
public bool EnableSsl { get; set; }
/// <summary>
/// The SMTP email server to use.
/// </summary>
public string MailServer { get; set; }
}
}
|
apache-2.0
|
C#
|
1359235df373f22d92ea1d500180257266a9fd20
|
remove build warning
|
yanggujun/commonsfornet,yanggujun/commonsfornet
|
src/Commons.Collections/Collection/IndexedCollection.cs
|
src/Commons.Collections/Collection/IndexedCollection.cs
|
// Copyright CommonsForNET. Author: Gujun Yang. email: gujun.yang@gmail.com
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Commons.Collections.Map;
using Commons.Collections.Common;
namespace Commons.Collections.Collection
{
/// <summary>
/// The IndexedCollection provides a map like view on a collection. Other than specifying the key and value explicitly,
/// the indexed collection generates the key from the value added to itself. How the key is generated is defined by
/// the client with a delegate.
/// The inside map is a (key)-(collection of the value) pair.
/// When unique index is false, items which generate the same key are added to a collection in the IMultiMap dictionary.
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
[CLSCompliant(true)]
public class IndexedCollection<K, V> : AbstractCollectionDecorator<V>
{
private readonly IMultiMap<K, V> map;
private readonly Transformer<V, K> transform;
public IndexedCollection(ICollection<V> valueCollection, Transformer<V, K> transform) : base(valueCollection)
{
this.transform = transform;
}
public IndexedCollection(ICollection<V> valueCollection, IMultiMap<K, V> map, Transformer<V, K> transform)
: base(valueCollection)
{
this.transform = transform;
this.map = map;
}
}
}
|
// Copyright CommonsForNET. Author: Gujun Yang. email: gujun.yang@gmail.com
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Commons.Collections.Map;
using Commons.Collections.Common;
namespace Commons.Collections.Collection
{
/// <summary>
/// The IndexedCollection provides a map like view on a collection. Other than specifying the key and value explicitly,
/// the indexed collection generates the key from the value added to itself. How the key is generated is defined by
/// the client with a delegate.
/// The inside map is a (key)-(collection of the value) pair.
/// When unique index is false, items which generate the same key are added to a collection in the IMultiMap dictionary.
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
[CLSCompliant(true)]
public class IndexedCollection<K, V> : AbstractCollectionDecorator<V>
{
private readonly IMultiMap<K, V> map;
private readonly Transformer<V, K> transform;
public IndexedCollection(ICollection<V> collection, Transformer<V, K> transform) : base(collection)
{
this.transform = transform;
}
}
}
|
apache-2.0
|
C#
|
444b7ebfb9292eefc524456614f47d15033bfa70
|
bump version number
|
mruhul/Bolt.Common.Extensions
|
src/Bolt.Common.Extensions/Properties/AssemblyInfo.cs
|
src/Bolt.Common.Extensions/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("Bolt.Common.Extensions")]
[assembly: AssemblyDescription("Common used extension methods")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mohammad Ruhul Amin")]
[assembly: AssemblyProduct("Bolt.Common.Extensions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2619104c-61d8-4dde-868c-dee0eb13379a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Bolt.Common.Extensions")]
[assembly: AssemblyDescription("Common used extension methods")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mohammad Ruhul Amin")]
[assembly: AssemblyProduct("Bolt.Common.Extensions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2619104c-61d8-4dde-868c-dee0eb13379a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
|
mit
|
C#
|
cd5cd0cf64ce24f3e4b9328e4c9f5604641fd2fc
|
Replace Create factory methods with constructors - CCCallFuncO
|
hig-ag/CocosSharp,haithemaraissia/CocosSharp,mono/CocosSharp,TukekeSoft/CocosSharp,hig-ag/CocosSharp,netonjm/CocosSharp,haithemaraissia/CocosSharp,mono/cocos2d-xna,netonjm/CocosSharp,mono/CocosSharp,mono/cocos2d-xna,zmaruo/CocosSharp,MSylvia/CocosSharp,zmaruo/CocosSharp,MSylvia/CocosSharp,TukekeSoft/CocosSharp
|
cocos2d/actions/action_instants/callfunc/CCCallFuncO.cs
|
cocos2d/actions/action_instants/callfunc/CCCallFuncO.cs
|
namespace cocos2d
{
public class CCCallFuncO : CCCallFunc
{
private SEL_CallFuncO m_pCallFuncO;
private object m_pObject;
public CCCallFuncO()
{
m_pObject = null;
m_pCallFuncO = null;
}
public CCCallFuncO (SEL_CallFuncO selector, object pObject) : this()
{
InitWithTarget(selector, pObject);
}
protected CCCallFuncO (CCCallFuncO callFuncO) : base (callFuncO)
{
InitWithTarget(callFuncO.m_pCallFuncO, callFuncO.m_pObject);
}
public bool InitWithTarget(SEL_CallFuncO selector, object pObject)
{
m_pObject = pObject;
m_pCallFuncO = selector;
return true;
}
// super methods
public override object Copy(ICopyable zone)
{
if (zone != null)
{
//in case of being called at sub class
var pRet = (CCCallFuncO) (zone);
base.Copy(zone);
pRet.InitWithTarget(m_pCallFuncO, m_pObject);
return pRet;
}
else
{
return new CCCallFuncO(this);
}
}
public override void Execute()
{
if (null != m_pCallFuncO)
{
m_pCallFuncO(m_pObject);
}
//if (CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()) {
// CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeCallFunc0(
// m_scriptFuncName.c_str(), m_pObject);
//}
}
public object Object
{
get { return m_pObject; }
set { m_pObject = value; }
}
}
}
|
namespace cocos2d
{
public class CCCallFuncO : CCCallFunc
{
private SEL_CallFuncO m_pCallFuncO;
private object m_pObject;
public CCCallFuncO()
{
m_pObject = null;
m_pCallFuncO = null;
}
public static CCCallFuncO Create(SEL_CallFuncO selector, object pObject)
{
var pRet = new CCCallFuncO();
pRet.InitWithTarget(selector, pObject);
return pRet;
}
public bool InitWithTarget(SEL_CallFuncO selector, object pObject)
{
m_pObject = pObject;
m_pCallFuncO = selector;
return true;
}
// super methods
public override object Copy(ICopyable zone)
{
CCCallFuncO pRet;
if (zone != null)
{
//in case of being called at sub class
pRet = (CCCallFuncO) (zone);
}
else
{
pRet = new CCCallFuncO();
zone = (pRet);
}
base.Copy(zone);
pRet.InitWithTarget(m_pCallFuncO, m_pObject);
return pRet;
}
public override void Execute()
{
if (null != m_pCallFuncO)
{
m_pCallFuncO(m_pObject);
}
//if (CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()) {
// CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeCallFunc0(
// m_scriptFuncName.c_str(), m_pObject);
//}
}
public object Object
{
get { return m_pObject; }
set { m_pObject = value; }
}
}
}
|
mit
|
C#
|
f8ac492699443cb0f3f4e6654d453000d9734fa5
|
Test YoloMigrationRunner
|
rapidcore/rapidcore,rapidcore/rapidcore
|
src/postgresql/test-functional/YoloMigrationRunnerTests.cs
|
src/postgresql/test-functional/YoloMigrationRunnerTests.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Dapper;
using functionaltests.Migrations;
using functionaltests.Migrations.TestMigrations;
using FakeItEasy;
using Microsoft.Extensions.DependencyInjection;
using RapidCore.Locking;
using Xunit;
using RapidCore.PostgreSql;
using RapidCore.PostgreSql.FunctionalTests;
namespace functionaltests
{
public class YoloMigrationRunnerTests : PostgreSqlMigrationTestBase
{
[Fact]
public async void RunMigrations_Works()
{
await DropMigrationInfoTable();
await PrepareCounterTable(new List<Counter> { new Counter { Id = 999, CounterValue = 12 } });
var db = GetDb();
var services = new ServiceCollection();
var runner = new YoloMigrationRunner(
services.BuildServiceProvider(),
"staging",
ConnectionString,
A.Fake<IDistributedAppLockProvider>(),
typeof(YoloMigrationRunnerTests).GetTypeInfo().Assembly
);
await runner.UpgradeAsync();
// are all the migrations marked as completed?
var migrationInfos = await GetAllMigrationInfo();
Assert.Contains(migrationInfos, x => x.Name == nameof(Migration01) && x.MigrationCompleted);
Assert.Contains(migrationInfos, x => x.Name == nameof(Migration02) && x.MigrationCompleted);
// check the state of the db
var counter999 = await db.QuerySingleAsync<Counter>("select * from __Counter where Id = 999");
Assert.Equal("sample default value", counter999.Description);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using RapidCore.PostgreSql;
namespace functionaltests
{
public class YoloMigrationRunnerTests
{
[Fact]
public async void RunMigrations_Works()
{
//var runner = new YoloMigrationRunner();
}
}
}
|
mit
|
C#
|
d779d17238b986157d269147261d694ca4389279
|
Set default for Beta channel to be false
|
adilmughal/OpenLiveWriter,randrey/OpenLiveWriter,Gordon-Beeming/OpenLiveWriter,Gordon-Beeming/OpenLiveWriter,hashhar/OpenLiveWriter,lisardggY/OpenLiveWriter,adilmughal/OpenLiveWriter,willduff/OpenLiveWriter-1,willduff/OpenLiveWriter-1,willduff/OpenLiveWriter-1,randrey/OpenLiveWriter,Gordon-Beeming/OpenLiveWriter,lisardggY/OpenLiveWriter,PeteKersker/OpenLiveWriter,PeteKersker/OpenLiveWriter,KirillOsenkov/OpenLiveWriter,PeteKersker/OpenLiveWriter,adilmughal/OpenLiveWriter,punker76/OpenLiveWriter,adilmughal/OpenLiveWriter,adilmughal/OpenLiveWriter,Gordon-Beeming/OpenLiveWriter,panjkov/OpenLiveWriter,MitchMilam/OpenLiveWriter,MitchMilam/OpenLiveWriter,panjkov/OpenLiveWriter,willduff/OpenLiveWriter-1,randrey/OpenLiveWriter,MitchMilam/OpenLiveWriter,hashhar/OpenLiveWriter,KirillOsenkov/OpenLiveWriter,hashhar/OpenLiveWriter,willduff/OpenLiveWriter-1,punker76/OpenLiveWriter,PeteKersker/OpenLiveWriter,lisardggY/OpenLiveWriter,hashhar/OpenLiveWriter,punker76/OpenLiveWriter,randrey/OpenLiveWriter,lisardggY/OpenLiveWriter,panjkov/OpenLiveWriter,randrey/OpenLiveWriter,Gordon-Beeming/OpenLiveWriter,PeteKersker/OpenLiveWriter,lisardggY/OpenLiveWriter,punker76/OpenLiveWriter,panjkov/OpenLiveWriter,panjkov/OpenLiveWriter,MitchMilam/OpenLiveWriter,punker76/OpenLiveWriter,KirillOsenkov/OpenLiveWriter,KirillOsenkov/OpenLiveWriter,hashhar/OpenLiveWriter,MitchMilam/OpenLiveWriter,KirillOsenkov/OpenLiveWriter
|
src/managed/OpenLiveWriter.PostEditor/Updates/UpdateSettings.cs
|
src/managed/OpenLiveWriter.PostEditor/Updates/UpdateSettings.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Text;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Settings;
namespace OpenLiveWriter.PostEditor.Updates
{
public class UpdateSettings
{
static UpdateSettings()
{
// Force these settings temporarily in case people already got defaults set.
BetaUpdateDownloadUrl = BETAUPDATEDOWNLOADURL;
}
public static bool AutoUpdate
{
get { return settings.GetBoolean(AUTOUPDATE, true); }
set { settings.SetBoolean(AUTOUPDATE, value); }
}
public static bool CheckForBetaUpdates
{
get { return settings.GetBoolean(CHECKFORBETAUPDATES, false); }
set { settings.SetBoolean(CHECKFORBETAUPDATES, value); }
}
public static string UpdateDownloadUrl
{
get { return settings.GetString(CHECKUPDATESURL, UPDATEDOWNLOADURL); }
set { settings.SetString(CHECKUPDATESURL, value); }
}
public static string BetaUpdateDownloadUrl
{
get { return settings.GetString(CHECKBETAUPDATESURL, BETAUPDATEDOWNLOADURL); }
set { settings.SetString(CHECKBETAUPDATESURL, value); }
}
private const string AUTOUPDATE = "AutoUpdate";
private const string CHECKFORBETAUPDATES = "CheckForBetaUpdates";
private const string CHECKUPDATESURL = "CheckUpdatesUrl";
private const string UPDATEDOWNLOADURL = "https://openlivewriter.azureedge.net/stable/Releases"; // Location of signed builds
private const string CHECKBETAUPDATESURL = "CheckBetaUpdatesUrl";
private const string BETAUPDATEDOWNLOADURL = "https://olw.blob.core.windows.net/nightly/Releases"; // Location of CI builds
private static readonly SettingsPersisterHelper settings = ApplicationEnvironment.UserSettingsRoot.GetSubSettings("Updates");
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Text;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Settings;
namespace OpenLiveWriter.PostEditor.Updates
{
public class UpdateSettings
{
static UpdateSettings()
{
// Force these settings temporarily in case people already got defaults set.
BetaUpdateDownloadUrl = BETAUPDATEDOWNLOADURL;
}
public static bool AutoUpdate
{
get { return settings.GetBoolean(AUTOUPDATE, true); }
set { settings.SetBoolean(AUTOUPDATE, value); }
}
public static bool CheckForBetaUpdates
{
get { return settings.GetBoolean(CHECKFORBETAUPDATES, true); }
set { settings.SetBoolean(CHECKFORBETAUPDATES, value); }
}
public static string UpdateDownloadUrl
{
get { return settings.GetString(CHECKUPDATESURL, UPDATEDOWNLOADURL); }
set { settings.SetString(CHECKUPDATESURL, value); }
}
public static string BetaUpdateDownloadUrl
{
get { return settings.GetString(CHECKBETAUPDATESURL, BETAUPDATEDOWNLOADURL); }
set { settings.SetString(CHECKBETAUPDATESURL, value); }
}
private const string AUTOUPDATE = "AutoUpdate";
private const string CHECKFORBETAUPDATES = "CheckForBetaUpdates";
private const string CHECKUPDATESURL = "CheckUpdatesUrl";
private const string UPDATEDOWNLOADURL = "https://openlivewriter.azureedge.net/stable/Releases"; // Location of signed builds
private const string CHECKBETAUPDATESURL = "CheckBetaUpdatesUrl";
private const string BETAUPDATEDOWNLOADURL = "https://olw.blob.core.windows.net/nightly/Releases"; // Location of CI builds
private static readonly SettingsPersisterHelper settings = ApplicationEnvironment.UserSettingsRoot.GetSubSettings("Updates");
}
}
|
mit
|
C#
|
3caafd6529827bf4256e61b61b56c973ae584e50
|
Change configurations to decimal value
|
takenet/blip-sdk-csharp
|
src/Take.Blip.Builder/Hosting/ConventionsConfiguration.cs
|
src/Take.Blip.Builder/Hosting/ConventionsConfiguration.cs
|
using System;
namespace Take.Blip.Builder.Hosting
{
public class ConventionsConfiguration : IConfiguration
{
public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1);
public virtual string RedisStorageConfiguration => "localhost";
public virtual int RedisDatabase => 0;
public virtual int MaxTransitionsByInput => 10;
public virtual int TraceQueueBoundedCapacity => 512;
public virtual int TraceQueueMaxDegreeOfParallelism => 512;
public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5);
public virtual string RedisKeyPrefix => "builder";
public bool ContactCacheEnabled => true;
public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30);
public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30);
public int ExecuteScriptLimitRecursion => 50;
public int ExecuteScriptMaxStatements => 1000;
public long ExecuteScriptLimitMemory => 1_000_000; // Nearly 1MB or 1 << 20
public long ExecuteScriptLimitMemoryWarning => 500_000; // Nearly 512KB or 1 << 19
public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5);
}
}
|
using System;
namespace Take.Blip.Builder.Hosting
{
public class ConventionsConfiguration : IConfiguration
{
public virtual TimeSpan InputProcessingTimeout => TimeSpan.FromMinutes(1);
public virtual string RedisStorageConfiguration => "localhost";
public virtual int RedisDatabase => 0;
public virtual int MaxTransitionsByInput => 10;
public virtual int TraceQueueBoundedCapacity => 512;
public virtual int TraceQueueMaxDegreeOfParallelism => 512;
public virtual TimeSpan TraceTimeout => TimeSpan.FromSeconds(5);
public virtual string RedisKeyPrefix => "builder";
public bool ContactCacheEnabled => true;
public virtual TimeSpan ContactCacheExpiration => TimeSpan.FromMinutes(30);
public virtual TimeSpan DefaultActionExecutionTimeout => TimeSpan.FromSeconds(30);
public int ExecuteScriptLimitRecursion => 50;
public int ExecuteScriptMaxStatements => 1000;
public long ExecuteScriptLimitMemory => 0x100000; // 1MiB or 1 << 20
public long ExecuteScriptLimitMemoryWarning => 0x80000; // 512KiB or 1 << 19
public TimeSpan ExecuteScriptTimeout => TimeSpan.FromSeconds(5);
}
}
|
apache-2.0
|
C#
|
d2d6b7cbf2a22921c61ca520c25bf5e04598e592
|
Fix small problem
|
aleksandra992/Team-work-Naga
|
Naga/FlappyBird/Obstacle.cs
|
Naga/FlappyBird/Obstacle.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlappyBird
{
class Obstacle
{
public int height;
public string[] upperPart = { " __________ ", "| |", "| |", " __________ " };
public int X, Y;
public Obstacle(int height, int X, int Y)
{
this.height = height;
this.X = X;
this.Y = Y;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlappyBird
{
class Obstacle//Andrey
{
public int height;
public string[] upperPart = { " __________ ", "| |", "| |", " __________ " };
public int X, Y;
public Obstacle(int height, int X, int Y)
{
this.height = height;
this.X = X;
this.Y = Y;
}
}
}
|
mit
|
C#
|
061c805ec1526513d8cf80342dce2ae253bc7a7e
|
Fix core live tests (#6175)
|
jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,stankovski/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,stankovski/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,hyonholee/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,markcowl/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net
|
sdk/core/Azure.Core/tests/samples/Sample1_HelloWorld.cs
|
sdk/core/Azure.Core/tests/samples/Sample1_HelloWorld.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using Azure.Core.Pipeline;
using NUnit.Framework;
using System;
using System.IO;
using System.Threading.Tasks;
namespace Azure.Core.Samples
{
[Category("Live")]
public partial class BaseSamples
{
[Test]
public async Task HelloWorld()
{
var pipeline = new HttpPipeline(new HttpClientTransport());
var request = pipeline.CreateRequest();
var uri = new Uri(@"https://raw.githubusercontent.com/Azure/azure-sdk-for-net/master/README.md");
request.SetRequestLine(HttpPipelineMethod.Get, uri);
request.Headers.Add("Host", uri.Host);
Response response = await pipeline.SendRequestAsync(request, cancellationToken: default).ConfigureAwait(false);
if (response.Status == 200) {
var reader = new StreamReader(response.ContentStream);
string responseText = reader.ReadToEnd();
}
else throw new RequestFailedException(response);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using Azure.Core.Pipeline;
using NUnit.Framework;
using System;
using System.IO;
using System.Threading.Tasks;
namespace Azure.Core.Samples
{
[Category("Live")]
public partial class BaseSamples
{
[Test]
public async Task HelloWorld()
{
var pipeline = new HttpPipeline(new HttpClientTransport());
var request = pipeline.CreateRequest();
var uri = new Uri(@"https://raw.githubusercontent.com/Azure/azure-sdk-for-net/master/src/SDKs/Azure.Core/data-plane/README.md");
request.SetRequestLine(HttpPipelineMethod.Get, uri);
request.Headers.Add("Host", uri.Host);
Response response = await pipeline.SendRequestAsync(request, cancellationToken: default).ConfigureAwait(false);
if (response.Status == 200) {
var reader = new StreamReader(response.ContentStream);
string responseText = reader.ReadToEnd();
}
else throw new RequestFailedException(response);
}
}
}
|
mit
|
C#
|
5a2ae03f264e6ac26e670ca69195f27827a0fb33
|
fix beatswitch observer
|
Dalet/140-speedrun-timer,Dalet/140-speedrun-timer,Dalet/140-speedrun-timer
|
140-speedrun-timer/GameObservers/BeatLayerSwitchObserver.cs
|
140-speedrun-timer/GameObservers/BeatLayerSwitchObserver.cs
|
using System.Linq;
using UnityEngine;
namespace SpeedrunTimerMod.GameObservers
{
[GameObserver]
class BeatLayerSwitchObserver : MonoBehaviour
{
MenuSystem _menuSystem;
BossGate _bossGate;
ColorSphere[] _beatSwitchColorSpheres;
void Awake()
{
var levelsFolder = GameObject.Find("Levels");
if (levelsFolder == null)
{
Debug.Log($"{nameof(BeatLayerSwitchObserver)}: Couldn't find Levels object");
Destroy(this);
return;
}
var menuSystemObj = GameObject.Find("_MenuSystem");
if (menuSystemObj != null)
_menuSystem = menuSystemObj.GetComponent<MenuSystem>();
else
Debug.Log($"{nameof(BeatLayerSwitchObserver)}: Couldn't find _MenuSystem object");
_bossGate = levelsFolder.GetComponentInChildren<BossGate>();
var beatswitches = levelsFolder.GetComponentsInChildren<BeatLayerSwitch>();
var colorSpheres = beatswitches.Select(b => b.colorSphere);
if (_menuSystem != null)
colorSpheres = colorSpheres.Where(c => c != _menuSystem.colorSphere);
_beatSwitchColorSpheres = colorSpheres.ToArray();
}
void OnEnable()
{
if (_beatSwitchColorSpheres != null)
{
foreach (var colorSphere in _beatSwitchColorSpheres)
colorSphere.colorSphereExpanding += OnColorSphereExpanding;
}
if (_menuSystem != null)
{
_menuSystem.colorSphere.colorSphereOpened += OnMenuKeyUsed;
_menuSystem.colorSphere.colorSphereExpanding += OnMenuColorSphereExpanding;
}
if (_bossGate != null)
_bossGate.colorSphere.colorSphereExpanding += OnBossGateColorSphereExpanding;
}
void OnDisable()
{
if (_beatSwitchColorSpheres != null)
{
foreach (var colorSphere in _beatSwitchColorSpheres)
colorSphere.colorSphereExpanding -= OnColorSphereExpanding;
}
if (_menuSystem != null)
{
_menuSystem.colorSphere.colorSphereOpened -= OnMenuKeyUsed;
_menuSystem.colorSphere.colorSphereExpanding -= OnMenuColorSphereExpanding;
}
if (_bossGate != null)
_bossGate.colorSphere.colorSphereExpanding -= OnBossGateColorSphereExpanding;
}
void OnBossGateColorSphereExpanding()
{
// colorSphereExpanding is triggered twice for some reason
_bossGate.colorSphere.colorSphereExpanding -= OnBossGateColorSphereExpanding;
Debug.Log("BossGate colorsphere expanding: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.Split();
}
void OnColorSphereExpanding()
{
Debug.Log("BeatLayerSwitch colorsphere expanding: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.Split();
}
void OnMenuColorSphereExpanding()
{
Debug.Log("OnMenuColorSphereExpanding: " + DebugBeatListener.DebugStr);
// colorsphere expands 32 quarterbeats after opening, then starts the load after 0.66s
SpeedrunTimer.Instance?.Split();
SpeedrunTimer.Instance?.StartLoad(660);
}
void OnMenuKeyUsed()
{
Debug.Log("OnMenuKeyUsed: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.Unfreeze();
}
}
}
|
using UnityEngine;
namespace SpeedrunTimerMod.GameObservers
{
[GameObserver]
class BeatLayerSwitchObserver : MonoBehaviour
{
GameObject _levelsFolder;
MenuSystem _menuSystem;
void Awake()
{
_levelsFolder = GameObject.Find("Levels");
if (_levelsFolder == null)
{
Debug.Log($"{nameof(BeatLayerSwitchObserver)}: Couldn't find Levels object");
Destroy(this);
return;
}
var menuSystemObj = GameObject.Find("_MenuSystem");
if (menuSystemObj != null)
_menuSystem = menuSystemObj.GetComponent<MenuSystem>();
else
Debug.Log($"{nameof(BeatLayerSwitchObserver)}: Couldn't find _MenuSystem object");
}
void OnEnable()
{
var colorSpheres = _levelsFolder.GetComponentsInChildren<ColorSphere>();
foreach (var colorSphere in colorSpheres)
{
if (_menuSystem != null && colorSphere == _menuSystem.colorSphere)
{
colorSphere.colorSphereOpened += OnMenuKeyUsed;
colorSphere.colorSphereExpanding += OnMenuColorSphereExpanding;
}
else
{
colorSphere.colorSphereExpanding += OnColorSphereExpanding;
}
}
}
void OnDisable()
{
if (_levelsFolder == null)
return;
var colorSpheres = _levelsFolder.GetComponentsInChildren<ColorSphere>();
foreach (var colorSphere in colorSpheres)
{
if (_menuSystem != null && colorSphere == _menuSystem.colorSphere)
{
colorSphere.colorSphereOpened -= OnMenuKeyUsed;
colorSphere.colorSphereExpanding -= OnMenuColorSphereExpanding;
}
else
{
colorSphere.colorSphereExpanding -= OnColorSphereExpanding;
}
}
}
void OnColorSphereExpanding()
{
Debug.Log("BeatLayerSwitch colorsphere expanding: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.Split();
}
void OnMenuColorSphereExpanding()
{
Debug.Log("OnMenuColorSphereExpanding: " + DebugBeatListener.DebugStr);
// colorsphere expands 32 quarterbeats after opening, then starts the load after 0.66s
SpeedrunTimer.Instance?.Split();
SpeedrunTimer.Instance?.StartLoad(660);
}
void OnMenuKeyUsed()
{
Debug.Log("OnMenuKeyUsed: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.Unfreeze();
}
}
}
|
unlicense
|
C#
|
ac998fe28bf41c3e9fa4d54a093f00638db2639e
|
Make server port configurable
|
ritnorthstar/Minimap-Control
|
Server/Hosting/WebAPIServer.cs
|
Server/Hosting/WebAPIServer.cs
|
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Server.Hosting
{
public class WebAPIServer
{
private IDisposable instance;
public int Port
{
get
{
return Port;
}
set
{
port = value;
if (IsRunning())
{
Restart();
}
}
}
protected int port = 9000;
public void Start()
{
if (!IsRunning())
{
Console.WriteLine("STARTING SERVER");
instance = WebApp.Start<Startup>(url: "http://*:" + Port);
}
}
public void Stop()
{
if (IsRunning())
{
Console.WriteLine("STOPPING SERVER");
instance.Dispose();
instance = null;
}
}
public void Restart()
{
Stop();
Start();
}
public bool IsRunning()
{
return instance != null;
}
}
}
|
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Server.Hosting
{
public class WebAPIServer
{
private IDisposable instance;
public void Start(int port = 9000)
{
if (instance == null)
{
Console.WriteLine("STARTING SERVER");
instance = WebApp.Start<Startup>(url: "http://*:" + port);
}
}
public void Stop()
{
if (instance != null)
{
Console.WriteLine("STOPPING SERVER");
instance.Dispose();
instance = null;
}
}
public void Restart()
{
Stop();
Start();
}
public bool IsRunning()
{
return instance != null;
}
}
}
|
mit
|
C#
|
8092d517c797a1102acda5ed58b0df5aba301d5c
|
Make monster mirror player's Y position
|
ianlav/EECS393IsaacGameThing,ianlav/EECS393IsaacGameThing,ianlav/EECS393IsaacGameThing
|
EECS393IsaacGameThing/Assets/Scripts/Characters/Enemy/Monster.cs
|
EECS393IsaacGameThing/Assets/Scripts/Characters/Enemy/Monster.cs
|
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Monster : MonoBehaviour {
public int updatesToUpgrade;
private int updateClock;
public float maxVelocity; //Highest possible speed of monster. Increases as game progresses.
public float acceleration; //Ability for monster to return to speed when hit. Increases.
public float defense; //Modifier for the amount that damage slows down monster. Increases.
private Rigidbody2D rigidMonster;
void Start () {
rigidMonster = GetComponent<Rigidbody2D>();
gameObject.tag = "Monster";
gameObject.layer = LayerMask.NameToLayer("Monster");
}
public void takeDamage(int damage){
maxVelocity -= damage/defense; //slow the monster when hit by projectile
}
void Update () {
if(rigidMonster.velocity.x<maxVelocity){
Vector2 playerPos = GameObject.Find ("Player").transform.position;
rigidMonster.velocity = new Vector2(rigidMonster.velocity.x+acceleration, playerPos.y);
if(rigidMonster.velocity.x > maxVelocity){rigidMonster.velocity=new Vector2(maxVelocity, playerPos.y);}
}
if (updateClock == updatesToUpgrade) {
updateClock = 0;
UpgradeMonster ();
} else {
updateClock++;
}
}
void UpgradeMonster(){
maxVelocity += 0.25f;
acceleration += 0.1f;
defense += 1f;
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.CompareTag("Player") || col.CompareTag("Floor"))
Destroy(col.gameObject);
if (col.CompareTag ("Bullet"))
rigidMonster.velocity = new Vector2 (rigidMonster.velocity.x - 10 / (1 + defense), 0);
}
}
|
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class Monster : MonoBehaviour {
public int updatesToUpgrade;
private int updateClock;
public float maxVelocity; //Highest possible speed of monster. Increases as game progresses.
public float acceleration; //Ability for monster to return to speed when hit. Increases.
public float defense; //Modifier for the amount that damage slows down monster. Increases.
private Rigidbody2D rigidMonster;
void Start () {
rigidMonster = GetComponent<Rigidbody2D>();
gameObject.tag = "Monster";
gameObject.layer = LayerMask.NameToLayer("Monster");
}
public void takeDamage(int damage){
maxVelocity -= damage/defense; //slow the monster when hit by projectile
}
void Update () {
if(rigidMonster.velocity.x<maxVelocity){
rigidMonster.velocity = new Vector2(rigidMonster.velocity.x+acceleration, 0);
if(rigidMonster.velocity.x > maxVelocity){rigidMonster.velocity=new Vector2(maxVelocity,0);}
}
if (updateClock == updatesToUpgrade) {
updateClock = 0;
UpgradeMonster ();
} else {
updateClock++;
}
}
void UpgradeMonster(){
maxVelocity += 0.25f;
acceleration += 0.1f;
defense += 1f;
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.CompareTag("Player") || col.CompareTag("Floor"))
Destroy(col.gameObject);
if (col.CompareTag ("Bullet"))
rigidMonster.velocity = new Vector2 (rigidMonster.velocity.x - 10 / (1 + defense), 0);
}
}
|
apache-2.0
|
C#
|
0e594dd5a156b748fbd9ae8b0bcad354daa533ea
|
Make sure compiler knows of access to threaded value.
|
rdodesigns/Esoma-Data-Processor
|
src/device/Device.cs
|
src/device/Device.cs
|
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace Device
{
public abstract class Device
{
protected string name;
protected SortedList data = new SortedList();
private DataRecord.DataRecordGenerator drg;
private bool stopped = false;
private volatile bool end = false;
public Device(DataRecord.DataRecordGenerator drg)
{
this.init();
System.Console.WriteLine("Created {0} Device object.", this.name);
this.drg = drg;
this.registerDataTypes();
this.registerWithDataRecord();
}
protected abstract void init();
protected abstract void registerDataTypes();
public void start(){
if(!stopped){
Thread t = new Thread(acquireData);
t.Start();
} else
System.Console.WriteLine("ERROR: Device {0} is stopped due to an error.", this.name);
}
public void stop() { end = true;}
protected abstract void getInput();
public void acquireData(){
while (!end){
System.Threading.Thread.Sleep(1000);
this.getInput();
this.sendToDataRecord();
}
}
private void registerWithDataRecord(){
try {
for(int i = 0; i < data.Count; i++)
drg.addDataField((string) data.GetKey(i), data.GetByIndex(i));
}
catch (Exception ex){
System.Console.WriteLine(ex);
this.stopped = true;
unregisterWithDataRecord();
}
}
private void unregisterWithDataRecord(){
for(int i = 0; i < data.Count; i++)
drg.removeKey((string) data.GetKey(i));
}
private void sendToDataRecord() {
lock(drg.loc){
try {
drg.addValues(data);
}
catch (Exception ex) {
System.Console.WriteLine("ERROR: {0} Could not send to DataRecordGenerator", name);
throw ex;
}
}
}
} // end class Device
} // end namespace Device
|
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace Device
{
public abstract class Device
{
protected string name;
protected SortedList data = new SortedList();
private DataRecord.DataRecordGenerator drg;
private bool stopped = false;
private bool end = false;
public Device(DataRecord.DataRecordGenerator drg)
{
this.init();
System.Console.WriteLine("Created {0} Device object.", this.name);
this.drg = drg;
this.registerDataTypes();
this.registerWithDataRecord();
}
protected abstract void init();
protected abstract void registerDataTypes();
public void start(){
if(!stopped){
Thread t = new Thread(acquireData);
t.Start();
} else
System.Console.WriteLine("ERROR: Device {0} is stopped due to an error.", this.name);
}
public void stop() { end = true;}
protected abstract void getInput();
public void acquireData(){
while (!end){
System.Threading.Thread.Sleep(1000);
this.getInput();
this.sendToDataRecord();
}
}
private void registerWithDataRecord(){
try {
for(int i = 0; i < data.Count; i++)
drg.addDataField((string) data.GetKey(i), data.GetByIndex(i));
}
catch (Exception ex){
System.Console.WriteLine(ex);
this.stopped = true;
unregisterWithDataRecord();
}
}
private void unregisterWithDataRecord(){
for(int i = 0; i < data.Count; i++)
drg.removeKey((string) data.GetKey(i));
}
private void sendToDataRecord() {
lock(drg.loc){
try {
drg.addValues(data);
}
catch (Exception ex) {
System.Console.WriteLine("ERROR: {0} Could not send to DataRecordGenerator", name);
throw ex;
}
}
}
} // end class Device
} // end namespace Device
|
bsd-3-clause
|
C#
|
8e3036dd93780722e34da4cca333e13f08229662
|
move inout inside label
|
MacsDickinson/HackManchester2014,MacsDickinson/HackManchester2014,MacsDickinson/HackManchester2014
|
HackManchester2014/HackManchester2014/Home/Views/Register4.cshtml
|
HackManchester2014/HackManchester2014/Home/Views/Register4.cshtml
|
@{
Layout = "Shared/_Layout.cshtml";
}
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
<article>
<section class="container-block">
<div class="layout-constrained form-step">
<h2><span class="progress-step">3</span>Upload your proof</h2>
<div class="form-step__intro">
<p>
Select a challenge from below to
</p>
</div>
<fieldset>
<legend class="is-offscreen">Prove you have done the challenge</legend>
<div class="form-group">
<form id="upload-form" method="POST" enctype="multipart/form-data">
<label for="proof-file" class="btn btn--primary">
Upload your image
<input type="file" id="proof-file" name="file" onchange="$('#upload-form').submit();" />
</label>
</form>
</div>
</fieldset>
</div>
</section>
</article>
|
@{
Layout = "Shared/_Layout.cshtml";
}
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
<article>
<section class="container-block">
<div class="layout-constrained form-step">
<h2><span class="progress-step">3</span>Upload your proof</h2>
<div class="form-step__intro">
<p>
Select a challenge from below to
</p>
</div>
<fieldset>
<legend class="is-offscreen">Prove you have done the challenge</legend>
<div class="form-group">
<form id="upload-form" method="POST" enctype="multipart/form-data">
<label for="proof-file" class="btn btn--primary">
Upload your image
</label>
<input type="file" id="proof-file" name="file" onchange="$('#upload-form').submit();" />
</form>
</div>
</fieldset>
</div>
</section>
</article>
|
mit
|
C#
|
29fb2c0dc5d68a585450e03ae4d3cd890e0d1f77
|
Update Constants.cs
|
peejster/DormRoomMonitor
|
DormRoomMonitor/Constants.cs
|
DormRoomMonitor/Constants.cs
|
namespace DormRoomMonitor
{
/// <summary>
/// General constant variables
/// </summary>
public static class GeneralConstants
{
// With no GPU support, the Raspberry Pi cannot display the live camera feed so this variable should be set to true.
// However, if you are deploying to other harware on which Windows 10 IoT Core does have GPU support, set it to fale.
public const bool DisableLiveCameraFeed = true;
// Oxford Face API Primary should be entered here
// You can obtain a subscription key for Face API by following the instructions here: https://www.projectoxford.ai/doc/general/subscription-key-mgmt
public const string OxfordAPIKey = "<your Oxford Face API key>";
// Name of the folder in which all Whitelist data is stored
public const string WhiteListFolderName = "Dorm Room Monitor Whitelist";
// Name of the folder in which all the intruder data is stored
public const string IntruderFolderName = "Dorm Room Monitor Intruders";
}
/// <summary>
/// Constant variables that hold messages to be read via the SpeechHelper class
/// </summary>
public static class SpeechContants
{
public const string InitialGreetingMessage = "Dorm room monitor has been activated.";
public const string IntruderDetectedMessage = "Intruder detected.";
public const string NotAllowedEntryMessage = "Sorry! I don't recognize you. You are not authorized to be here.";
public const string NoCameraMessage = "Sorry! It seems like your camera has not been fully initialized.";
public static string AllowedEntryMessage(string visitorName)
{
return "Hello " + visitorName + "! You are authorized to be here.";
}
}
/// <summary>
/// Constant variables that hold values used to interact with device Gpio
/// </summary>
public static class GpioConstants
{
// The GPIO pin that the PIR motion sensor is attached to
public const int PirPin = 5;
// The GPIO pin that the door lock is attached to
public const int DoorLockPinID = 6;
// The amount of time in seconds that the door will remain unlocked for
public const int DoorLockOpenDurationSeconds = 10;
}
}
|
namespace DormRoomMonitor
{
/// <summary>
/// General constant variables
/// </summary>
public static class GeneralConstants
{
// With no GPU support, the Raspberry Pi cannot display the live camera feed so this variable should be set to true.
// However, if you are deploying to other harware on which Windows 10 IoT Core does have GPU support, set it to fale.
public const bool DisableLiveCameraFeed = true;
// Oxford Face API Primary should be entered here
// You can obtain a subscription key for Face API by following the instructions here: https://www.projectoxford.ai/doc/general/subscription-key-mgmt
public const string OxfordAPIKey = "<your Oxford Face API>";
// Name of the folder in which all Whitelist data is stored
public const string WhiteListFolderName = "Dorm Room Monitor Whitelist";
// Name of the folder in which all the intruder data is stored
public const string IntruderFolderName = "Dorm Room Monitor Intruders";
}
/// <summary>
/// Constant variables that hold messages to be read via the SpeechHelper class
/// </summary>
public static class SpeechContants
{
public const string InitialGreetingMessage = "Dorm room monitor has been activated.";
public const string IntruderDetectedMessage = "Intruder detected.";
public const string NotAllowedEntryMessage = "Sorry! I don't recognize you. You are not authorized to be here.";
public const string NoCameraMessage = "Sorry! It seems like your camera has not been fully initialized.";
public static string AllowedEntryMessage(string visitorName)
{
return "Hello " + visitorName + "! You are authorized to be here.";
}
}
/// <summary>
/// Constant variables that hold values used to interact with device Gpio
/// </summary>
public static class GpioConstants
{
// The GPIO pin that the PIR motion sensor is attached to
public const int PirPin = 5;
// The GPIO pin that the door lock is attached to
public const int DoorLockPinID = 6;
// The amount of time in seconds that the door will remain unlocked for
public const int DoorLockOpenDurationSeconds = 10;
}
}
|
mit
|
C#
|
18a03731ba5f935f5e4b8c5948030c186d7791e6
|
Combine return with assignment.
|
jherby2k/AudioWorks
|
AudioWorks/AudioWorks.Commands/SaveAudioMetadataCommand.cs
|
AudioWorks/AudioWorks.Commands/SaveAudioMetadataCommand.cs
|
using AudioWorks.Api;
using AudioWorks.Common;
using JetBrains.Annotations;
using System.IO;
using System.Management.Automation;
namespace AudioWorks.Commands
{
/// <summary>
/// <para type="synopsis">Saves an audio file's metadata to disk.</para>
/// <para type="description">The Save-AudioMetadata cmdlet persists changes to an audio file's metadata. Depending
/// on the file extension, various optional parameters may be available.</para>
/// </summary>
[PublicAPI]
[Cmdlet(VerbsData.Save, "AudioMetadata", SupportsShouldProcess = true), OutputType(typeof(ITaggedAudioFile))]
public sealed class SaveAudioMetadataCommand : Cmdlet, IDynamicParameters
{
[CanBeNull] RuntimeDefinedParameterDictionary _parameters;
/// <summary>
/// <para type="description">Specifies the audio file.</para>
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
public ITaggedAudioFile AudioFile { get; set; }
/// <summary>
/// <para type="description">Returns an object representing the item with which you are working. By default,
/// this cmdlet does not generate any output.</para>
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }
/// <inheritdoc/>
protected override void ProcessRecord()
{
try
{
if (ShouldProcess(AudioFile.Path))
AudioFile.SaveMetadata(SettingAdapter.ParametersToSettings(_parameters));
}
catch (AudioUnsupportedException e)
{
WriteError(new ErrorRecord(e, e.GetType().Name, ErrorCategory.InvalidData, AudioFile));
}
if (PassThru)
WriteObject(AudioFile);
}
/// <inheritdoc/>
[CanBeNull]
public object GetDynamicParameters()
{
// AudioFile parameter may not be bound yet
if (AudioFile == null) return null;
return _parameters = SettingAdapter.SettingInfoToParameters(
AudioMetadataEncoderManager.GetSettingInfo(Path.GetExtension(AudioFile.Path)));
}
}
}
|
using AudioWorks.Api;
using AudioWorks.Common;
using JetBrains.Annotations;
using System.IO;
using System.Management.Automation;
namespace AudioWorks.Commands
{
/// <summary>
/// <para type="synopsis">Saves an audio file's metadata to disk.</para>
/// <para type="description">The Save-AudioMetadata cmdlet persists changes to an audio file's metadata. Depending
/// on the file extension, various optional parameters may be available.</para>
/// </summary>
[PublicAPI]
[Cmdlet(VerbsData.Save, "AudioMetadata", SupportsShouldProcess = true), OutputType(typeof(ITaggedAudioFile))]
public sealed class SaveAudioMetadataCommand : Cmdlet, IDynamicParameters
{
[CanBeNull] RuntimeDefinedParameterDictionary _parameters;
/// <summary>
/// <para type="description">Specifies the audio file.</para>
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
public ITaggedAudioFile AudioFile { get; set; }
/// <summary>
/// <para type="description">Returns an object representing the item with which you are working. By default,
/// this cmdlet does not generate any output.</para>
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }
/// <inheritdoc/>
protected override void ProcessRecord()
{
try
{
if (ShouldProcess(AudioFile.Path))
AudioFile.SaveMetadata(SettingAdapter.ParametersToSettings(_parameters));
}
catch (AudioUnsupportedException e)
{
WriteError(new ErrorRecord(e, e.GetType().Name, ErrorCategory.InvalidData, AudioFile));
}
if (PassThru)
WriteObject(AudioFile);
}
/// <inheritdoc/>
[CanBeNull]
public object GetDynamicParameters()
{
// AudioFile parameter may not be bound yet
if (AudioFile == null) return null;
_parameters = SettingAdapter.SettingInfoToParameters(
AudioMetadataEncoderManager.GetSettingInfo(Path.GetExtension(AudioFile.Path)));
return _parameters;
}
}
}
|
agpl-3.0
|
C#
|
0fa043123efffaa878e87cc24f17b10e0967efc0
|
Fix doc comment cref being incorrect
|
terrafx/terrafx
|
sources/Audio/AudioDeviceType.cs
|
sources/Audio/AudioDeviceType.cs
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
namespace TerraFX.Audio
{
/// <summary>Represents a type of <see cref="IAudioAdapter"/></summary>
public enum AudioDeviceType
{
/// <summary>Indicates that this is a device used for recording.</summary>
Recording,
/// <summary>Indicates that this is a device used for playback.</summary>
Playback
}
}
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
namespace TerraFX.Audio
{
/// <summary>Represents a type of <see cref="IAudioDeviceOptions"/></summary>
public enum AudioDeviceType
{
/// <summary>Indicates that this is a device used for recording.</summary>
Recording,
/// <summary>Indicates that this is a device used for playback.</summary>
Playback
}
}
|
mit
|
C#
|
1fcf4c4bbc4bdda26c3c5f9d3ec39957938c7557
|
Fix build breaks mirrored from Github
|
CloudLens/corefx,Petermarcu/corefx,oceanho/corefx,alexandrnikitin/corefx,Frank125/corefx,rjxby/corefx,wtgodbe/corefx,ViktorHofer/corefx,krk/corefx,the-dwyer/corefx,Petermarcu/corefx,mafiya69/corefx,nbarbettini/corefx,gkhanna79/corefx,rahku/corefx,adamralph/corefx,n1ghtmare/corefx,rahku/corefx,uhaciogullari/corefx,vs-team/corefx,dhoehna/corefx,benjamin-bader/corefx,the-dwyer/corefx,khdang/corefx,nbarbettini/corefx,tstringer/corefx,tijoytom/corefx,shahid-pk/corefx,Petermarcu/corefx,larsbj1988/corefx,nchikanov/corefx,vrassouli/corefx,parjong/corefx,dkorolev/corefx,elijah6/corefx,jmhardison/corefx,Chrisboh/corefx,alphonsekurian/corefx,erpframework/corefx,MaggieTsang/corefx,khdang/corefx,ericstj/corefx,pallavit/corefx,twsouthwick/corefx,weltkante/corefx,BrennanConroy/corefx,ptoonen/corefx,shimingsg/corefx,cartermp/corefx,ericstj/corefx,heXelium/corefx,kyulee1/corefx,richlander/corefx,marksmeltzer/corefx,ellismg/corefx,rahku/corefx,pgavlin/corefx,stormleoxia/corefx,cydhaselton/corefx,josguil/corefx,ericstj/corefx,iamjasonp/corefx,Chrisboh/corefx,kyulee1/corefx,rubo/corefx,parjong/corefx,Priya91/corefx-1,mmitche/corefx,vs-team/corefx,mmitche/corefx,kkurni/corefx,benjamin-bader/corefx,JosephTremoulet/corefx,dtrebbien/corefx,Yanjing123/corefx,lggomez/corefx,axelheer/corefx,mokchhya/corefx,jmhardison/corefx,shrutigarg/corefx,rajansingh10/corefx,zhangwenquan/corefx,cydhaselton/corefx,janhenke/corefx,ericstj/corefx,benjamin-bader/corefx,shmao/corefx,shmao/corefx,jhendrixMSFT/corefx,ptoonen/corefx,anjumrizwi/corefx,690486439/corefx,axelheer/corefx,jcme/corefx,jlin177/corefx,jcme/corefx,benpye/corefx,thiagodin/corefx,nchikanov/corefx,vrassouli/corefx,fgreinacher/corefx,josguil/corefx,Ermiar/corefx,jeremymeng/corefx,alphonsekurian/corefx,cnbin/corefx,Chrisboh/corefx,heXelium/corefx,krytarowski/corefx,n1ghtmare/corefx,Jiayili1/corefx,billwert/corefx,brett25/corefx,PatrickMcDonald/corefx,Chrisboh/corefx,PatrickMcDonald/corefx,weltkante/corefx,axelheer/corefx,Petermarcu/corefx,krytarowski/corefx,MaggieTsang/corefx,lggomez/corefx,VPashkov/corefx,stone-li/corefx,benpye/corefx,janhenke/corefx,krk/corefx,parjong/corefx,axelheer/corefx,nbarbettini/corefx,fffej/corefx,yizhang82/corefx,Frank125/corefx,dhoehna/corefx,nchikanov/corefx,jcme/corefx,rahku/corefx,cydhaselton/corefx,SGuyGe/corefx,zhenlan/corefx,zhenlan/corefx,iamjasonp/corefx,larsbj1988/corefx,kkurni/corefx,shana/corefx,ellismg/corefx,jcme/corefx,the-dwyer/corefx,ViktorHofer/corefx,DnlHarvey/corefx,mellinoe/corefx,lydonchandra/corefx,vijaykota/corefx,josguil/corefx,shahid-pk/corefx,jlin177/corefx,vijaykota/corefx,huanjie/corefx,CherryCxldn/corefx,billwert/corefx,vidhya-bv/corefx-sorting,gkhanna79/corefx,erpframework/corefx,zhenlan/corefx,jmhardison/corefx,rajansingh10/corefx,akivafr123/corefx,kyulee1/corefx,manu-silicon/corefx,mmitche/corefx,andyhebear/corefx,CloudLens/corefx,shrutigarg/corefx,adamralph/corefx,shimingsg/corefx,MaggieTsang/corefx,mazong1123/corefx,shrutigarg/corefx,chenxizhang/corefx,xuweixuwei/corefx,dotnet-bot/corefx,DnlHarvey/corefx,josguil/corefx,yizhang82/corefx,YoupHulsebos/corefx,dotnet-bot/corefx,fffej/corefx,shana/corefx,MaggieTsang/corefx,Jiayili1/corefx,marksmeltzer/corefx,Ermiar/corefx,khdang/corefx,brett25/corefx,bitcrazed/corefx,nelsonsar/corefx,n1ghtmare/corefx,ViktorHofer/corefx,jeremymeng/corefx,VPashkov/corefx,dhoehna/corefx,yizhang82/corefx,bpschoch/corefx,elijah6/corefx,chenxizhang/corefx,ellismg/corefx,nbarbettini/corefx,parjong/corefx,PatrickMcDonald/corefx,zhenlan/corefx,nbarbettini/corefx,kkurni/corefx,lggomez/corefx,shana/corefx,iamjasonp/corefx,manu-silicon/corefx,vijaykota/corefx,nbarbettini/corefx,wtgodbe/corefx,lydonchandra/corefx,nchikanov/corefx,stephenmichaelf/corefx,lggomez/corefx,andyhebear/corefx,chaitrakeshav/corefx,huanjie/corefx,Priya91/corefx-1,mmitche/corefx,parjong/corefx,khdang/corefx,cartermp/corefx,YoupHulsebos/corefx,ptoonen/corefx,shmao/corefx,gregg-miskelly/corefx,zhangwenquan/corefx,nbarbettini/corefx,anjumrizwi/corefx,chaitrakeshav/corefx,nelsonsar/corefx,Petermarcu/corefx,ravimeda/corefx,pgavlin/corefx,gkhanna79/corefx,bpschoch/corefx,lggomez/corefx,Ermiar/corefx,dhoehna/corefx,tstringer/corefx,jlin177/corefx,cartermp/corefx,MaggieTsang/corefx,josguil/corefx,shimingsg/corefx,jhendrixMSFT/corefx,shmao/corefx,gabrielPeart/corefx,viniciustaveira/corefx,krk/corefx,pallavit/corefx,zhenlan/corefx,dotnet-bot/corefx,dotnet-bot/corefx,benjamin-bader/corefx,fgreinacher/corefx,jeremymeng/corefx,akivafr123/corefx,shimingsg/corefx,CherryCxldn/corefx,axelheer/corefx,weltkante/corefx,YoupHulsebos/corefx,chenxizhang/corefx,oceanho/corefx,gkhanna79/corefx,ravimeda/corefx,twsouthwick/corefx,claudelee/corefx,mokchhya/corefx,claudelee/corefx,richlander/corefx,lggomez/corefx,billwert/corefx,jcme/corefx,alexandrnikitin/corefx,iamjasonp/corefx,shahid-pk/corefx,mazong1123/corefx,seanshpark/corefx,pgavlin/corefx,stephenmichaelf/corefx,pallavit/corefx,mokchhya/corefx,shmao/corefx,mazong1123/corefx,ViktorHofer/corefx,DnlHarvey/corefx,parjong/corefx,Yanjing123/corefx,KrisLee/corefx,stone-li/corefx,janhenke/corefx,seanshpark/corefx,Frank125/corefx,zhenlan/corefx,marksmeltzer/corefx,shmao/corefx,twsouthwick/corefx,mellinoe/corefx,kkurni/corefx,ptoonen/corefx,uhaciogullari/corefx,benpye/corefx,mellinoe/corefx,JosephTremoulet/corefx,gkhanna79/corefx,rubo/corefx,wtgodbe/corefx,alexandrnikitin/corefx,alexandrnikitin/corefx,the-dwyer/corefx,mafiya69/corefx,dhoehna/corefx,stephenmichaelf/corefx,stormleoxia/corefx,Yanjing123/corefx,vs-team/corefx,larsbj1988/corefx,tstringer/corefx,benpye/corefx,parjong/corefx,twsouthwick/corefx,rajansingh10/corefx,elijah6/corefx,DnlHarvey/corefx,pgavlin/corefx,jhendrixMSFT/corefx,thiagodin/corefx,fgreinacher/corefx,andyhebear/corefx,shana/corefx,krytarowski/corefx,benjamin-bader/corefx,ericstj/corefx,comdiv/corefx,bitcrazed/corefx,Jiayili1/corefx,alexperovich/corefx,erpframework/corefx,tijoytom/corefx,MaggieTsang/corefx,SGuyGe/corefx,jlin177/corefx,rjxby/corefx,cydhaselton/corefx,ravimeda/corefx,jlin177/corefx,matthubin/corefx,benpye/corefx,stephenmichaelf/corefx,VPashkov/corefx,mmitche/corefx,n1ghtmare/corefx,mokchhya/corefx,weltkante/corefx,fgreinacher/corefx,tstringer/corefx,elijah6/corefx,xuweixuwei/corefx,vrassouli/corefx,ericstj/corefx,Alcaro/corefx,kyulee1/corefx,shrutigarg/corefx,fffej/corefx,shimingsg/corefx,stormleoxia/corefx,wtgodbe/corefx,alphonsekurian/corefx,pallavit/corefx,mafiya69/corefx,lydonchandra/corefx,marksmeltzer/corefx,seanshpark/corefx,billwert/corefx,JosephTremoulet/corefx,bpschoch/corefx,richlander/corefx,jmhardison/corefx,pallavit/corefx,rajansingh10/corefx,CherryCxldn/corefx,dkorolev/corefx,lggomez/corefx,vidhya-bv/corefx-sorting,Chrisboh/corefx,shmao/corefx,weltkante/corefx,janhenke/corefx,s0ne0me/corefx,shahid-pk/corefx,tijoytom/corefx,mazong1123/corefx,xuweixuwei/corefx,iamjasonp/corefx,jhendrixMSFT/corefx,thiagodin/corefx,heXelium/corefx,Yanjing123/corefx,billwert/corefx,wtgodbe/corefx,Alcaro/corefx,alphonsekurian/corefx,akivafr123/corefx,alexperovich/corefx,PatrickMcDonald/corefx,bitcrazed/corefx,dsplaisted/corefx,stephenmichaelf/corefx,brett25/corefx,scott156/corefx,manu-silicon/corefx,krytarowski/corefx,SGuyGe/corefx,mazong1123/corefx,brett25/corefx,kkurni/corefx,dsplaisted/corefx,jeremymeng/corefx,comdiv/corefx,ellismg/corefx,wtgodbe/corefx,VPashkov/corefx,claudelee/corefx,YoupHulsebos/corefx,stone-li/corefx,Petermarcu/corefx,mafiya69/corefx,rjxby/corefx,uhaciogullari/corefx,yizhang82/corefx,690486439/corefx,dkorolev/corefx,mellinoe/corefx,KrisLee/corefx,gregg-miskelly/corefx,the-dwyer/corefx,akivafr123/corefx,krytarowski/corefx,wtgodbe/corefx,gkhanna79/corefx,nchikanov/corefx,Alcaro/corefx,ravimeda/corefx,viniciustaveira/corefx,anjumrizwi/corefx,rjxby/corefx,dhoehna/corefx,dtrebbien/corefx,huanjie/corefx,scott156/corefx,dhoehna/corefx,oceanho/corefx,krk/corefx,alphonsekurian/corefx,manu-silicon/corefx,vrassouli/corefx,rahku/corefx,690486439/corefx,Priya91/corefx-1,heXelium/corefx,690486439/corefx,nelsonsar/corefx,shimingsg/corefx,chaitrakeshav/corefx,zhangwenquan/corefx,stormleoxia/corefx,rjxby/corefx,mmitche/corefx,CloudLens/corefx,erpframework/corefx,krk/corefx,pallavit/corefx,tijoytom/corefx,PatrickMcDonald/corefx,gregg-miskelly/corefx,chaitrakeshav/corefx,gregg-miskelly/corefx,rjxby/corefx,elijah6/corefx,bitcrazed/corefx,seanshpark/corefx,viniciustaveira/corefx,mafiya69/corefx,Jiayili1/corefx,YoupHulsebos/corefx,zmaruo/corefx,twsouthwick/corefx,nchikanov/corefx,shahid-pk/corefx,rubo/corefx,seanshpark/corefx,JosephTremoulet/corefx,ptoonen/corefx,cydhaselton/corefx,ellismg/corefx,Jiayili1/corefx,DnlHarvey/corefx,rahku/corefx,mazong1123/corefx,vidhya-bv/corefx-sorting,BrennanConroy/corefx,Frank125/corefx,cnbin/corefx,Priya91/corefx-1,matthubin/corefx,SGuyGe/corefx,alexandrnikitin/corefx,s0ne0me/corefx,comdiv/corefx,twsouthwick/corefx,matthubin/corefx,ViktorHofer/corefx,nelsonsar/corefx,zmaruo/corefx,Priya91/corefx-1,mafiya69/corefx,shahid-pk/corefx,ravimeda/corefx,KrisLee/corefx,alphonsekurian/corefx,jhendrixMSFT/corefx,billwert/corefx,khdang/corefx,krk/corefx,kkurni/corefx,JosephTremoulet/corefx,krytarowski/corefx,scott156/corefx,rubo/corefx,mokchhya/corefx,khdang/corefx,dtrebbien/corefx,cartermp/corefx,yizhang82/corefx,iamjasonp/corefx,stone-li/corefx,mokchhya/corefx,Yanjing123/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,CherryCxldn/corefx,bpschoch/corefx,fffej/corefx,comdiv/corefx,ptoonen/corefx,andyhebear/corefx,zhangwenquan/corefx,akivafr123/corefx,zmaruo/corefx,ravimeda/corefx,yizhang82/corefx,larsbj1988/corefx,Ermiar/corefx,alphonsekurian/corefx,josguil/corefx,mazong1123/corefx,cydhaselton/corefx,alexperovich/corefx,ViktorHofer/corefx,jcme/corefx,iamjasonp/corefx,tijoytom/corefx,jeremymeng/corefx,tijoytom/corefx,weltkante/corefx,ericstj/corefx,jlin177/corefx,tstringer/corefx,stephenmichaelf/corefx,alexperovich/corefx,marksmeltzer/corefx,Petermarcu/corefx,seanshpark/corefx,tijoytom/corefx,anjumrizwi/corefx,Jiayili1/corefx,viniciustaveira/corefx,BrennanConroy/corefx,manu-silicon/corefx,stone-li/corefx,rahku/corefx,richlander/corefx,the-dwyer/corefx,Priya91/corefx-1,ravimeda/corefx,cnbin/corefx,SGuyGe/corefx,janhenke/corefx,alexperovich/corefx,dotnet-bot/corefx,stephenmichaelf/corefx,s0ne0me/corefx,YoupHulsebos/corefx,dsplaisted/corefx,dotnet-bot/corefx,ellismg/corefx,manu-silicon/corefx,krk/corefx,cartermp/corefx,manu-silicon/corefx,DnlHarvey/corefx,shimingsg/corefx,bitcrazed/corefx,mmitche/corefx,jhendrixMSFT/corefx,jlin177/corefx,cydhaselton/corefx,richlander/corefx,krytarowski/corefx,mellinoe/corefx,JosephTremoulet/corefx,billwert/corefx,yizhang82/corefx,Alcaro/corefx,gabrielPeart/corefx,Ermiar/corefx,alexperovich/corefx,stone-li/corefx,axelheer/corefx,marksmeltzer/corefx,scott156/corefx,zhenlan/corefx,690486439/corefx,seanshpark/corefx,claudelee/corefx,rubo/corefx,KrisLee/corefx,vidhya-bv/corefx-sorting,Ermiar/corefx,MaggieTsang/corefx,adamralph/corefx,janhenke/corefx,CloudLens/corefx,tstringer/corefx,oceanho/corefx,vidhya-bv/corefx-sorting,cnbin/corefx,dtrebbien/corefx,YoupHulsebos/corefx,weltkante/corefx,s0ne0me/corefx,gabrielPeart/corefx,jhendrixMSFT/corefx,matthubin/corefx,thiagodin/corefx,ViktorHofer/corefx,n1ghtmare/corefx,DnlHarvey/corefx,rjxby/corefx,alexperovich/corefx,benpye/corefx,Ermiar/corefx,dkorolev/corefx,ptoonen/corefx,vs-team/corefx,richlander/corefx,richlander/corefx,mellinoe/corefx,elijah6/corefx,nchikanov/corefx,uhaciogullari/corefx,marksmeltzer/corefx,gabrielPeart/corefx,stone-li/corefx,benjamin-bader/corefx,the-dwyer/corefx,Jiayili1/corefx,huanjie/corefx,cartermp/corefx,zmaruo/corefx,gkhanna79/corefx,elijah6/corefx,SGuyGe/corefx,lydonchandra/corefx,twsouthwick/corefx,Chrisboh/corefx
|
src/Common/src/Interop/Windows/mincore/WinRT/Interop.DeleteVolumeMountPoint.cs
|
src/Common/src/Interop/Windows/mincore/WinRT/Interop.DeleteVolumeMountPoint.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal partial class Interop
{
internal partial class mincore
{
internal static bool DeleteVolumeMountPoint(string mountPoint)
{
// DeleteVolumeMountPointW is not available to store apps.
// The expectation is that no store app would even have permission
// to call this from the app container
throw new UnauthorizedAccessException();
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal partial class Interop
{
internal partial class mincore
{
internal static int DeleteVolumeMountPoint(string mountPoint)
{
// DeleteVolumeMountPointW is not available to store apps.
// The expectation is that no store app would even have permission
// to call this from the app container
throw new UnauthorizedAccessException();
}
}
}
|
mit
|
C#
|
928682e8d4020b4ee58e14de6a910551dfd7c4a8
|
Remove unused member
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/WebClients/PayJoin/PayjoinReceiverException.cs
|
WalletWasabi/WebClients/PayJoin/PayjoinReceiverException.cs
|
namespace WalletWasabi.WebClients.PayJoin
{
public class PayjoinReceiverException : PayjoinException
{
public PayjoinReceiverException(int httpCode, string errorCode, string message)
: base(message)
{
HttpCode = httpCode;
ErrorCode = errorCode;
ErrorMessage = message;
}
public int HttpCode { get; }
public string ErrorCode { get; }
public string ErrorMessage { get; }
}
}
|
namespace WalletWasabi.WebClients.PayJoin
{
public class PayjoinReceiverException : PayjoinException
{
public PayjoinReceiverException(int httpCode, string errorCode, string message)
: base(message)
{
HttpCode = httpCode;
ErrorCode = errorCode;
ErrorMessage = message;
}
public int HttpCode { get; }
public string ErrorCode { get; }
public string ErrorMessage { get; }
private static string FormatMessage(in int httpCode, string errorCode, string message)
{
return $"{errorCode}: {message} (HTTP: {httpCode})";
}
}
}
|
mit
|
C#
|
fa56806ab1f4061e59e56614ca3c847733afd032
|
Use using statement in WP samples
|
moljac/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,nexussays/Xamarin.Mobile,orand/Xamarin.Mobile,xamarin/Xamarin.Mobile,xamarin/Xamarin.Mobile
|
WindowsPhone/Samples/MediaPickerSample/MainPageViewModel.cs
|
WindowsPhone/Samples/MediaPickerSample/MainPageViewModel.cs
|
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Xamarin.Media;
namespace MediaPickerSample
{
public class MainPageViewModel
: INotifyPropertyChanged
{
public MainPageViewModel()
{
TakePhoto = new DelegatedCommand (TakePhotoHandler, s => this.picker.PhotosSupported && this.picker.IsCameraAvailable);
PickPhoto = new DelegatedCommand (PickPhotoHandler, s => this.picker.PhotosSupported);
}
public event PropertyChangedEventHandler PropertyChanged;
private string state;
public string State
{
get { return this.state; }
private set
{
if (this.state == value)
return;
this.state = value;
}
}
public ICommand TakePhoto
{
get;
private set;
}
public ICommand PickPhoto
{
get;
private set;
}
private BitmapImage image;
public BitmapImage Image
{
get { return this.image; }
private set
{
if (this.image == value)
return;
this.image = value;
OnPropertyChanged ("Image");
}
}
private readonly MediaPicker picker = new MediaPicker();
private async void TakePhotoHandler (object state)
{
try
{
using (MediaFile file = await this.picker.TakePhotoAsync (new StoreCameraMediaOptions()))
{
State = file.Path;
Image = new BitmapImage();
Image.SetSource (file.GetStream());
}
}
catch (TaskCanceledException canceled)
{
State = "Canceled";
}
catch (Exception ex)
{
State = "Error: " + ex.Message;
}
}
private async void PickPhotoHandler (object state)
{
try
{
using (MediaFile file = await this.picker.PickPhotoAsync())
{
State = file.Path;
Image = new BitmapImage();
Image.SetSource (file.GetStream());
}
}
catch (TaskCanceledException canceled)
{
State = "Canceled";
}
catch (Exception ex)
{
State = "Error: " + ex.Message;
}
}
private void OnPropertyChanged (string name)
{
var changed = PropertyChanged;
if (changed != null)
changed (this, new PropertyChangedEventArgs (name));
}
}
}
|
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Xamarin.Media;
namespace MediaPickerSample
{
public class MainPageViewModel
: INotifyPropertyChanged
{
public MainPageViewModel()
{
TakePhoto = new DelegatedCommand (TakePhotoHandler, s => this.picker.PhotosSupported && this.picker.IsCameraAvailable);
PickPhoto = new DelegatedCommand (PickPhotoHandler, s => this.picker.PhotosSupported);
}
public event PropertyChangedEventHandler PropertyChanged;
private string state;
public string State
{
get { return this.state; }
private set
{
if (this.state == value)
return;
this.state = value;
}
}
public ICommand TakePhoto
{
get;
private set;
}
public ICommand PickPhoto
{
get;
private set;
}
private BitmapImage image;
public BitmapImage Image
{
get { return this.image; }
private set
{
if (this.image == value)
return;
this.image = value;
OnPropertyChanged ("Image");
}
}
private readonly MediaPicker picker = new MediaPicker();
private async void TakePhotoHandler (object state)
{
try
{
MediaFile file = await this.picker.TakePhotoAsync (new StoreCameraMediaOptions());
State = file.Path;
Image = new BitmapImage();
Image.SetSource (file.GetStream());
}
catch (TaskCanceledException canceled)
{
State = "Canceled";
}
catch (Exception ex)
{
State = "Error: " + ex.Message;
}
}
private async void PickPhotoHandler (object state)
{
try
{
MediaFile file = await this.picker.PickPhotoAsync();
State = file.Path;
Image = new BitmapImage();
Image.SetSource (file.GetStream());
}
catch (TaskCanceledException canceled)
{
State = "Canceled";
}
catch (Exception ex)
{
State = "Error: " + ex.Message;
}
}
private void OnPropertyChanged (string name)
{
var changed = PropertyChanged;
if (changed != null)
changed (this, new PropertyChangedEventArgs (name));
}
}
}
|
apache-2.0
|
C#
|
1c72afe8c49bfbe8df6f7670bb21c8f45cbcd271
|
Move fading test to top for convenience
|
EVAST9919/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
|
osu.Game.Tests/Visual/Gameplay/TestSceneFailingLayer.cs
|
osu.Game.Tests/Visual/Gameplay/TestSceneFailingLayer.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailingLayer : OsuTestScene
{
private FailingLayer layer;
[Resolved]
private OsuConfigManager config { get; set; }
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create layer", () => Child = layer = new FailingLayer());
AddStep("enable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, true));
AddUntilStep("layer is visible", () => layer.IsPresent);
}
[Test]
public void TestLayerFading()
{
AddSliderStep("current health", 0.0, 1.0, 1.0, val =>
{
if (layer != null)
layer.Current.Value = val;
});
AddStep("set health to 0.10", () => layer.Current.Value = 0.1);
AddUntilStep("layer fade is visible", () => layer.Child.Alpha > 0.1f);
AddStep("set health to 1", () => layer.Current.Value = 1f);
AddUntilStep("layer fade is invisible", () => !layer.Child.IsPresent);
}
[Test]
public void TestLayerDisabledViaConfig()
{
AddStep("disable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, false));
AddUntilStep("layer is not visible", () => !layer.IsPresent);
}
[Test]
public void TestLayerVisibilityWithAccumulatingProcessor()
{
AddStep("bind accumulating processor", () => layer.BindHealthProcessor(new AccumulatingHealthProcessor(1)));
AddUntilStep("layer is not visible", () => !layer.IsPresent);
}
[Test]
public void TestLayerVisibilityWithDrainingProcessor()
{
AddStep("bind accumulating processor", () => layer.BindHealthProcessor(new DrainingHealthProcessor(1)));
AddWaitStep("wait for potential fade", 10);
AddAssert("layer is still visible", () => layer.IsPresent);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailingLayer : OsuTestScene
{
private FailingLayer layer;
[Resolved]
private OsuConfigManager config { get; set; }
[SetUpSteps]
public void SetUpSteps()
{
AddStep("create layer", () => Child = layer = new FailingLayer());
AddStep("enable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, true));
AddUntilStep("layer is visible", () => layer.IsPresent);
}
[Test]
public void TestLayerDisabledViaConfig()
{
AddStep("disable layer", () => config.Set(OsuSetting.FadePlayfieldWhenHealthLow, false));
AddUntilStep("layer is not visible", () => !layer.IsPresent);
}
[Test]
public void TestLayerVisibilityWithAccumulatingProcessor()
{
AddStep("bind accumulating processor", () => layer.BindHealthProcessor(new AccumulatingHealthProcessor(1)));
AddUntilStep("layer is not visible", () => !layer.IsPresent);
}
[Test]
public void TestLayerVisibilityWithDrainingProcessor()
{
AddStep("bind accumulating processor", () => layer.BindHealthProcessor(new DrainingHealthProcessor(1)));
AddWaitStep("wait for potential fade", 10);
AddAssert("layer is still visible", () => layer.IsPresent);
}
[Test]
public void TestLayerFading()
{
AddSliderStep("current health", 0.0, 1.0, 1.0, val =>
{
if (layer != null)
layer.Current.Value = val;
});
AddStep("set health to 0.10", () => layer.Current.Value = 0.1);
AddUntilStep("layer fade is visible", () => layer.Child.Alpha > 0.1f);
AddStep("set health to 1", () => layer.Current.Value = 1f);
AddUntilStep("layer fade is invisible", () => !layer.Child.IsPresent);
}
}
}
|
mit
|
C#
|
e648aff6c78b176fc820e0c0895c9216e1a8d585
|
Set IPAddress.None when hostname is set in machine inspect
|
mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker,mariotoffia/FluentDocker
|
Ductus.FluentDocker/Executors/Parsers/MachineInspectResponseParser.cs
|
Ductus.FluentDocker/Executors/Parsers/MachineInspectResponseParser.cs
|
using System.Net;
using Ductus.FluentDocker.Model.Containers;
using Ductus.FluentDocker.Model.Machines;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Ductus.FluentDocker.Executors.Parsers
{
public sealed class MachineInspectResponseParser : IProcessResponseParser<MachineConfiguration>
{
public CommandResponse<MachineConfiguration> Response { get; private set; }
public IProcessResponse<MachineConfiguration> Process(ProcessExecutionResult response)
{
if (string.IsNullOrEmpty(response.StdOut))
{
Response = response.ToResponse(false, "No response",
new MachineConfiguration {AuthConfig = new MachineAuthConfig()});
return this;
}
var j = JObject.Parse(response.StdOut);
var str = j["HostOptions"]["AuthOptions"].ToString();
var ip = j["Driver"]["IPAddress"].Value<string>();
var authConfig = JsonConvert.DeserializeObject<MachineAuthConfig>(str);
int memsize = 0;
if (null != j["Driver"]["Memory"])
{
memsize = j["Driver"]["Memory"].Value<int>();
}
if (null != j["Driver"]["MemSize"])
{
memsize = j["Driver"]["MemSize"].Value<int>();
}
string hostname = string.Empty;
if (!IPAddress.TryParse(ip, out var ipaddr))
{
hostname = ip;
ipaddr = IPAddress.None;
}
var config = new MachineConfiguration
{
AuthConfig = authConfig,
IpAddress = ipaddr,
Hostname = hostname,
DriverName = null != j["DriverName"] ? j["DriverName"].Value<string>() : "unknown",
MemorySizeMb = memsize,
Name = null != j["Name"] ? j["Name"].Value<string>() : string.Empty,
RequireTls = j["HostOptions"]["EngineOptions"]["TlsVerify"].Value<bool>(),
StorageSizeMb = j["Driver"]["DiskSize"]?.Value<int>() ?? 0,
CpuCount = j["Driver"]["CPU"]?.Value<int>() ?? 0,
StorePath = j["Driver"]["StorePath"]?.Value<string>() ?? string.Empty
};
Response = response.ToResponse(true, string.Empty, config);
return this;
}
}
}
|
using System.Net;
using Ductus.FluentDocker.Model.Containers;
using Ductus.FluentDocker.Model.Machines;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Ductus.FluentDocker.Executors.Parsers
{
public sealed class MachineInspectResponseParser : IProcessResponseParser<MachineConfiguration>
{
public CommandResponse<MachineConfiguration> Response { get; private set; }
public IProcessResponse<MachineConfiguration> Process(ProcessExecutionResult response)
{
if (string.IsNullOrEmpty(response.StdOut))
{
Response = response.ToResponse(false, "No response",
new MachineConfiguration {AuthConfig = new MachineAuthConfig()});
return this;
}
var j = JObject.Parse(response.StdOut);
var str = j["HostOptions"]["AuthOptions"].ToString();
var ip = j["Driver"]["IPAddress"].Value<string>();
var authConfig = JsonConvert.DeserializeObject<MachineAuthConfig>(str);
int memsize = 0;
if (null != j["Driver"]["Memory"])
{
memsize = j["Driver"]["Memory"].Value<int>();
}
if (null != j["Driver"]["MemSize"])
{
memsize = j["Driver"]["MemSize"].Value<int>();
}
string hostname = null;
if (!IPAddress.TryParse(ip, out var ipaddr))
hostname = ip;
var config = new MachineConfiguration
{
AuthConfig = authConfig,
IpAddress = ipaddr,
Hostname = hostname,
DriverName = null != j["DriverName"] ? j["DriverName"].Value<string>() : "unknown",
MemorySizeMb = memsize,
Name = null != j["Name"] ? j["Name"].Value<string>() : string.Empty,
RequireTls = j["HostOptions"]["EngineOptions"]["TlsVerify"].Value<bool>(),
StorageSizeMb = j["Driver"]["DiskSize"]?.Value<int>() ?? 0,
CpuCount = j["Driver"]["CPU"]?.Value<int>() ?? 0,
StorePath = j["Driver"]["StorePath"]?.Value<string>() ?? string.Empty
};
Response = response.ToResponse(true, string.Empty, config);
return this;
}
}
}
|
apache-2.0
|
C#
|
e88e9ff77c088b4a8a0ebfff9294fb320b713a2b
|
Remove the function specific filter.
|
zacbrown/hiddentreasure-etw-demo
|
hiddentreasure-etw-demo/PowerShellMethodExecution.cs
|
hiddentreasure-etw-demo/PowerShellMethodExecution.cs
|
// Copyright (c) Zac Brown. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using O365.Security.ETW;
namespace hiddentreasure_etw_demo
{
public static class PowerShellMethodExecution
{
public static void Run()
{
// For a more thorough example of how to implement this detection,
// have a look at https://github.com/zacbrown/PowerShellMethodAuditor
var filter = new EventFilter(Filter
.EventIdIs(7937)
.And(UnicodeString.Contains("Payload", "Started")));
filter.OnEvent += (IEventRecord r) => {
var method = r.GetUnicodeString("ContextInfo");
Console.WriteLine($"Method executed:\n{method}");
};
var provider = new Provider("Microsoft-Windows-PowerShell");
provider.AddFilter(filter);
var trace = new UserTrace();
trace.Enable(provider);
// Setup Ctrl-C to call trace.Stop();
Helpers.SetupCtrlC(trace);
// This call is blocking. The thread that calls UserTrace.Start()
// is donating itself to the ETW subsystem to pump events off
// of the buffer.
trace.Start();
}
}
}
|
// Copyright (c) Zac Brown. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using O365.Security.ETW;
namespace hiddentreasure_etw_demo
{
public static class PowerShellMethodExecution
{
public static void Run()
{
// For a more thorough example of how to implement this detection,
// have a look at https://github.com/zacbrown/PowerShellMethodAuditor
var filter = new EventFilter(Filter
.EventIdIs(7937)
.And(UnicodeString.Contains("Payload", "Started"))
.And(UnicodeString.Contains("ContextInfo", "Command Type = Function")));
filter.OnEvent += (IEventRecord r) => {
var method = r.GetUnicodeString("ContextInfo");
Console.WriteLine($"Method executed:\n{method}");
};
var provider = new Provider("Microsoft-Windows-PowerShell");
provider.AddFilter(filter);
var trace = new UserTrace();
trace.Enable(provider);
// Setup Ctrl-C to call trace.Stop();
Helpers.SetupCtrlC(trace);
// This call is blocking. The thread that calls UserTrace.Start()
// is donating itself to the ETW subsystem to pump events off
// of the buffer.
trace.Start();
}
}
}
|
mit
|
C#
|
e014b30915690e751cc91875db926fb4fb657db6
|
Remove on code warning
|
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
|
BTCPayServer/Plugins/Shopify/Models/ShopifySettings.cs
|
BTCPayServer/Plugins/Shopify/Models/ShopifySettings.cs
|
using System;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
namespace BTCPayServer.Plugins.Shopify.Models
{
public class ShopifySettings
{
[Display(Name = "Shop Name")]
public string ShopName { get; set; }
public string ApiKey { get; set; }
public string Password { get; set; }
public bool CredentialsPopulated()
{
return
!string.IsNullOrWhiteSpace(ShopName) &&
!string.IsNullOrWhiteSpace(ApiKey) &&
!string.IsNullOrWhiteSpace(Password);
}
public DateTimeOffset? IntegratedAt { get; set; }
[JsonIgnore]
public string ShopifyUrl
{
get
{
return ShopName?.Contains(".", StringComparison.OrdinalIgnoreCase) is true ? $"https://{ShopName}.myshopify.com" : ShopName;
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
namespace BTCPayServer.Plugins.Shopify.Models
{
public class ShopifySettings
{
[Display(Name = "Shop Name")]
public string ShopName { get; set; }
public string ApiKey { get; set; }
public string Password { get; set; }
public bool CredentialsPopulated()
{
return
!string.IsNullOrWhiteSpace(ShopName) &&
!string.IsNullOrWhiteSpace(ApiKey) &&
!string.IsNullOrWhiteSpace(Password);
}
public DateTimeOffset? IntegratedAt { get; set; }
[JsonIgnore]
public string ShopifyUrl
{
get
{
return ShopName?.Contains(".") is true ? $"https://{ShopName}.myshopify.com" : ShopName;
}
}
}
}
|
mit
|
C#
|
9451c86bb65687b7098ed071acd7a3c3831d8724
|
Fix unreachable code.
|
PixelWaffles/miniblocks-unity3d,ginsederp/miniblocks-unity3d
|
MiniblockRectangleTool.cs
|
MiniblockRectangleTool.cs
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace ginsederp.miniblocks
{
public class MiniblockRectangleTool : MonoBehaviour
{
protected enum eToolType {
add,
remove,
}
[SerializeField] protected eToolType[] toolType;
[SerializeField] protected int[] toolBlockId;
[SerializeField] protected Int3[] toolStart;
[SerializeField] protected Int3[] toolSize;
public Grid3<int> CreateGrid()
{
AssertEqualToolArrayLengths();
Grid3<int> grid = new Grid3<int>();
for( int i = 0; i < toolType.Length; i++ ) {
switch( toolType[i] ) {
case eToolType.add:
grid.Add( toolBlockId[i], toolStart[i], toolSize[i] );
break;
case eToolType.remove:
grid.Remove( toolStart[i], toolSize[i] );
break;
}
}
return grid;
}
protected void AssertEqualToolArrayLengths()
{
if( toolBlockId.Length != toolType.Length || toolStart.Length != toolType.Length || toolSize.Length != toolType.Length ) {
throw new Exception("Array length of tool array variables are not equal.");
}
return;
}
void Start()
{
AssertEqualToolArrayLengths();
return;
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace ginsederp.miniblocks
{
public class MiniblockRectangleTool : MonoBehaviour
{
protected enum eToolType {
add,
remove,
}
[SerializeField] protected eToolType[] toolType;
[SerializeField] protected int[] toolBlockId;
[SerializeField] protected Int3[] toolStart;
[SerializeField] protected Int3[] toolSize;
public Grid3<int> CreateGrid()
{
AssertEqualToolArrayLengths();
Grid3<int> grid = new Grid3<int>();
for( int i = 0; i < toolType.Length; i++ ) {
switch( toolType[i] ) {
case eToolType.add:
grid.Add( toolBlockId[i], toolStart[i], toolSize[i] );
break;
case eToolType.remove:
grid.Remove( toolStart[i], toolSize[i] );
break;
}
}
return grid;
}
protected bool AssertEqualToolArrayLengths()
{
if( toolBlockId.Length != toolType.Length || toolStart.Length != toolType.Length || toolSize.Length != toolType.Length ) {
throw new Exception("Array length of tool array variables are not equal.");
return false;
}
return true;
}
void Start()
{
AssertEqualToolArrayLengths();
return;
}
}
}
|
mit
|
C#
|
d9aef6f813d9666e18dbe313498317fea200dbb4
|
Change label of attribute
|
peppy/osu-new,ppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu
|
osu.Game.Rulesets.Osu/Mods/OsuModApproachCircle.cs
|
osu.Game.Rulesets.Osu/Mods/OsuModApproachCircle.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModApproachCircle : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Approach Circle";
public override string Acronym => "AC";
public override string Description => "Never trust the approach circles...";
public override double ScoreMultiplier => 1;
public override IconUsage? Icon { get; } = FontAwesome.Regular.Circle;
[SettingSource("Easing", "Change the easing type of the approach circles.", 0)]
public Bindable<Easing> BindableEasing { get; } = new Bindable<Easing>();
[SettingSource("Scale the size", "Change the factor of the approach circle scale.", 1)]
public BindableFloat Scale { get; } = new BindableFloat
{
Precision = 0.1f,
MinValue = 2,
MaxValue = 10,
Default = 4,
Value = 4
};
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable =>
{
drawable.ApplyCustomUpdateState += (drawableHitObj, state) =>
{
if (!(drawableHitObj is DrawableOsuHitObject drawableOsuHitObj) || !(drawableHitObj is DrawableHitCircle hitCircle)) return;
var obj = drawableOsuHitObj.HitObject;
hitCircle.BeginAbsoluteSequence(obj.StartTime - obj.TimePreempt, true);
hitCircle.ApproachCircle.ScaleTo(Scale.Value);
hitCircle.ApproachCircle.FadeIn(Math.Min(obj.TimeFadeIn, obj.TimePreempt));
hitCircle.ApproachCircle.ScaleTo(1f, obj.TimePreempt, BindableEasing.Value);
hitCircle.ApproachCircle.Expire(true);
};
});
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModApproachCircle : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Approach Circle";
public override string Acronym => "AC";
public override string Description => "Never trust the approach circles...";
public override double ScoreMultiplier => 1;
public override IconUsage? Icon { get; } = FontAwesome.Regular.Circle;
[SettingSource("Easing", "Change the easing type of the approach circles.", 0)]
public Bindable<Easing> BindableEasing { get; } = new Bindable<Easing>();
[SettingSource("Scale", "Change the factor of the approach circle scale.", 1)]
public BindableFloat Scale { get; } = new BindableFloat
{
Precision = 0.1f,
MinValue = 2,
MaxValue = 10,
Default = 4,
Value = 4,
};
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable =>
{
drawable.ApplyCustomUpdateState += (drawableHitObj, state) =>
{
if (!(drawableHitObj is DrawableOsuHitObject drawableOsuHitObj) || !(drawableHitObj is DrawableHitCircle hitCircle)) return;
var obj = drawableOsuHitObj.HitObject;
hitCircle.BeginAbsoluteSequence(obj.StartTime - obj.TimePreempt, true);
hitCircle.ApproachCircle.ScaleTo(Scale.Value);
hitCircle.ApproachCircle.FadeIn(Math.Min(obj.TimeFadeIn, obj.TimePreempt));
hitCircle.ApproachCircle.ScaleTo(1f, obj.TimePreempt, BindableEasing.Value);
hitCircle.ApproachCircle.Expire(true);
};
});
}
}
}
|
mit
|
C#
|
47d55a0e71c0abed612d9134054d47f1217f70ac
|
Add xmldoc to MidiKeyInput
|
peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
|
osu.Framework/Input/StateChanges/MidiKeyInput.cs
|
osu.Framework/Input/StateChanges/MidiKeyInput.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.States;
namespace osu.Framework.Input.StateChanges
{
/// <summary>
/// Represents an input from a MIDI device.
/// </summary>
public class MidiKeyInput : ButtonInput<MidiKey>
{
/// <summary>
/// A mapping of <see cref="MidiKey"/>s to the velocities they were pressed or released with.
/// </summary>
public readonly IReadOnlyDictionary<MidiKey, byte> Velocities;
/// <summary>
/// Creates a <see cref="MidiKeyInput"/> for a single key state.
/// </summary>
/// <param name="button">The <see cref="MidiKey"/> whose state changed.</param>
/// <param name="velocity">The velocity with which with the input was performed.</param>
/// <param name="isPressed">Whether <paramref name="button"/> was pressed or released.</param>
public MidiKeyInput(MidiKey button, byte velocity, bool isPressed)
: base(button, isPressed)
{
Velocities = new Dictionary<MidiKey, byte> { [button] = velocity };
}
/// <summary>
/// Creates a <see cref="MidiKeyInput"/> from the difference of two <see cref="MidiState"/>s.
/// </summary>
/// <remarks>
/// Buttons that are pressed in <paramref name="previousState"/> and not pressed in <paramref name="currentState"/> will be listed as <see cref="ButtonStateChangeKind.Released"/>.
/// Buttons that are not pressed in <paramref name="previousState"/> and pressed in <paramref name="currentState"/> will be listed as <see cref="ButtonStateChangeKind.Pressed"/>.
/// Key velocities from <paramref name="currentState"/> always take precedence over velocities from <paramref name="previousState"/>.
/// </remarks>
/// <param name="currentState">The newer <see cref="MidiState"/>.</param>
/// <param name="previousState">The older <see cref="MidiState"/>.</param>
public MidiKeyInput(MidiState currentState, MidiState previousState)
: base(currentState.Keys, previousState.Keys)
{
// newer velocities always take precedence
// if the newer midi state doesn't specify a velocity for a key, it will be preserved after Apply()
Velocities = new Dictionary<MidiKey, byte>(currentState.Velocities);
}
/// <summary>
/// Retrieves the <see cref="ButtonStates{TButton}"/> from a <see cref="MidiKeyInput"/>.
/// </summary>
protected override ButtonStates<MidiKey> GetButtonStates(InputState state) => state.Midi.Keys;
public override void Apply(InputState state, IInputStateChangeHandler handler)
{
foreach (var (key, velocity) in Velocities)
state.Midi.Velocities[key] = velocity;
base.Apply(state, handler);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.States;
namespace osu.Framework.Input.StateChanges
{
public class MidiKeyInput : ButtonInput<MidiKey>
{
public readonly IReadOnlyDictionary<MidiKey, byte> Velocities;
public MidiKeyInput(MidiKey button, byte velocity, bool isPressed)
: base(button, isPressed)
{
Velocities = new Dictionary<MidiKey, byte> { [button] = velocity };
}
public MidiKeyInput(MidiState currentState, MidiState previousState)
: base(currentState.Keys, previousState.Keys)
{
// newer velocities always take precedence
// if the newer midi state doesn't specify a velocity for a key, it will be preserved after Apply()
Velocities = new Dictionary<MidiKey, byte>(currentState.Velocities);
}
protected override ButtonStates<MidiKey> GetButtonStates(InputState state) => state.Midi.Keys;
public override void Apply(InputState state, IInputStateChangeHandler handler)
{
foreach (var (key, velocity) in Velocities)
state.Midi.Velocities[key] = velocity;
base.Apply(state, handler);
}
}
}
|
mit
|
C#
|
5e98726b6fb3bb330e0edcbe9be782cf596111d6
|
remove hardcode points spawnManager
|
hay-espacio-en-el-taco/Alerta-Minerva,lordzero0000/Alerta-Minerva
|
Assets/Scripts/monstruo/spawnManager.cs
|
Assets/Scripts/monstruo/spawnManager.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnManager : MonoBehaviour {
public float spawnTime = 3f; // How long between each spawn.
public int limitMonsters = 7; // Maximum of the monsters iin scene
public Transform[] spawnPoints; // An array of the spawn points this enemy can spawn from.
public GameObject[] monsterTypes; // An array of the mounter type prefab to be spawned.
void Start ()
{
// Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
createMonster();
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
/// <summary>
/// Create random type of monster in a random spawn point whole number of monsters are less than limitMonsters
/// </summary>
void Spawn ()
{
if(GameObject.FindGameObjectsWithTag("monster").Length < limitMonsters)
createMonster ();
}
bool createMonster(){
try{
//Select the spawn point to create the enamy
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
//Select the mounterType to create the enamy
int monsterTypeIndex = Random.Range (0, monsterTypes.Length);
// Create an instance of the mounter prefab at the randomly selected spawn point's position and rotation.
Instantiate (monsterTypes[monsterTypeIndex], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
return true;
}
catch{ return false; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnManager : MonoBehaviour {
public float spawnTime = 3f; // How long between each spawn.
public int limitMonsters = 7; // Maximum of the monsters iin scene
public Transform[] spawnPoints; // An array of the spawn points this enemy can spawn from.
public GameObject[] monsterTypes; // An array of the mounter type prefab to be spawned.
void Start ()
{
// Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
createMonster();
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
/// <summary>
/// Create random type of monster in a random spawn point whole number of monsters are less than limitMonsters
/// </summary>
void Spawn ()
{
if(GameObject.FindGameObjectsWithTag("monster").Length < limitMonsters)
createMonster ();
}
bool createMonster(){
try{
//Select the spawn point to create the enamy
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
//Select the mounterType to create the enamy
int monsterTypeIndex = Random.Range (0, monsterTypes.Length);
// Create an instance of the mounter prefab at the randomly selected spawn point's position and rotation.
Instantiate (monsterTypes[monsterTypeIndex], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
Score.addPoints(20);
return true;
}
catch{ return false; }
}
}
|
mit
|
C#
|
f6e191252025a633208180fa11581a94cca2e411
|
Fix format for ets timeline
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Models/Soldier.cs
|
Battery-Commander.Web/Models/Soldier.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BatteryCommander.Web.Models
{
public class Soldier
{
private const double DaysPerYear = 365.2425;
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required, StringLength(50)]
[Display(Name = "Last Name")]
public String LastName { get; set; }
[Required, StringLength(50)]
[Display(Name = "First Name")]
public String FirstName { get; set; }
[StringLength(50), Display(Name = "Middle Name")]
public String MiddleName { get; set; }
[Required]
public Rank Rank { get; set; } = Rank.E1;
[StringLength(12)]
public String DoDId { get; set; }
[DataType(DataType.EmailAddress), StringLength(50)]
public String MilitaryEmail { get; set; }
[DataType(DataType.EmailAddress), StringLength(50)]
public String CivilianEmail { get; set; }
[DataType(DataType.Date), Column(TypeName = "date"), Display(Name = "DOB")]
public DateTime DateOfBirth { get; set; }
public int Age => AgeAsOf(DateTime.Today);
public int AgeAsOf(DateTime date)
{
// They may not have reached their birthday for this year
return (int)((date - DateOfBirth).TotalDays / DaysPerYear);
}
[DataType(DataType.Date), Column(TypeName = "date"), Display(Name = "ETS Date")]
public DateTime? ETSDate { get; set; }
[NotMapped, DisplayFormat(DataFormatString = "{0:%d}d")]
public TimeSpan? TimeTillETS => ETSDate - DateTime.Today;
[Required]
public Gender Gender { get; set; } = Gender.Male;
// public MilitaryEducationLevel EducationLevel { get; set; } = MilitaryEducationLevel.None;
// Status - Active, Inactive
[Required]
public int UnitId { get; set; }
public virtual Unit Unit { get; set; }
// Position
// Security Clearance
// MOS - Duty MOSQ'd?
// ETS Date & Time till ETS
// PEBD
// Date of Rank
public virtual ICollection<APFT> APFTs { get; set; }
public virtual ICollection<ABCP> ABCPs { get; set; }
public override string ToString() => $"{Rank.ShortName()} {LastName} {FirstName} {MiddleName}".ToUpper();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BatteryCommander.Web.Models
{
public class Soldier
{
private const double DaysPerYear = 365.2425;
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required, StringLength(50)]
[Display(Name = "Last Name")]
public String LastName { get; set; }
[Required, StringLength(50)]
[Display(Name = "First Name")]
public String FirstName { get; set; }
[StringLength(50), Display(Name = "Middle Name")]
public String MiddleName { get; set; }
[Required]
public Rank Rank { get; set; } = Rank.E1;
[StringLength(12)]
public String DoDId { get; set; }
[DataType(DataType.EmailAddress), StringLength(50)]
public String MilitaryEmail { get; set; }
[DataType(DataType.EmailAddress), StringLength(50)]
public String CivilianEmail { get; set; }
[DataType(DataType.Date), Column(TypeName = "date"), Display(Name = "DOB")]
public DateTime DateOfBirth { get; set; }
public int Age => AgeAsOf(DateTime.Today);
public int AgeAsOf(DateTime date)
{
// They may not have reached their birthday for this year
return (int)((date - DateOfBirth).TotalDays / DaysPerYear);
}
[DataType(DataType.Date), Column(TypeName = "date"), Display(Name = "ETS Date")]
public DateTime? ETSDate { get; set; }
public TimeSpan? TimeTillETS => ETSDate - DateTime.Today;
[Required]
public Gender Gender { get; set; } = Gender.Male;
// public MilitaryEducationLevel EducationLevel { get; set; } = MilitaryEducationLevel.None;
// Status - Active, Inactive
[Required]
public int UnitId { get; set; }
public virtual Unit Unit { get; set; }
// Position
// Security Clearance
// MOS - Duty MOSQ'd?
// ETS Date & Time till ETS
// PEBD
// Date of Rank
public virtual ICollection<APFT> APFTs { get; set; }
public virtual ICollection<ABCP> ABCPs { get; set; }
public override string ToString() => $"{Rank.ShortName()} {LastName} {FirstName} {MiddleName}".ToUpper();
}
}
|
mit
|
C#
|
56c01c6ef83fa283ed53e34489605d5e370a258a
|
Bump version to 0.6.20 to match milestone
|
juoni/kudu,dev-enthusiast/kudu,juvchan/kudu,uQr/kudu,juoni/kudu,barnyp/kudu,bbauya/kudu,shanselman/kudu,sitereactor/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,shibayan/kudu,oliver-feng/kudu,kenegozi/kudu,mauricionr/kudu,oliver-feng/kudu,EricSten-MSFT/kudu,uQr/kudu,bbauya/kudu,chrisrpatterson/kudu,kali786516/kudu,projectkudu/kudu,sitereactor/kudu,kenegozi/kudu,barnyp/kudu,projectkudu/kudu,projectkudu/kudu,duncansmart/kudu,juvchan/kudu,mauricionr/kudu,shibayan/kudu,MavenRain/kudu,dev-enthusiast/kudu,uQr/kudu,puneet-gupta/kudu,duncansmart/kudu,YOTOV-LIMITED/kudu,barnyp/kudu,puneet-gupta/kudu,uQr/kudu,YOTOV-LIMITED/kudu,sitereactor/kudu,YOTOV-LIMITED/kudu,duncansmart/kudu,juvchan/kudu,shrimpy/kudu,shrimpy/kudu,shanselman/kudu,juoni/kudu,MavenRain/kudu,mauricionr/kudu,barnyp/kudu,bbauya/kudu,juvchan/kudu,shibayan/kudu,chrisrpatterson/kudu,kali786516/kudu,MavenRain/kudu,kali786516/kudu,oliver-feng/kudu,dev-enthusiast/kudu,oliver-feng/kudu,shibayan/kudu,badescuga/kudu,sitereactor/kudu,kenegozi/kudu,WeAreMammoth/kudu-obsolete,sitereactor/kudu,kenegozi/kudu,mauricionr/kudu,puneet-gupta/kudu,juoni/kudu,MavenRain/kudu,WeAreMammoth/kudu-obsolete,bbauya/kudu,chrisrpatterson/kudu,duncansmart/kudu,kali786516/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,shibayan/kudu,badescuga/kudu,projectkudu/kudu,puneet-gupta/kudu,badescuga/kudu,shrimpy/kudu,EricSten-MSFT/kudu,badescuga/kudu,juvchan/kudu,chrisrpatterson/kudu,dev-enthusiast/kudu,WeAreMammoth/kudu-obsolete,shrimpy/kudu,puneet-gupta/kudu,shanselman/kudu,projectkudu/kudu,EricSten-MSFT/kudu
|
Common/CommonAssemblyInfo.cs
|
Common/CommonAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyVersion("0.6.20.0")]
[assembly: AssemblyFileVersion("0.6.20.0")]
|
using System.Reflection;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyVersion("0.6.0.0")]
[assembly: AssemblyFileVersion("0.6.0.0")]
|
apache-2.0
|
C#
|
38689df583bd233175e3a7843fafb52257b75409
|
Fix axis value potentially getting stuck non-zero
|
peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework
|
osu.Framework/Input/StateChanges/JoystickAxisInput.cs
|
osu.Framework/Input/StateChanges/JoystickAxisInput.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osu.Framework.Utils;
namespace osu.Framework.Input.StateChanges
{
public class JoystickAxisInput : IInput
{
/// <summary>
/// List of joystick axes.
/// </summary>
public readonly IEnumerable<JoystickAxis> Axes;
public JoystickAxisInput(JoystickAxis axis)
: this(axis.Yield())
{
}
public JoystickAxisInput(IEnumerable<JoystickAxis> axes)
{
if (axes.Count() > JoystickState.MAX_AXES)
throw new ArgumentException($"The length of the provided axes collection ({axes.Count()}) exceeds the maximum length ({JoystickState.MAX_AXES})", nameof(axes));
Axes = axes;
}
public void Apply(InputState state, IInputStateChangeHandler handler)
{
foreach (var a in Axes)
{
float oldValue = state.Joystick.AxesValues[(int)a.Source];
// Not enough movement, don't fire event (unless returning to zero).
if (oldValue == a.Value || (a.Value != 0 && Precision.AlmostEquals(oldValue, a.Value)))
continue;
state.Joystick.AxesValues[(int)a.Source] = a.Value;
handler.HandleInputStateChange(new JoystickAxisChangeEvent(state, this, a, oldValue));
}
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osu.Framework.Utils;
namespace osu.Framework.Input.StateChanges
{
public class JoystickAxisInput : IInput
{
/// <summary>
/// List of joystick axes.
/// </summary>
public readonly IEnumerable<JoystickAxis> Axes;
public JoystickAxisInput(JoystickAxis axis)
: this(axis.Yield())
{
}
public JoystickAxisInput(IEnumerable<JoystickAxis> axes)
{
if (axes.Count() > JoystickState.MAX_AXES)
throw new ArgumentException($"The length of the provided axes collection ({axes.Count()}) exceeds the maximum length ({JoystickState.MAX_AXES})", nameof(axes));
Axes = axes;
}
public void Apply(InputState state, IInputStateChangeHandler handler)
{
foreach (var a in Axes)
{
// Not enough movement, don't fire event
if (Precision.AlmostEquals(state.Joystick.AxesValues[(int)a.Source], a.Value))
continue;
var lastValue = state.Joystick.AxesValues[(int)a.Source];
state.Joystick.AxesValues[(int)a.Source] = a.Value;
handler.HandleInputStateChange(new JoystickAxisChangeEvent(state, this, a, lastValue));
}
}
}
}
|
mit
|
C#
|
d8ec9d71363bf5fc8c54bfd660cf7c069b918572
|
Update RetryOptions.cs
|
tjscience/RoboSharp,tjscience/RoboSharp
|
RoboSharp/RetryOptions.cs
|
RoboSharp/RetryOptions.cs
|
using System.Text;
namespace RoboSharp
{
public class RetryOptions
{
internal const string RETRY_COUNT = "/R:{0} ";
internal const string RETRY_WAIT_TIME = "/W:{0} ";
internal const string SAVE_TO_REGISTRY = "/REG ";
internal const string WAIT_FOR_SHARENAMES = "/TBD ";
private int retryCount = 0;
private int retryWaitTime = 30;
/// <summary>
/// Specifies the number of retries N on failed copies (default is 0).
/// [/R:N]
/// </summary>
public int RetryCount
{
get { return retryCount; }
set { retryCount = value; }
}
/// <summary>
/// Specifies the wait time N in seconds between retries (default is 30).
/// [/W:N]
/// </summary>
public int RetryWaitTime
{
get { return retryWaitTime; }
set { retryWaitTime = value; }
}
/// <summary>
/// Saves RetryCount and RetryWaitTime in the Registry as default settings.
/// [/REG]
/// </summary>
public bool SaveToRegistry { get; set; }
/// <summary>
/// Wait for sharenames to be defined.
/// [/TBD]
/// </summary>
public bool WaitForSharenames { get; set; }
internal string Parse()
{
var options = new StringBuilder();
options.Append(string.Format(RETRY_COUNT, RetryCount));
options.Append(string.Format(RETRY_WAIT_TIME, RetryWaitTime));
if (SaveToRegistry)
options.Append(SAVE_TO_REGISTRY);
if (WaitForSharenames)
options.Append(WAIT_FOR_SHARENAMES);
return options.ToString();
}
}
}
|
using System.Text;
namespace RoboSharp
{
public class RetryOptions
{
internal const string RETRY_COUNT = "/R:{0} ";
internal const string RETRY_WAIT_TIME = "/W:{0} ";
internal const string SAVE_TO_REGISTRY = "/REG ";
internal const string WAIT_FOR_SHARENAMES = "/TBD ";
private int retryCount = 2;
private int retryWaitTime = 2;
/// <summary>
/// Specifies the number of retries N on failed copies (default is 0).
/// [/R:N]
/// </summary>
public int RetryCount
{
get { return retryCount; }
set { retryCount = value; }
}
/// <summary>
/// Specifies the wait time N in seconds between retries (default is 30).
/// [/W:N]
/// </summary>
public int RetryWaitTime
{
get { return retryWaitTime; }
set { retryWaitTime = value; }
}
/// <summary>
/// Saves RetryCount and RetryWaitTime in the Registry as default settings.
/// [/REG]
/// </summary>
public bool SaveToRegistry { get; set; }
/// <summary>
/// Wait for sharenames to be defined.
/// [/TBD]
/// </summary>
public bool WaitForSharenames { get; set; }
internal string Parse()
{
var options = new StringBuilder();
options.Append(string.Format(RETRY_COUNT, RetryCount));
options.Append(string.Format(RETRY_WAIT_TIME, RetryWaitTime));
if (SaveToRegistry)
options.Append(SAVE_TO_REGISTRY);
if (WaitForSharenames)
options.Append(WAIT_FOR_SHARENAMES);
return options.ToString();
}
}
}
|
mit
|
C#
|
68b70c581b6a42d8a21a21dbd30cd279e0c22568
|
increase version
|
tynor88/Topshelf.SimpleInjector
|
Source/AssemblyVersion.cs
|
Source/AssemblyVersion.cs
|
using System.Reflection;
[assembly: AssemblyVersion("0.1.3.1")]
[assembly: AssemblyFileVersion("0.1.3.1")]
|
using System.Reflection;
[assembly: AssemblyVersion("0.1.3.0")]
[assembly: AssemblyFileVersion("0.1.3.0")]
|
mit
|
C#
|
f007b6c65df3e79c2a55f7d26a7196d862898453
|
Use SetEquals instead.
|
mono/msbuild,mono/msbuild,mono/msbuild,mono/msbuild
|
src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryTaskInfo.cs
|
src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryTaskInfo.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Build.Tasks
{
internal sealed class RoslynCodeTaskFactoryTaskInfo : IEquatable<RoslynCodeTaskFactoryTaskInfo>
{
/// <summary>
/// Gets or sets the code language of the task.
/// </summary>
public string CodeLanguage { get; set; }
/// <summary>
/// Gets or sets the <see cref="RoslynCodeTaskFactoryCodeType"/> of the task.
/// </summary>
public RoslynCodeTaskFactoryCodeType CodeType { get; set; }
/// <summary>
/// Gets or sets the name of the task.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets a <see cref="ISet{String}"/> of namespaces to use.
/// </summary>
public ISet<string> Namespaces { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets an <see cref="ISet{String}"/> of assembly references.
/// </summary>
public ISet<string> References { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the source code of the assembly.
/// </summary>
public string SourceCode { get; set; }
/// <inheritdoc cref="IEquatable{T}.Equals(T)"/>
public bool Equals(RoslynCodeTaskFactoryTaskInfo other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return String.Equals(SourceCode, other.SourceCode, StringComparison.Ordinal) && References.SetEquals(other.References);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
return Equals(obj as RoslynCodeTaskFactoryTaskInfo);
}
public override int GetHashCode()
{
// This is good enough to avoid most collisions, no need to hash References
return SourceCode.GetHashCode();
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Build.Tasks
{
internal sealed class RoslynCodeTaskFactoryTaskInfo : IEquatable<RoslynCodeTaskFactoryTaskInfo>
{
/// <summary>
/// Gets or sets the code language of the task.
/// </summary>
public string CodeLanguage { get; set; }
/// <summary>
/// Gets or sets the <see cref="RoslynCodeTaskFactoryCodeType"/> of the task.
/// </summary>
public RoslynCodeTaskFactoryCodeType CodeType { get; set; }
/// <summary>
/// Gets or sets the name of the task.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets a <see cref="ISet{String}"/> of namespaces to use.
/// </summary>
public ISet<string> Namespaces { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets an <see cref="ISet{String}"/> of assembly references.
/// </summary>
public ISet<string> References { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the source code of the assembly.
/// </summary>
public string SourceCode { get; set; }
/// <inheritdoc cref="IEquatable{T}.Equals(T)"/>
public bool Equals(RoslynCodeTaskFactoryTaskInfo other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return String.Equals(SourceCode, other.SourceCode, StringComparison.Ordinal) && References.OrderBy(s => s).SequenceEqual(other.References.OrderBy(s => s));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
return Equals(obj as RoslynCodeTaskFactoryTaskInfo);
}
public override int GetHashCode()
{
// This is good enough to avoid most collisions, no need to hash References
return SourceCode.GetHashCode();
}
}
}
|
mit
|
C#
|
305dd58365cf44e4c74ebb998be95f5ba51b3cc8
|
fix version cache key in msbuild task
|
asbjornu/GitVersion,GitTools/GitVersion,Philo/GitVersion,ParticularLabs/GitVersion,dpurge/GitVersion,FireHost/GitVersion,MarkZuber/GitVersion,RaphHaddad/GitVersion,dazinator/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,DanielRose/GitVersion,onovotny/GitVersion,asbjornu/GitVersion,JakeGinnivan/GitVersion,distantcam/GitVersion,TomGillen/GitVersion,Philo/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,dpurge/GitVersion,pascalberger/GitVersion,TomGillen/GitVersion,FireHost/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,RaphHaddad/GitVersion,pascalberger/GitVersion,JakeGinnivan/GitVersion,openkas/GitVersion,dpurge/GitVersion,DanielRose/GitVersion,alexhardwicke/GitVersion,ParticularLabs/GitVersion,openkas/GitVersion,distantcam/GitVersion,JakeGinnivan/GitVersion,dpurge/GitVersion,alexhardwicke/GitVersion,JakeGinnivan/GitVersion,DanielRose/GitVersion,onovotny/GitVersion,GitTools/GitVersion,pascalberger/GitVersion,ermshiperete/GitVersion,MarkZuber/GitVersion,onovotny/GitVersion
|
src/GitVersionTask/VersionAndBranchFinder.cs
|
src/GitVersionTask/VersionAndBranchFinder.cs
|
using System;
using System.Collections.Generic;
using GitVersion;
using GitVersion.Helpers;
public static class VersionAndBranchFinder
{
static Dictionary<string, CachedVersion> versionCacheVersions = new Dictionary<string, CachedVersion>();
public static bool TryGetVersion(string directory, out VersionVariables versionVariables, bool noFetch, Authentication authentication, IFileSystem fileSystem)
{
try
{
versionVariables = GetVersion(directory, authentication, noFetch, fileSystem);
return true;
}
catch (Exception ex)
{
Logger.WriteWarning("Could not determine assembly version: " + ex.Message);
versionVariables = null;
return false;
}
}
public static VersionVariables GetVersion(string directory, Authentication authentication, bool noFetch, IFileSystem fileSystem)
{
var gitDir = GitDirFinder.TreeWalkForDotGitDir(directory);
using (var repo = RepositoryLoader.GetRepo(gitDir))
{
var ticks = DirectoryDateFinder.GetLastDirectoryWrite(gitDir);
var key = string.Format("{0}:{1}:{2}",gitDir, repo.Head.CanonicalName, repo.Head.Tip.Sha);
Logger.WriteInfo("CacheKey: " + key );
CachedVersion result;
if (versionCacheVersions.TryGetValue(key, out result))
{
if (result.Timestamp != ticks)
{
Logger.WriteInfo(string.Format("Change detected. Flushing cache. OldTimeStamp: {0}. NewTimeStamp: {1}", result.Timestamp, ticks));
result.VersionVariables = ExecuteCore.ExecuteGitVersion(fileSystem, null, null, authentication, null, noFetch, directory, null);
result.Timestamp = ticks;
}
Logger.WriteInfo("Returning version from cache");
return result.VersionVariables;
}
Logger.WriteInfo("Version not in cache. Calculating version.");
return (versionCacheVersions[key] = new CachedVersion
{
VersionVariables = ExecuteCore.ExecuteGitVersion(fileSystem, null, null, authentication, null, noFetch, directory, null),
Timestamp = ticks
}).VersionVariables;
}
}
}
|
using System;
using System.Collections.Generic;
using GitVersion;
using GitVersion.Helpers;
public static class VersionAndBranchFinder
{
static Dictionary<string, CachedVersion> versionCacheVersions = new Dictionary<string, CachedVersion>();
public static bool TryGetVersion(string directory, out VersionVariables versionVariables, bool noFetch, Authentication authentication, IFileSystem fileSystem)
{
try
{
versionVariables = GetVersion(directory, authentication, noFetch, fileSystem);
return true;
}
catch (Exception ex)
{
Logger.WriteWarning("Could not determine assembly version: " + ex.Message);
versionVariables = null;
return false;
}
}
public static VersionVariables GetVersion(string directory, Authentication authentication, bool noFetch, IFileSystem fileSystem)
{
var gitDir = GitDirFinder.TreeWalkForDotGitDir(directory);
using (var repo = RepositoryLoader.GetRepo(gitDir))
{
var ticks = DirectoryDateFinder.GetLastDirectoryWrite(directory);
var key = string.Format("{0}:{1}:{2}", repo.Head.CanonicalName, repo.Head.Tip.Sha, ticks);
CachedVersion result;
if (versionCacheVersions.TryGetValue(key, out result))
{
if (result.Timestamp != ticks)
{
Logger.WriteInfo("Change detected. flushing cache.");
result.VersionVariables = ExecuteCore.ExecuteGitVersion(fileSystem, null, null, authentication, null, noFetch, directory, null);
}
return result.VersionVariables;
}
Logger.WriteInfo("Version not in cache. Calculating version.");
return (versionCacheVersions[key] = new CachedVersion
{
VersionVariables = ExecuteCore.ExecuteGitVersion(fileSystem, null, null, authentication, null, noFetch, directory, null),
Timestamp = ticks
}).VersionVariables;
}
}
}
|
mit
|
C#
|
3acded0db62ed35a7c0b5d81308b8d1cd9e18594
|
move pretext to all lowercase
|
Inumedia/SlackAPI,vampireneo/SlackAPI,smanabat/SlackAPI,Jaykul/SlackAPI
|
Attachment.cs
|
Attachment.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
public class Attachment
{
public string pretext;
public string text;
public string fallback;
public string color;
public Field[] fields;
public string image_url;
public string thumb_url;
public string[] mrkdwn_in;
public string title;
///I have absolutely no idea what goes on in here.
}
public class Field{
public string title;
public string value;
public string @short;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
public class Attachment
{
public string Pretext;
public string text;
public string fallback;
public string color;
public Field[] fields;
public string image_url;
public string thumb_url;
public string[] mrkdwn_in;
public string title;
///I have absolutely no idea what goes on in here.
}
public class Field{
public string title;
public string value;
public string @short;
}
}
|
mit
|
C#
|
a300eb4ff6c1343ae591659143a25226b30234ec
|
Use recotd for FileMetadata
|
nikeee/HolzShots
|
src/HolzShots.Core/IO/Naming/FileMetadata.cs
|
src/HolzShots.Core/IO/Naming/FileMetadata.cs
|
using System;
using System.Drawing;
namespace HolzShots.IO.Naming
{
public record FileMetadata(DateTime Timestamp, MemSize FileSize, Size Dimensions)
{
public static FileMetadata DemoMetadata { get; } = new FileMetadata(new DateTime(2010, 6, 14, 21, 47, 33), new MemSize(2, MemSizeUnit.MibiByte), new Size(800, 600));
}
}
|
using System;
using System.Drawing;
namespace HolzShots.IO.Naming
{
public struct FileMetadata : IEquatable<FileMetadata>
{
public static FileMetadata DemoMetadata { get; } = new FileMetadata(new DateTime(2010, 6, 14, 21, 47, 33), new MemSize(2, MemSizeUnit.MibiByte), new Size(800, 600));
public DateTime Timestamp { get; }
public MemSize FileSize { get; }
public Size Dimensions { get; }
public FileMetadata(DateTime timestamp, MemSize fileSize, Size dimensions)
{
Timestamp = timestamp;
FileSize = fileSize;
Dimensions = dimensions;
}
public override bool Equals(object? obj) => obj is FileMetadata m && m == this;
public bool Equals(FileMetadata other) => other == this;
public override int GetHashCode() => HashCode.Combine(Timestamp, FileSize, Dimensions);
public static bool operator ==(FileMetadata left, FileMetadata right) => left.FileSize == right.FileSize && left.Timestamp == right.Timestamp && left.Dimensions == right.Dimensions;
public static bool operator !=(FileMetadata left, FileMetadata right) => !(left == right);
}
}
|
agpl-3.0
|
C#
|
f7a451ed8221efa1ef2ad4f84b955edfca73ecec
|
Update test case.
|
2yangk23/osu,naoey/osu,Frontear/osuKyzer,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,johnneijzen/osu,naoey/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,DrabWeb/osu,2yangk23/osu,ZLima12/osu,naoey/osu,johnneijzen/osu,Nabile-Rahmani/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu,ppy/osu,Drezi126/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,Damnae/osu,ppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu
|
osu.Desktop.VisualTests/Tests/TestCaseUserProfile.cs
|
osu.Desktop.VisualTests/Tests/TestCaseUserProfile.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Overlays;
using osu.Game.Users;
namespace osu.Desktop.VisualTests.Tests
{
internal class TestCaseUserProfile : TestCase
{
public override string Description => "Tests user's profile page.";
public override void Reset()
{
base.Reset();
var userpage = new UserProfile(new User
{
Username = @"peppy",
Id = 2,
Country = new Country { FullName = @"Australia", FlagName = @"AU" },
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg"
})
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Horizontal = 50 },
State = Visibility.Visible
};
Add(userpage);
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Overlays;
using osu.Game.Users;
namespace osu.Desktop.VisualTests.Tests
{
internal class TestCaseUserProfile : TestCase
{
public override string Description => "Tests user's profile page.";
public override void Reset()
{
base.Reset();
var userpage = new UserProfile(new User
{
Username = @"peppy",
Id = 2,
Country = new Country { FlagName = @"AU" },
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg"
})
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 800,
Height = 500
};
Add(userpage);
AddStep("Toggle", userpage.ToggleVisibility);
}
}
}
|
mit
|
C#
|
cfe7d2f184915ace483fd7c6ac30850d9e3fbd21
|
Fix usings.
|
RedNesto/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,peppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,paparony03/osu-framework,Tom94/osu-framework,default0/osu-framework,naoey/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,default0/osu-framework,ppy/osu-framework
|
osu.Framework/Graphics/Transforms/TransformColour.cs
|
osu.Framework/Graphics/Transforms/TransformColour.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.MathUtils;
using OpenTK.Graphics;
namespace osu.Framework.Graphics.Transforms
{
/// <summary>
/// Transforms colour value in linear colour space.
/// </summary>
public class TransformColour : Transform<Color4>
{
/// <summary>
/// Current value of the transformed colour in linear colour space.
/// </summary>
protected override Color4 CurrentValue
{
get
{
double time = Time?.Current ?? 0;
if (time < StartTime) return StartValue;
if (time >= EndTime) return EndValue;
return Interpolation.ValueAt(time, StartValue, EndValue, StartTime, EndTime, Easing);
}
}
public override void Apply(Drawable d)
{
base.Apply(d);
d.Colour = CurrentValue;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.MathUtils;
using OpenTK.Graphics;
using osu.Framework.Graphics.Colour;
namespace osu.Framework.Graphics.Transforms
{
/// <summary>
/// Transforms colour value in linear colour space.
/// </summary>
public class TransformColour : Transform<Color4>
{
/// <summary>
/// Current value of the transformed colour in linear colour space.
/// </summary>
protected override Color4 CurrentValue
{
get
{
double time = Time?.Current ?? 0;
if (time < StartTime) return StartValue;
if (time >= EndTime) return EndValue;
return Interpolation.ValueAt(time, StartValue, EndValue, StartTime, EndTime, Easing);
}
}
public override void Apply(Drawable d)
{
base.Apply(d);
d.Colour = CurrentValue;
}
}
}
|
mit
|
C#
|
e8218bc47a1f6d6efab03c040207d3bbcc190753
|
Add empty type
|
DMagic1/Orbital-Science,Kerbas-ad-astra/Orbital-Science
|
Source/DMScienceContainer.cs
|
Source/DMScienceContainer.cs
|
#region license
/* DMagic Orbital Science - DMScienceContainer
* Object to store experiment properties
*
* Copyright (c) 2014, David Grandy <david.grandy@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#endregion
namespace DMagic
{
internal class DMScienceContainer
{
internal int sitMask, bioMask;
internal DMScienceType type;
internal ScienceExperiment exp;
internal string sciPart, agent;
internal DMScienceContainer(ScienceExperiment sciExp, int sciSitMask, int sciBioMask, DMScienceType Type, string sciPartID, string agentName)
{
sitMask = sciSitMask;
bioMask = sciBioMask;
exp = sciExp;
sciPart = sciPartID;
agent = agentName;
type = Type;
}
}
internal enum DMScienceType
{
None = 0,
Surface = 1,
Aerial = 2,
Space = 4,
Biological = 8,
}
}
|
#region license
/* DMagic Orbital Science - DMScienceContainer
* Object to store experiment properties
*
* Copyright (c) 2014, David Grandy <david.grandy@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#endregion
namespace DMagic
{
internal class DMScienceContainer
{
internal int sitMask, bioMask;
internal DMScienceType type;
internal ScienceExperiment exp;
internal string sciPart, agent;
internal DMScienceContainer(ScienceExperiment sciExp, int sciSitMask, int sciBioMask, DMScienceType Type, string sciPartID, string agentName)
{
sitMask = sciSitMask;
bioMask = sciBioMask;
exp = sciExp;
sciPart = sciPartID;
agent = agentName;
type = Type;
}
}
internal enum DMScienceType
{
Surface = 1,
Aerial = 2,
Space = 4,
Biological = 8,
}
}
|
bsd-3-clause
|
C#
|
4ed65a6a16c431c58423ae7888933c133dd47528
|
Switch to 2.6.1
|
davidlee80/SharpDX-1,waltdestler/SharpDX,jwollen/SharpDX,TigerKO/SharpDX,fmarrabal/SharpDX,TigerKO/SharpDX,Ixonos-USA/SharpDX,dazerdude/SharpDX,davidlee80/SharpDX-1,waltdestler/SharpDX,TigerKO/SharpDX,VirusFree/SharpDX,waltdestler/SharpDX,dazerdude/SharpDX,weltkante/SharpDX,jwollen/SharpDX,manu-silicon/SharpDX,TigerKO/SharpDX,manu-silicon/SharpDX,davidlee80/SharpDX-1,RobyDX/SharpDX,PavelBrokhman/SharpDX,Ixonos-USA/SharpDX,mrvux/SharpDX,VirusFree/SharpDX,dazerdude/SharpDX,andrewst/SharpDX,sharpdx/SharpDX,jwollen/SharpDX,PavelBrokhman/SharpDX,Ixonos-USA/SharpDX,sharpdx/SharpDX,VirusFree/SharpDX,Ixonos-USA/SharpDX,TechPriest/SharpDX,weltkante/SharpDX,davidlee80/SharpDX-1,dazerdude/SharpDX,andrewst/SharpDX,weltkante/SharpDX,TechPriest/SharpDX,fmarrabal/SharpDX,RobyDX/SharpDX,manu-silicon/SharpDX,jwollen/SharpDX,mrvux/SharpDX,TechPriest/SharpDX,waltdestler/SharpDX,TechPriest/SharpDX,RobyDX/SharpDX,sharpdx/SharpDX,mrvux/SharpDX,fmarrabal/SharpDX,VirusFree/SharpDX,andrewst/SharpDX,manu-silicon/SharpDX,fmarrabal/SharpDX,PavelBrokhman/SharpDX,weltkante/SharpDX,RobyDX/SharpDX,PavelBrokhman/SharpDX
|
Source/SharedAssemblyInfo.cs
|
Source/SharedAssemblyInfo.cs
|
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("2.6.1")]
[assembly:AssemblyFileVersion("2.6.1")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)]
[assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
|
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly:AssemblyCompany("Alexandre Mutel")]
[assembly:AssemblyCopyright("Copyright © 2010-2013 Alexandre Mutel")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly:AssemblyVersion("2.6.0")]
[assembly:AssemblyFileVersion("2.6.0")]
[assembly: NeutralResourcesLanguage("en-us")]
#if DEBUG
[assembly:AssemblyConfiguration("Debug")]
#else
[assembly:AssemblyConfiguration("Release")]
#endif
[assembly:ComVisible(false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when public and interface: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when struct: renaming", Exclude = false, ApplyToMembers = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.*: INotifyPropertyChanged heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: forced rename", Exclude = false)]
[assembly: Obfuscation(Feature = "Apply to type SharpDX.* when enum: enum values pruning", Exclude = false)]
[assembly: Obfuscation(Feature = "legacy xml serialization heuristics", Exclude = true)]
[assembly: Obfuscation(Feature = "ignore InternalsVisibleToAttribute", Exclude = false)]
|
mit
|
C#
|
e5a42b54e1a1c815da10282e32f1cf58a5ac5141
|
update version to v0.6.3
|
0x1mason/GribApi.NET
|
src/GribApi.NET/Grib.Api/Properties/AssemblyInfo.cs
|
src/GribApi.NET/Grib.Api/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("Grib.Api.dll")]
[assembly: AssemblyDescription("A powerful .NET library for reading and writing GRIB 1 and 2 files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eric Millin")]
[assembly: AssemblyProduct("GribApi.NET")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("90b4caeb-dfee-4cf5-88cb-0716d4575612")]
// 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.6.3.0")]
[assembly: AssemblyFileVersion("0.6.3.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Grib.Api.dll")]
[assembly: AssemblyDescription("A powerful .NET library for reading and writing GRIB 1 and 2 files.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eric Millin")]
[assembly: AssemblyProduct("GribApi.NET")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("90b4caeb-dfee-4cf5-88cb-0716d4575612")]
// 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.6.2.0")]
[assembly: AssemblyFileVersion("0.6.2.0")]
|
apache-2.0
|
C#
|
3fbcf4eef92fd5fcc007dc4da4be7ed20b0a165d
|
Improve inline data for existing usecases
|
ardalis/GuardClauses
|
src/GuardClauses.UnitTests/GuardAgainsOutOfRange.cs
|
src/GuardClauses.UnitTests/GuardAgainsOutOfRange.cs
|
using Ardalis.GuardClauses;
using System;
using Xunit;
namespace GuardClauses.UnitTests
{
public class GuardAgainsOutOfRange
{
[Theory]
[InlineData(1, 1, 3)]
[InlineData(2, 1, 3)]
[InlineData(3, 1, 3)]
public void DoesNothingGivenInRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo)
{
Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo);
}
[Theory]
[InlineData(1, 1, 3)]
[InlineData(2, 1, 3)]
[InlineData(3, 1, 3)]
public void DoesNothingGivenInRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo)
{
Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo);
}
[Theory]
[InlineData(-1, 1, 3)]
[InlineData(0, 1, 3)]
[InlineData(4, 1, 3)]
public void ThrowsGivenOutOfRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo));
}
[Theory]
[InlineData(-1, 1, 3)]
[InlineData(0, 1, 3)]
[InlineData(4, 1, 3)]
public void ThrowsGivenOutOfRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo));
}
}
}
|
using Ardalis.GuardClauses;
using System;
using Xunit;
namespace GuardClauses.UnitTests
{
public class GuardAgainsOutOfRange
{
[Theory]
[InlineData(1, 1, 5)]
[InlineData(2, 1, 5)]
[InlineData(3, 1, 5)]
public void DoesNothingGivenInRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo)
{
Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo);
}
[Theory]
[InlineData(1, 1, 5)]
[InlineData(2, 1, 5)]
[InlineData(3, 1, 5)]
public void DoesNothingGivenInRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo)
{
Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo);
}
[Theory]
[InlineData(-1, 1, 5)]
[InlineData(0, 1, 5)]
[InlineData(6, 1, 5)]
public void ThrowsGivenOutOfRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo));
}
[Theory]
[InlineData(-1, 1, 5)]
[InlineData(0, 1, 5)]
[InlineData(6, 1, 5)]
public void ThrowsGivenOutOfRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo));
}
}
}
|
mit
|
C#
|
860be98c65a0d3fa9cb5574c2e32a68a7aabc728
|
fix spelling
|
Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache
|
NuCache/Controllers/ManageController.cs
|
NuCache/Controllers/ManageController.cs
|
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NuCache.Infrastructure.Spark;
using NuCache.Models;
namespace NuCache.Controllers
{
public class ManageController : ApiController
{
private readonly SparkResponseFactory _responseFactory;
private readonly IPackageCache _packageCache;
public ManageController(SparkResponseFactory responseFactory, IPackageCache packageCache)
{
_responseFactory = responseFactory;
_packageCache = packageCache;
}
public HttpResponseMessage GetIndex()
{
var model = new ManageViewModel
{
Packages = _packageCache.GetAllPackages()
};
return _responseFactory.From(model);
}
public HttpResponseMessage DeletePackage(string name, string version)
{
_packageCache.Remove(new PackageID(name, version));
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(string.Format("Deleted {0}, v{1}", name, version))
};
}
}
}
|
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NuCache.Infrastructure.Spark;
using NuCache.Models;
namespace NuCache.Controllers
{
public class ManageController : ApiController
{
private readonly SparkResponseFactory _responseFactory;
private readonly IPackageCache _packageCache;
public ManageController(SparkResponseFactory responseFactory, IPackageCache packageCache)
{
_responseFactory = responseFactory;
_packageCache = packageCache;
}
public HttpResponseMessage GetIndex()
{
var model = new ManageViewModel
{
Packages = _packageCache.GetAllPackages()
};
return _responseFactory.From(model);
}
public HttpResponseMessage DeletePacakge(string name, string version)
{
_packageCache.Remove(new PackageID(name, version));
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(string.Format("Deleted {0}, v{1}", name, version))
};
}
}
}
|
lgpl-2.1
|
C#
|
7f2ee8fe457de32f96db7eada7c9aa3488a9414e
|
Fix employee achievements not displayed in EmployeeDirectory after AchievementTypes table was added
|
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
|
R7.University.EmployeeDirectory/Queries/TeachersQuery.cs
|
R7.University.EmployeeDirectory/Queries/TeachersQuery.cs
|
//
// TeachersQuery.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;
using R7.University.Queries;
namespace R7.University.EmployeeDirectory.Queries
{
internal class TeachersQuery: QueryBase
{
public TeachersQuery (IModelContext modelContext): base (modelContext)
{
}
public IList<EmployeeInfo> List ()
{
return ModelContext.Query<EmployeeInfo> ()
.Include (e => e.Positions)
.Include (e => e.Positions.Select (op => op.Position))
.Include (e => e.Positions.Select (op => op.Division))
.Include (e => e.Disciplines)
.Include (e => e.Achievements)
.Include (e => e.Achievements.Select (ea => ea.Achievement))
.Include (e => e.Achievements.Select (ea => ea.Achievement.AchievementType))
.Include (e => e.Achievements.Select (ea => ea.AchievementType))
.Where (e => e.Positions.Any (op => op.Position.IsTeacher))
.ToList ();
}
}
}
|
//
// TeachersQuery.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;
using R7.University.Queries;
namespace R7.University.EmployeeDirectory.Queries
{
internal class TeachersQuery: QueryBase
{
public TeachersQuery (IModelContext modelContext): base (modelContext)
{
}
public IList<EmployeeInfo> List ()
{
return ModelContext.Query<EmployeeInfo> ()
.Include (e => e.Positions)
.Include (e => e.Positions.Select (op => op.Position))
.Include (e => e.Positions.Select (op => op.Division))
.Include (e => e.Disciplines)
.Include (e => e.Achievements)
.Include (e => e.Achievements.Select (ea => ea.Achievement))
.Where (e => e.Positions.Any (op => op.Position.IsTeacher))
.ToList ();
}
}
}
|
agpl-3.0
|
C#
|
3d52ad7503b4f870d9fca703002c11f406e99611
|
Allow ReleaseNotesDialog to handle raw HTML properly
|
gmartin7/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso
|
SIL.Windows.Forms/ReleaseNotes/ShowReleaseNotesDialog.cs
|
SIL.Windows.Forms/ReleaseNotes/ShowReleaseNotesDialog.cs
|
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MarkdownDeep;
using SIL.IO;
namespace SIL.Windows.Forms.ReleaseNotes
{
/// <summary>
/// Shows a dialog for release notes; accepts html and markdown
/// </summary>
/// <remarks>
/// Despite the name, this dialog is generally useful for displaying
/// formatted information, not just for release notes.
/// </remarks>
public partial class ShowReleaseNotesDialog : Form
{
private readonly string _path;
private TempFile _temp;
private readonly Icon _icon;
public bool ApplyMarkdown { get; set;}
public ShowReleaseNotesDialog(Icon icon, string path, bool applyMarkdown = true)
{
_path = path;
_icon = icon;
ApplyMarkdown = applyMarkdown;
InitializeComponent();
}
private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
{
string contents = File.ReadAllText(_path);
// Disposed of during dialog Dispose()
_temp = TempFile.WithExtension("htm");
if (ApplyMarkdown)
{
var md = new Markdown();
File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents)));
}
else if (contents.Contains("<html>") && contents.Contains("<body"))
{
// apparently full fledged HTML already, so just copy the input file
File.WriteAllText(_temp.Path, contents);
}
else
{
// likely markdown output from another process, so add outer html elements
File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(contents));
}
_browser.Url = new Uri(_temp.Path);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// a bug in Mono requires us to wait to set Icon until handle created.
Icon = _icon;
}
private string GetBasicHtmlFromMarkdown(string markdownHtml)
{
return string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", markdownHtml);
}
}
}
|
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MarkdownDeep;
using SIL.IO;
namespace SIL.Windows.Forms.ReleaseNotes
{
/// <summary>
/// Shows a dialog for release notes; accepts html and markdown
/// </summary>
public partial class ShowReleaseNotesDialog : Form
{
private readonly string _path;
private TempFile _temp;
private readonly Icon _icon;
public ShowReleaseNotesDialog(Icon icon, string path)
{
_path = path;
_icon = icon;
InitializeComponent();
}
private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
{
string contents = File.ReadAllText(_path);
var md = new Markdown();
// Disposed of during dialog Dispose()
_temp = TempFile.WithExtension("htm");
File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents)));
_browser.Url = new Uri(_temp.Path);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// a bug in Mono requires us to wait to set Icon until handle created.
Icon = _icon;
}
private string GetBasicHtmlFromMarkdown(string markdownHtml)
{
return string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", markdownHtml);
}
}
}
|
mit
|
C#
|
44e15d335e7c71fcdfaf4c8a52f0a12e694f2d47
|
Add command-line args interpretation.
|
tf3604/SetMeUp
|
ThinkInSetsTestHarness/ThinkInSetsTestHarness/Program.cs
|
ThinkInSetsTestHarness/ThinkInSetsTestHarness/Program.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ThinkInSetsLib;
namespace ThinkInSetsTestHarness
{
class Program
{
static void Main(string[] args)
{
bool runAllTests = args.Length == 0;
try
{
if (runAllTests ||
ArgsMatchPattern(args, "^.*singleton*.$"))
{
Console.WriteLine("*** Singleton Test (#60)");
FileSystemSingletonInsertTest singletonTest = new FileSystemSingletonInsertTest(
Properties.Settings.Default.FileSystemPath,
Properties.Settings.Default.FileCount,
Properties.Settings.Default.SqlInstanceName,
Properties.Settings.Default.SqlDataBaseName);
ExecutionEngine.RunTest(singletonTest);
Console.WriteLine();
}
if (runAllTests ||
ArgsMatchPattern(args, "^.*bulk.*copy.*$"))
{
Console.WriteLine("*** Bulk Copy Test (#61)");
FileSystemBulkCopyTest bulkCopyTest = new FileSystemBulkCopyTest(
Properties.Settings.Default.FileSystemPath,
Properties.Settings.Default.FileCount,
Properties.Settings.Default.SqlInstanceName,
Properties.Settings.Default.SqlDataBaseName);
ExecutionEngine.RunTest(bulkCopyTest);
}
}
catch (Exception ex)
{
Console.WriteLine($"{ex.ToString()}");
}
}
private static bool ArgsMatchPattern(string[] args, string pattern)
{
foreach (string arg in args)
{
string argLower = arg.ToLowerInvariant();
if (Regex.IsMatch(argLower, pattern))
{
return true;
}
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThinkInSetsLib;
namespace ThinkInSetsTestHarness
{
class Program
{
static void Main(string[] args)
{
try
{
//Console.WriteLine("*** Singleton Test (#60)");
//FileSystemSingletonInsertTest singletonTest = new FileSystemSingletonInsertTest(
// Properties.Settings.Default.FileSystemPath,
// Properties.Settings.Default.FileCount,
// Properties.Settings.Default.SqlInstanceName,
// Properties.Settings.Default.SqlDataBaseName);
//ExecutionEngine.RunTest(singletonTest);
Console.WriteLine();
Console.WriteLine("*** Bulk Copy Test (#61)");
FileSystemBulkCopyTest bulkCopyTest = new FileSystemBulkCopyTest(
Properties.Settings.Default.FileSystemPath,
Properties.Settings.Default.FileCount,
Properties.Settings.Default.SqlInstanceName,
Properties.Settings.Default.SqlDataBaseName);
ExecutionEngine.RunTest(bulkCopyTest);
}
catch (Exception ex)
{
Console.WriteLine($"{ex.ToString()}");
}
}
}
}
|
mit
|
C#
|
a0b62702a387b3184501821947d1f950b280ca14
|
Add InvertUnsafe and ToSwTransform for Matrix4x4Extensions
|
Weingartner/SolidworksAddinFramework
|
SolidworksAddinFramework/Geometry/Matrix4x4Extensions.cs
|
SolidworksAddinFramework/Geometry/Matrix4x4Extensions.cs
|
using System;
using System.Diagnostics;
using System.DoubleNumerics;
using System.Text;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework.Geometry
{
public static class Matrix4x4Extensions
{
public static Matrix4x4 CreateFromAxisAngleOrigin(PointDirection3 p, double angle)
{
return
Matrix4x4.CreateTranslation(-p.Point)
*Matrix4x4.CreateFromAxisAngle(p.Direction.Unit(), angle)
*Matrix4x4.CreateTranslation(p.Point);
}
public static Matrix4x4 CreateFromEdgeAngleOrigin(Edge3 p, double angle)
{
return CreateFromAxisAngleOrigin(new PointDirection3(p.A,p.Delta),angle);
}
/// <summary>
/// A fluent matrix inversion. Will fail with an
/// exception if the matrix is not invertable. Use
/// only when you are sure you have an invertable
/// matrix;
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
public static Matrix4x4 InvertUnsafe(this Matrix4x4 m)
{
Matrix4x4 inv;
if (!Matrix4x4.Invert(m, out inv))
{
throw new Exception("Matrix inversion failed");
}
return inv;
}
public static Matrix4x4 ExtractRotationPart(this Matrix4x4 m)
{
Vector3 dScale;
Quaternion dRotation;
Vector3 dTranslation;
Matrix4x4.Decompose(m, out dScale, out dRotation, out dTranslation);
return Matrix4x4.CreateFromQuaternion(dRotation);
}
public static MathTransform ToSwTransform(this Matrix4x4 m, IMathUtility math = null) =>
(math ?? SwAddinBase.Active.Math).ToSwMatrix(m);
}
}
|
using System.DoubleNumerics;
using System.Text;
namespace SolidworksAddinFramework.Geometry
{
public static class Matrix4x4Extensions
{
public static Matrix4x4 CreateFromAxisAngleOrigin(PointDirection3 p, double angle)
{
return
Matrix4x4.CreateTranslation(-p.Point)
*Matrix4x4.CreateFromAxisAngle(p.Direction.Unit(), angle)
*Matrix4x4.CreateTranslation(p.Point);
}
public static Matrix4x4 CreateFromEdgeAngleOrigin(Edge3 p, double angle)
{
return CreateFromAxisAngleOrigin(new PointDirection3(p.A,p.Delta),angle);
}
public static Matrix4x4 ExtractRotationPart(this Matrix4x4 m)
{
Vector3 dScale;
Quaternion dRotation;
Vector3 dTranslation;
Matrix4x4.Decompose(m, out dScale, out dRotation, out dTranslation);
return Matrix4x4.CreateFromQuaternion(dRotation);
}
}
}
|
mit
|
C#
|
4bf8501d57bb9f8694f82c83823a543f52d9273f
|
Fix parameter name
|
manu-silicon/SharpDX,wyrover/SharpDX,mrvux/SharpDX,Ixonos-USA/SharpDX,wyrover/SharpDX,TigerKO/SharpDX,weltkante/SharpDX,dazerdude/SharpDX,andrewst/SharpDX,TigerKO/SharpDX,VirusFree/SharpDX,fmarrabal/SharpDX,RobyDX/SharpDX,TechPriest/SharpDX,andrewst/SharpDX,manu-silicon/SharpDX,TechPriest/SharpDX,dazerdude/SharpDX,RobyDX/SharpDX,Ixonos-USA/SharpDX,jwollen/SharpDX,sharpdx/SharpDX,davidlee80/SharpDX-1,waltdestler/SharpDX,jwollen/SharpDX,mrvux/SharpDX,VirusFree/SharpDX,PavelBrokhman/SharpDX,VirusFree/SharpDX,wyrover/SharpDX,manu-silicon/SharpDX,RobyDX/SharpDX,sharpdx/SharpDX,PavelBrokhman/SharpDX,sharpdx/SharpDX,TigerKO/SharpDX,fmarrabal/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX,PavelBrokhman/SharpDX,TechPriest/SharpDX,jwollen/SharpDX,dazerdude/SharpDX,davidlee80/SharpDX-1,VirusFree/SharpDX,weltkante/SharpDX,manu-silicon/SharpDX,Ixonos-USA/SharpDX,fmarrabal/SharpDX,TechPriest/SharpDX,fmarrabal/SharpDX,jwollen/SharpDX,waltdestler/SharpDX,weltkante/SharpDX,Ixonos-USA/SharpDX,mrvux/SharpDX,weltkante/SharpDX,RobyDX/SharpDX,PavelBrokhman/SharpDX,dazerdude/SharpDX,waltdestler/SharpDX,wyrover/SharpDX,davidlee80/SharpDX-1,davidlee80/SharpDX-1,andrewst/SharpDX
|
Source/SharpDX.Direct2D1/SimplifiedGeometrySinkNative.cs
|
Source/SharpDX.Direct2D1/SimplifiedGeometrySinkNative.cs
|
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SharpDX.Direct2D1
{
internal partial class SimplifiedGeometrySinkNative
{
public void SetFillMode(FillMode fillMode)
{
SetFillMode_(fillMode);
}
public void SetSegmentFlags(PathSegment vertexFlags)
{
SetSegmentFlags_(vertexFlags);
}
public void BeginFigure(Vector2 startPoint, FigureBegin figureBegin)
{
BeginFigure_(startPoint, figureBegin);
}
public void AddLines(Vector2[] points)
{
AddLines_(points, points.Length);
}
public void AddBeziers(BezierSegment[] beziers)
{
AddBeziers_(beziers, beziers.Length);
}
public void EndFigure(FigureEnd figureEnd)
{
EndFigure_(figureEnd);
}
public void Close()
{
Close_();
}
}
}
|
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SharpDX.Direct2D1
{
internal partial class SimplifiedGeometrySinkNative
{
public void SetFillMode(FillMode fillMode)
{
SetFillMode_(fillMode);
}
public void SetSegmentFlags(PathSegment vertexFlags)
{
SetSegmentFlags_(vertexFlags);
}
public void BeginFigure(Vector2 startPoint, FigureBegin figureBegin)
{
BeginFigure_(startPoint, figureBegin);
}
public void AddLines(Vector2[] ointsRef)
{
AddLines_(ointsRef, ointsRef.Length);
}
public void AddBeziers(BezierSegment[] beziers)
{
AddBeziers_(beziers, beziers.Length);
}
public void EndFigure(FigureEnd figureEnd)
{
EndFigure_(figureEnd);
}
public void Close()
{
Close_();
}
}
}
|
mit
|
C#
|
99b0b3355b003900f74e31d5ec532f4a8fb0a4c6
|
Improve AutoFixture customisation
|
csf-dev/ZPT-Sharp,csf-dev/ZPT-Sharp
|
Test.CSF.Zpt/Util/Autofixture/DummyModelCustomisation.cs
|
Test.CSF.Zpt/Util/Autofixture/DummyModelCustomisation.cs
|
using System;
using Ploeh.AutoFixture;
using CSF.Zpt.Rendering;
using Moq;
namespace Test.CSF.Zpt.Util.Autofixture
{
public class DummyModelCustomisation : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<DummyModel>(x => x.FromFactory(() => {
var output = new Mock<DummyModel>() { CallBase = true };
output.As<IModel>();
return output.Object;
}));
}
}
}
|
using System;
using Ploeh.AutoFixture;
using CSF.Zpt.Rendering;
using Moq;
namespace Test.CSF.Zpt.Util.Autofixture
{
public class DummyModelCustomisation : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<DummyModel>(x => x.FromFactory(() => {
return new Mock<DummyModel>() { CallBase = true }
.Object;
}));
}
}
}
|
mit
|
C#
|
536deba6795f4bd12152563c9eed542feeb155fb
|
Refactor ErrorCode
|
rcskids/ScriptLinkStandard
|
ScriptLinkStandard/Objects/ErrorCode.cs
|
ScriptLinkStandard/Objects/ErrorCode.cs
|
namespace ScriptLinkStandard.Objects
{
public static class ErrorCode
{
/// <summary>
/// Returns provided message with an Ok button. Stops script processing.
/// </summary>
public const int Error = 1;
/// <summary>
/// Returns provided message with Ok and Cancel buttons. Stops script processing, if Cancel is selected.
/// </summary>
public const int OkCancel = 2;
/// <summary>
/// Returns provided message with an Ok button.
/// </summary>
public const int Info = 3;
/// <summary>
/// Returns provided message with Yes and No buttons. Stops script processing, if No is selected.
/// </summary>
public const int YesNo = 4;
/// <summary>
/// Opens provided Url in default web browser.
/// </summary>
public const int OpenUrl = 5;
/// <summary>
/// Returns a message with Ok and Cancel buttons. Opens specified form(s) if OK selected. Can only be used at Form Load and on Field events.
/// </summary>
public const int OpenForm = 6;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ScriptLinkStandard.Objects
{
public static class ErrorCode
{
/// <summary>
/// Returns provided message with an Ok button. Stops script processing.
/// </summary>
public static int Error { get { return 1; } }
/// <summary>
/// Returns provided message with Ok and Cancel buttons. Stops script processing, if Cancel is selected.
/// </summary>
public static int OkCancel { get { return 2; } }
/// <summary>
/// Returns provided message with an Ok button.
/// </summary>
public static int Info { get { return 3; } }
/// <summary>
/// Returns provided message with Yes and No buttons. Stops script processing, if No is selected.
/// </summary>
public static int YesNo { get { return 4; } }
/// <summary>
/// Opens provided Url in default web browser.
/// </summary>
public static int OpenUrl { get { return 5; } }
/// <summary>
/// Returns a message with Ok and Cancel buttons. Opens specified form(s) if OK selected. Can only be used at Form Load and on Field events.
/// </summary>
public static int OpenForm { get { return 6; } }
}
}
|
mit
|
C#
|
f0b0c9ad62175abc71e8adb30175fda107879d8c
|
Fix path for Payments API
|
SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk,lorddev/connectedcare-sdk
|
SnapMD.ConnectedCare.Sdk/PaymentsApi.cs
|
SnapMD.ConnectedCare.Sdk/PaymentsApi.cs
|
using Newtonsoft.Json.Linq;
using SnapMD.ConnectedCare.Sdk.Models;
namespace SnapMD.ConnectedCare.Sdk
{
public class PaymentsApi : ApiCall
{
public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey)
: base(baseUrl, bearerToken, developerId, apiKey)
{
HospitalId = hospitalId;
}
public PaymentsApi(string baseUrl, int hospitalId)
: base(baseUrl)
{
HospitalId = hospitalId;
}
public int HospitalId { get; private set; }
public JObject GetCustomerProfile(int userId)
{
var result = MakeCall(string.Format("patients/{0}/payments", userId));
return result;
}
public JObject RegisterProfile(int userId, object paymentData)
{
var result = Post(string.Format("patients/{0}/payments", userId), paymentData);
return result;
}
public ApiResponse GetPaymentStatus(int consultationId)
{
var result = MakeCall<ApiResponse>(string.Format("patients/copay/{0}/paymentstatus", consultationId));
return result;
}
}
}
|
using Newtonsoft.Json.Linq;
using SnapMD.ConnectedCare.Sdk.Models;
namespace SnapMD.ConnectedCare.Sdk
{
public class PaymentsApi : ApiCall
{
public PaymentsApi(string baseUrl, string bearerToken, int hospitalId, string developerId, string apiKey)
: base(baseUrl, bearerToken, developerId, apiKey)
{
HospitalId = hospitalId;
}
public PaymentsApi(string baseUrl, int hospitalId)
: base(baseUrl)
{
HospitalId = hospitalId;
}
public int HospitalId { get; private set; }
public JObject GetCustomerProfile(int userId)
{
//API looks so strange
//hospital/{hospitalId}/payments/{userId}
var result = MakeCall(string.Format("hospital/{0}/payments", HospitalId));
return result;
}
public JObject RegisterProfile(int userId, object paymentData)
{
//hospital/{hospitalId}/payments/{userId}
var result = Post(string.Format("patients/{0}/payments", userId), paymentData);
return result;
}
public ApiResponse GetPaymentStatus(int consultationId)
{
var result = MakeCall<ApiResponse>(string.Format("patients/copay/{0}/paymentstatus", consultationId));
return result;
}
}
}
|
apache-2.0
|
C#
|
532ff990e19dfcf6e3afa4891cc8ad512c76a1c4
|
Switch Extensions to MS namespace for ease
|
HelloKitty/AspNet.Mvc.Formatters.Protobuf,HelloKitty/AspNet.Mvc.Formatters.Protobuf
|
src/AspNet.Mvc.Formatters.Protobuf/Extensions/ProtobufNetFormatterExtensions.cs
|
src/AspNet.Mvc.Formatters.Protobuf/Extensions/ProtobufNetFormatterExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using AspNet.Mvc.Formatters.Protobuf;
//I know we shouldn't hijack Microsoft namespaces but it's so much easier for consumers
//to access these extensions this way
namespace Microsoft.AspNet.Builder
{
/// <summary>
/// Extensions for Fluent MvcBuilder interfaces.
/// </summary>
public static class ProtobufNetFormatterExtensions
{
/// <summary>
/// Adds the <see cref="ProtobufNetInputFormatter"/> and <see cref="ProtobufNetOutputFormatter"/> to the known formatters.
/// Also registers the Protobuf-net media header to map to these formatters.
/// </summary>
/// <param name="builder">Builder to chain off.</param>
/// <returns>The fluent <see cref="IMvcCoreBuilder"/> instance.</returns>
public static IMvcCoreBuilder AddProtobufNetFormatters(this IMvcCoreBuilder builder)
{
//Add the formatters to the options.
return builder.AddMvcOptions(options =>
{
options.InputFormatters.Add(new ProtobufNetInputFormatter());
options.OutputFormatters.Add(new ProtobufNetOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("ProtobufNet", MediaTypeHeaderValue.Parse("application/Protobuf-Net"));
});
}
/// <summary>
/// Adds the <see cref="ProtobufNetInputFormatter"/> and <see cref="ProtobufNetOutputFormatter"/> to the known formatters.
/// Also registers the Protobuf-net media header to map to these formatters.
/// </summary>
/// <param name="builder">Builder to chain off.</param>
/// <returns>The fluent <see cref="IMvcBuilder"/> instance.</returns>
public static IMvcBuilder AddProtobufNetFormatters(this IMvcBuilder builder)
{
//Add the formatters to the options.
return builder.AddMvcOptions(options =>
{
options.InputFormatters.Add(new ProtobufNetInputFormatter());
options.OutputFormatters.Add(new ProtobufNetOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("ProtobufNet", MediaTypeHeaderValue.Parse("application/Protobuf-Net"));
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using AspNet.Mvc.Formatters.Protobuf;
namespace AspNet.Mvc
{
/// <summary>
/// Extensions for Fluent MvcBuilder interfaces.
/// </summary>
public static class ProtobufNetFormatterExtensions
{
/// <summary>
/// Adds the <see cref="ProtobufNetInputFormatter"/> and <see cref="ProtobufNetOutputFormatter"/> to the known formatters.
/// Also registers the Protobuf-net media header to map to these formatters.
/// </summary>
/// <param name="builder">Builder to chain off.</param>
/// <returns>The fluent <see cref="IMvcCoreBuilder"/> instance.</returns>
public static IMvcCoreBuilder AddProtobufNetFormatters(this IMvcCoreBuilder builder)
{
//Add the formatters to the options.
return builder.AddMvcOptions(options =>
{
options.InputFormatters.Add(new ProtobufNetInputFormatter());
options.OutputFormatters.Add(new ProtobufNetOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("ProtobufNet", MediaTypeHeaderValue.Parse("application/Protobuf-Net"));
});
}
/// <summary>
/// Adds the <see cref="ProtobufNetInputFormatter"/> and <see cref="ProtobufNetOutputFormatter"/> to the known formatters.
/// Also registers the Protobuf-net media header to map to these formatters.
/// </summary>
/// <param name="builder">Builder to chain off.</param>
/// <returns>The fluent <see cref="IMvcBuilder"/> instance.</returns>
public static IMvcBuilder AddProtobufNetFormatters(this IMvcBuilder builder)
{
//Add the formatters to the options.
return builder.AddMvcOptions(options =>
{
options.InputFormatters.Add(new ProtobufNetInputFormatter());
options.OutputFormatters.Add(new ProtobufNetOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("ProtobufNet", MediaTypeHeaderValue.Parse("application/Protobuf-Net"));
});
}
}
}
|
mit
|
C#
|
8b8be83a0cf310341d488dd821efc72576a3cbc2
|
Fix warning on linux/mac by adding AutoGenerateBindingRedirects
|
ubisoftinc/Sharpmake,ubisoftinc/Sharpmake,ubisoftinc/Sharpmake
|
Sharpmake.Application/Sharpmake.Application.sharpmake.cs
|
Sharpmake.Application/Sharpmake.Application.sharpmake.cs
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Sharpmake;
namespace SharpmakeGen
{
[Generate]
public class SharpmakeApplicationProject : Common.SharpmakeBaseProject
{
public SharpmakeApplicationProject()
: base(generateXmlDoc: false)
{
Name = "Sharpmake.Application";
ApplicationManifest = "app.manifest";
}
public override void ConfigureAll(Configuration conf, Target target)
{
base.ConfigureAll(conf, target);
conf.Output = Configuration.OutputType.DotNetConsoleApp;
conf.Options.Add(Options.CSharp.AutoGenerateBindingRedirects.Enabled);
conf.ReferencesByName.Add("System.Windows.Forms");
conf.AddPrivateDependency<SharpmakeProject>(target);
conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target);
conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Sharpmake;
namespace SharpmakeGen
{
[Generate]
public class SharpmakeApplicationProject : Common.SharpmakeBaseProject
{
public SharpmakeApplicationProject()
: base(generateXmlDoc: false)
{
Name = "Sharpmake.Application";
ApplicationManifest = "app.manifest";
}
public override void ConfigureAll(Configuration conf, Target target)
{
base.ConfigureAll(conf, target);
conf.Output = Configuration.OutputType.DotNetConsoleApp;
conf.ReferencesByName.Add("System.Windows.Forms");
conf.AddPrivateDependency<SharpmakeProject>(target);
conf.AddPrivateDependency<SharpmakeGeneratorsProject>(target);
conf.AddPrivateDependency<Platforms.CommonPlatformsProject>(target);
}
}
}
|
apache-2.0
|
C#
|
4afea39688925cd3953a35c5669f452d16a60ed8
|
Fix formating
|
wojtpl2/ExtendedXmlSerializer,wojtpl2/ExtendedXmlSerializer
|
test/ExtendedXmlSerializer.Tests.Performance/LegacyExtendedXmlSerializerTest.cs
|
test/ExtendedXmlSerializer.Tests.Performance/LegacyExtendedXmlSerializerTest.cs
|
// MIT License
//
// Copyright (c) 2016-2018 Wojciech Nagórski
// Michael DeMond
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using BenchmarkDotNet.Attributes;
using ExtendedXmlSerializer.Tests.Performance.Model;
namespace ExtendedXmlSerializer.Tests.Performance
{
[ShortRunJob]
[MemoryDiagnoser]
public class LegacyExtendedXmlSerializerTest
{
readonly TestClassOtherClass _obj = new TestClassOtherClass();
readonly string _xml;
#pragma warning disable 618
readonly ExtendedXmlSerialization.IExtendedXmlSerializer _serializer =
new ExtendedXmlSerialization.ExtendedXmlSerializer();
#pragma warning restore 618
public LegacyExtendedXmlSerializerTest()
{
_obj.Init();
_xml = SerializationClassWithPrimitive();
DeserializationClassWithPrimitive();
}
[Benchmark]
public string SerializationClassWithPrimitive() => _serializer.Serialize(_obj);
[Benchmark]
public TestClassOtherClass DeserializationClassWithPrimitive() => _serializer.Deserialize<TestClassOtherClass>(_xml);
}
}
|
// MIT License
//
// Copyright (c) 2016-2018 Wojciech Nagórski
// Michael DeMond
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using BenchmarkDotNet.Attributes;
using ExtendedXmlSerializer.Tests.Performance.Model;
namespace ExtendedXmlSerializer.Tests.Performance
{
[ShortRunJob]
[MemoryDiagnoser]
public class LegacyExtendedXmlSerializerTest
{
readonly TestClassOtherClass _obj = new TestClassOtherClass();
readonly string _xml;
#pragma warning disable 618
readonly ExtendedXmlSerialization.IExtendedXmlSerializer _serializer =
new ExtendedXmlSerialization.ExtendedXmlSerializer();
#pragma warning restore 618
public LegacyExtendedXmlSerializerTest()
{
_obj.Init();
_xml = SerializationClassWithPrimitive();
DeserializationClassWithPrimitive();
}
[Benchmark]
public string SerializationClassWithPrimitive() => _serializer.Serialize(_obj);
[Benchmark]
public TestClassOtherClass DeserializationClassWithPrimitive() => _serializer.Deserialize<TestClassOtherClass>(_xml);
}
}
|
mit
|
C#
|
6b6948081e5d02e2614b43e7b759c1b0a317174b
|
fix compiling error
|
sebas77/Svelto.ECS,sebas77/Svelto-ECS
|
Svelto.ECS.Components/Components/ExtensionMethodsUECS.cs
|
Svelto.ECS.Components/Components/ExtensionMethodsUECS.cs
|
#if UNITY_MATHEMATICS
using System.Runtime.CompilerServices;
using UnityEngine;
using Svelto.ECS.Components;
using Unity.Mathematics;
public static partial class ExtensionMethods
{
public static float3 ToFloat3(in this ECSVector3 vector)
{
return new float3(vector.x, vector.y, vector.z);
}
public static quaternion ToQuaternion(in this ECSVector4 vector)
{
return new quaternion(vector.x, vector.y, vector.z, vector.w);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Mul(ref this float3 vector1, float value)
{
vector1.x *= value;
vector1.y *= value;
vector1.z *= value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Div(ref this float3 vector1, float value)
{
vector1.x /= value;
vector1.y /= value;
vector1.z /= value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ProjectOnPlane(ref this float3 vector, in float3 planeNormal)
{
var num1 = math.dot(planeNormal,planeNormal);
if ((double) num1 < (double) Mathf.Epsilon)
return;
var num2 = math.dot(vector,planeNormal) / num1;
vector.x -= planeNormal.x * num2;
vector.y -= planeNormal.y * num2;
vector.z -= planeNormal.z * num2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Normalize(ref this float3 x)
{
x.Mul(math.rsqrt(math.dot(x,x)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NormalizeSafe(ref this float3 x)
{
var len = math.dot(x,x);
x = len > math.FLT_MIN_NORMAL ? x * math.rsqrt(len) : float3.zero;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(ref this float3 a, in float3 b)
{
a.x += b.x;
a.y += b.y;
a.z += b.z;
}
}
#endif
|
#if UNITY_MATHEMATICS
using Svelto.ECS.Components;
using Unity.Mathematics;
public static partial class ExtensionMethods
{
public static float3 ToFloat3(in this ECSVector3 vector)
{
return new float3(vector.x, vector.y, vector.z);
}
public static quaternion ToQuaternion(in this ECSVector4 vector)
{
return new quaternion(vector.x, vector.y, vector.z, vector.w);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Mul(ref this float3 vector1, float value)
{
vector1.x *= value;
vector1.y *= value;
vector1.z *= value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Div(ref this float3 vector1, float value)
{
vector1.x /= value;
vector1.y /= value;
vector1.z /= value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ProjectOnPlane(ref this float3 vector, in float3 planeNormal)
{
var num1 = math.dot(planeNormal,planeNormal);
if ((double) num1 < (double) Mathf.Epsilon)
return;
var num2 = math.dot(vector,planeNormal) / num1;
vector.x -= planeNormal.x * num2;
vector.y -= planeNormal.y * num2;
vector.z -= planeNormal.z * num2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Normalize(ref this float3 x)
{
x.Mul(math.rsqrt(math.dot(x,x)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NormalizeSafe(ref this float3 x)
{
var len = math.dot(x,x);
x = len > math.FLT_MIN_NORMAL ? x * math.rsqrt(len) : float3.zero;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(ref this float3 a, in float3 b)
{
a.x += b.x;
a.y += b.y;
a.z += b.z;
}
}
#endif
|
mit
|
C#
|
a14a4d2a207491e6daf53b5f13ea1d44146502f8
|
Check for existence of gedit before trying to launch it
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Helpers/FileHelpers.cs
|
WalletWasabi.Gui/Helpers/FileHelpers.cs
|
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Helpers
{
public static class FileHelpers
{
public static async Task OpenFileInTextEditorAsync(string filePath)
{
if (File.Exists(filePath))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// If no associated application/json MimeType is found xdg-open opens retrun error
// but it tries to open it anyway using the console editor (nano, vim, other..)
await EnvironmentHelpers.ShellExecAsync($"which gedit &> /dev/null && gedit {filePath} || xdg-open {filePath}", waitForExit: false).ConfigureAwait(false);
}
else
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
bool openWithNotepad = true; // If there is an exception with the registry read we use notepad.
try
{
openWithNotepad = !EnvironmentHelpers.IsFileTypeAssociated("json");
}
catch (Exception ex)
{
Logger.LogError(ex);
}
if (openWithNotepad)
{
// Open file using Notepad.
using Process notepadProcess = Process.Start(new ProcessStartInfo
{
FileName = "notepad.exe",
Arguments = filePath,
CreateNoWindow = true,
UseShellExecute = false
});
return; // Opened with notepad, return.
}
}
// Open file with the default editor.
using Process defaultEditorProcess = Process.Start(new ProcessStartInfo
{
FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? filePath : "open",
Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"-e {filePath}" : "",
CreateNoWindow = true,
UseShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
});
}
}
else
{
NotificationHelpers.Error("File not found.");
}
}
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Helpers
{
public static class FileHelpers
{
public static async Task OpenFileInTextEditorAsync(string filePath)
{
if (File.Exists(filePath))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// If no associated application/json MimeType is found xdg-open opens retrun error
// but it tries to open it anyway using the console editor (nano, vim, other..)
await EnvironmentHelpers.ShellExecAsync($"gedit {filePath} || xdg-open {filePath}", waitForExit: false).ConfigureAwait(false);
}
else
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
bool openWithNotepad = true; // If there is an exception with the registry read we use notepad.
try
{
openWithNotepad = !EnvironmentHelpers.IsFileTypeAssociated("json");
}
catch (Exception ex)
{
Logger.LogError(ex);
}
if (openWithNotepad)
{
// Open file using Notepad.
using Process notepadProcess = Process.Start(new ProcessStartInfo
{
FileName = "notepad.exe",
Arguments = filePath,
CreateNoWindow = true,
UseShellExecute = false
});
return; // Opened with notepad, return.
}
}
// Open file with the default editor.
using Process defaultEditorProcess = Process.Start(new ProcessStartInfo
{
FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? filePath : "open",
Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"-e {filePath}" : "",
CreateNoWindow = true,
UseShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
});
}
}
else
{
NotificationHelpers.Error("File not found.");
}
}
}
}
|
mit
|
C#
|
8a93af528bd88a7e320378d6530ac764b19f1a33
|
fix #4090
|
Faizan2304/cli,mlorbetske/cli,naamunds/cli,blackdwarf/cli,nguerrera/cli,svick/cli,livarcocc/cli-1,mlorbetske/cli,EdwardBlair/cli,nguerrera/cli,jonsequitur/cli,johnbeisner/cli,weshaggard/cli,weshaggard/cli,AbhitejJohn/cli,ravimeda/cli,mlorbetske/cli,harshjain2/cli,blackdwarf/cli,weshaggard/cli,jonsequitur/cli,jonsequitur/cli,Faizan2304/cli,EdwardBlair/cli,naamunds/cli,harshjain2/cli,AbhitejJohn/cli,ravimeda/cli,livarcocc/cli-1,svick/cli,Faizan2304/cli,EdwardBlair/cli,harshjain2/cli,johnbeisner/cli,naamunds/cli,nguerrera/cli,nguerrera/cli,dasMulli/cli,ravimeda/cli,dasMulli/cli,dasMulli/cli,jonsequitur/cli,weshaggard/cli,blackdwarf/cli,weshaggard/cli,livarcocc/cli-1,naamunds/cli,svick/cli,AbhitejJohn/cli,blackdwarf/cli,johnbeisner/cli,mlorbetske/cli,AbhitejJohn/cli,naamunds/cli
|
src/dotnet/commands/dotnet-resgen/ResourcesFileGenerator.cs
|
src/dotnet/commands/dotnet-resgen/ResourcesFileGenerator.cs
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using System.Resources;
using System.Xml.Linq;
namespace Microsoft.DotNet.Tools.Resgen
{
internal class ResourcesFileGenerator
{
public static void Generate(ResourceFile sourceFile, Stream outputStream)
{
if (outputStream == null) throw new ArgumentNullException(nameof(outputStream));
using (var input = sourceFile.File.OpenRead())
{
var document = XDocument.Load(input);
var data = document.Root.Elements("data").ToArray();
if (data.Any())
{
var rw = new ResourceWriter(outputStream);
foreach (var e in data)
{
var name = e.Attribute("name").Value;
var valueElement = e.Element("value");
var value = valueElement != null ? valueElement.Value : e.Value;
rw.AddResource(name, value);
}
rw.Generate();
}
}
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using System.Resources;
using System.Xml.Linq;
namespace Microsoft.DotNet.Tools.Resgen
{
internal class ResourcesFileGenerator
{
public static void Generate(ResourceFile sourceFile, Stream outputStream)
{
if (outputStream == null) throw new ArgumentNullException(nameof(outputStream));
using (var input = sourceFile.File.OpenRead())
{
var document = XDocument.Load(input);
var data = document.Root.Elements("data");
if (data.Any())
{
var rw = new ResourceWriter(outputStream);
foreach (var e in data)
{
var name = e.Attribute("name").Value;
var value = e.Element("value").Value;
rw.AddResource(name, value);
}
rw.Generate();
}
}
}
}
}
|
mit
|
C#
|
eb1680f2620b4cd72ae206b3922aae0b817b4c55
|
Add implementation for factory method in Autofac module.
|
lozanotek/mvcturbine,lozanotek/mvcturbine
|
src/Engine/MvcTurbine.Autofac/TurbineAutofacModule.cs
|
src/Engine/MvcTurbine.Autofac/TurbineAutofacModule.cs
|
namespace MvcTurbine.Autofac {
using System;
using System.Collections.Generic;
using ComponentModel;
using global::Autofac;
public class TurbineAutofacModule : Module, IServiceRegistrar {
private readonly IList<Action<ContainerBuilder>> batchedRegistrations;
public TurbineAutofacModule() {
batchedRegistrations = new List<Action<ContainerBuilder>>();
}
public void Dispose() {
}
public void RegisterAll<Interface>() {
}
protected override void Load(ContainerBuilder builder) {
foreach (var registration in batchedRegistrations) {
registration(builder);
}
}
void AddRegistration(Action<ContainerBuilder> builderAction) {
batchedRegistrations.Add(builderAction);
}
public void Register<Interface>(Type implType) where Interface : class {
AddRegistration(builder =>
builder.RegisterType(implType).As<Interface>());
}
public void Register<Interface, Implementation>() where Implementation : class, Interface {
AddRegistration(builder =>
builder.RegisterType<Implementation>().As<Interface>());
}
public void Register<Interface, Implementation>(string key) where Implementation :
class, Interface {
AddRegistration(builder =>
builder.RegisterType<Implementation>().Named<Interface>(key));
}
public void Register(string key, Type type) {
AddRegistration(builder =>
builder.RegisterType(type).Named(key, type));
}
public void Register(Type serviceType, Type implType) {
AddRegistration(builder =>
builder.RegisterType(implType).As(implType).As(serviceType));
}
public void Register<Interface>(Interface instance) where Interface : class
{
AddRegistration(builder => builder.RegisterInstance(instance));
}
public void Register<Interface>(Func<Interface> func) where Interface : class
{
AddRegistration(builder => builder.Register(c => func.Invoke()));
}
}
}
|
namespace MvcTurbine.Autofac {
using System;
using System.Collections.Generic;
using ComponentModel;
using global::Autofac;
public class TurbineAutofacModule : Module, IServiceRegistrar {
private readonly IList<Action<ContainerBuilder>> batchedRegistrations;
public TurbineAutofacModule() {
batchedRegistrations = new List<Action<ContainerBuilder>>();
}
public void Dispose() {
}
public void RegisterAll<Interface>() {
}
protected override void Load(ContainerBuilder builder) {
foreach (var registration in batchedRegistrations) {
registration(builder);
}
}
void AddRegistration(Action<ContainerBuilder> builderAction) {
batchedRegistrations.Add(builderAction);
}
public void Register<Interface>(Type implType) where Interface : class {
AddRegistration(builder =>
builder.RegisterType(implType).As<Interface>());
}
public void Register<Interface, Implementation>() where Implementation : class, Interface {
AddRegistration(builder =>
builder.RegisterType<Implementation>().As<Interface>());
}
public void Register<Interface, Implementation>(string key) where Implementation :
class, Interface {
AddRegistration(builder =>
builder.RegisterType<Implementation>().Named<Interface>(key));
}
public void Register(string key, Type type) {
AddRegistration(builder =>
builder.RegisterType(type).Named(key, type));
}
public void Register(Type serviceType, Type implType) {
AddRegistration(builder =>
builder.RegisterType(implType).As(implType).As(serviceType));
}
public void Register<Interface>(Interface instance) where Interface : class
{
AddRegistration(builder => builder.RegisterInstance(instance));
}
public void Register<Interface>(Func<Interface> func) where Interface : class
{
throw new NotImplementedException();
}
}
}
|
apache-2.0
|
C#
|
b60237f7d47b62e8a8340c19da8bfb4c91ca1170
|
Add license notice.
|
ForNeVeR/Pash,mrward/Pash,WimObiwan/Pash,ForNeVeR/Pash,sillvan/Pash,WimObiwan/Pash,sillvan/Pash,WimObiwan/Pash,sburnicki/Pash,sillvan/Pash,mrward/Pash,sburnicki/Pash,ForNeVeR/Pash,mrward/Pash,Jaykul/Pash,mrward/Pash,sburnicki/Pash,sillvan/Pash,sburnicki/Pash,Jaykul/Pash,Jaykul/Pash,WimObiwan/Pash,Jaykul/Pash,ForNeVeR/Pash
|
Source/System.Management/Pash/Implementation/Native/Posix.cs
|
Source/System.Management/Pash/Implementation/Native/Posix.cs
|
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Reflection;
namespace Pash.Implementation.Native
{
/// <summary>
/// Uses reflection for dynamic loading of Mono.Posix assembly and invocation of native calls.
/// Reflection is used for cross-platform compatibility of current assembly. Methods of this
/// class should be called only if Mono runtime is currently used.
/// </summary>
internal static class Posix
{
public static readonly object X_OK;
private static readonly Delegate _access;
static Posix()
{
var posix = Assembly.Load("Mono.Posix");
var syscall = posix.GetType("Mono.Unix.Native.Syscall");
var access = syscall.GetMethod("access");
_access = Delegate.CreateDelegate(syscall, access);
var accessModes = posix.GetType("Mono.Unix.Native.AccessModes");
X_OK = accessModes.GetField("X_OK").GetRawConstantValue();
}
public static int access(string path, object mode)
{
return (int) _access.DynamicInvoke(new[] { path, mode });
}
}
}
|
using System;
using System.Reflection;
namespace Pash.Implementation.Native
{
/// <summary>
/// Uses reflection for dynamic loading of Mono.Posix assembly and invocation of native calls.
/// Reflection is used for cross-platform compatibility of current assembly. Methods of this
/// class should be called only if Mono runtime is currently used.
/// </summary>
internal static class Posix
{
public static readonly object X_OK;
private static readonly Delegate _access;
static Posix()
{
var posix = Assembly.Load("Mono.Posix");
var syscall = posix.GetType("Mono.Unix.Native.Syscall");
var access = syscall.GetMethod("access");
_access = Delegate.CreateDelegate(syscall, access);
var accessModes = posix.GetType("Mono.Unix.Native.AccessModes");
X_OK = accessModes.GetField("X_OK").GetRawConstantValue();
}
public static int access(string path, object mode)
{
return (int) _access.DynamicInvoke(new[] { path, mode });
}
}
}
|
bsd-3-clause
|
C#
|
e8773f907e7ac252eab3068dff637ddc1f458c5a
|
Remove surplus code
|
MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site
|
src/HeadRaceTiming-Site/Controllers/HomeController.cs
|
src/HeadRaceTiming-Site/Controllers/HomeController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace HeadRaceTiming_Site.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace HeadRaceTiming_Site.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
|
mit
|
C#
|
6c53ce6da4e46940c3b5bc63a2d502c8cd42cea3
|
Update CompactBinaryBondSerializer.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Serialization/Bond/CompactBinaryBondSerializer.cs
|
TIKSN.Core/Serialization/Bond/CompactBinaryBondSerializer.cs
|
using Bond.IO.Safe;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class CompactBinaryBondSerializer : SerializerBase<byte[]>
{
protected override byte[] SerializeInternal(object obj)
{
var output = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(output);
global::Bond.Serialize.To(writer, obj);
return output.Data.Array;
}
}
}
|
using Bond.IO.Safe;
using Bond.Protocols;
using TIKSN.Analytics.Telemetry;
namespace TIKSN.Serialization.Bond
{
public class CompactBinaryBondSerializer : SerializerBase<byte[]>
{
public CompactBinaryBondSerializer(IExceptionTelemeter exceptionTelemeter) : base(exceptionTelemeter)
{
}
protected override byte[] SerializeInternal(object obj)
{
var output = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(output);
global::Bond.Serialize.To(writer, obj);
return output.Data.Array;
}
}
}
|
mit
|
C#
|
d9ca8a441db95a38cf7ba89e98941699d638da44
|
Fix and document the interface
|
shana/handy-things
|
TrackingCollection/TrackingCollection/ITrackingCollection.cs
|
TrackingCollection/TrackingCollection/ITrackingCollection.cs
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace GitHub.Collections
{
/// <summary>
/// TrackingCollection is a specialization of ObservableCollection that gets items from
/// an observable sequence and updates its contents in such a way that two updates to
/// the same object (as defined by an Equals call) will result in one object on
/// the list being updated (as opposed to having two different instances of the object
/// added to the list).
/// It is always sorted, either via the supplied comparer or using the default comparer
/// for T
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T>
{
/// <summary>
/// Sets up an observable as source for the collection.
/// </summary>
/// <param name="obs"></param>
/// <returns>An observable that will return all the items that are
/// fed via the original observer, for further processing by user code
/// if desired</returns>
IObservable<T> Listen(IObservable<T> obs);
IDisposable Subscribe();
IDisposable Subscribe(Action<T> onNext, Action onCompleted);
/// <summary>
/// Set a new comparer for the existing data. This will cause the
/// collection to be resorted and refiltered.
/// </summary>
/// <param name="theComparer">The comparer method for sorting, or null if not sorting</param>
void SetComparer(Func<T, T, int> comparer);
/// <summary>
/// Set a new filter. This will cause the collection to be filtered
/// </summary>
/// <param name="theFilter">The new filter, or null to not have any filtering</param>
void SetFilter(Func<T, int, IList<T>, bool> filter);
void AddItem(T item);
void RemoveItem(T item);
event NotifyCollectionChangedEventHandler CollectionChanged;
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace GitHub.Collections
{
public interface ITrackingCollection<T> : IDisposable, IList<T> where T : ICopyable<T>
{
IObservable<T> Listen(IObservable<T> obs);
IDisposable Subscribe();
IDisposable Subscribe(Action onCompleted);
void SetComparer(Func<T, T, int> theComparer);
void SetFilter(Func<T, int, IList<T>, bool> filter);
event NotifyCollectionChangedEventHandler CollectionChanged;
}
}
|
mit
|
C#
|
aea33f951f95a58d12de59120ff33ed3a982678c
|
Remove unused
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Converters/IsNotNullOrEmptyBoolConverter.cs
|
WalletWasabi.Gui/Converters/IsNotNullOrEmptyBoolConverter.cs
|
using Avalonia.Data.Converters;
using System;
using System.Globalization;
namespace WalletWasabi.Gui.Converters
{
internal class IsNotNullOrEmptyBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is null)
{
return false;
}
if (!string.IsNullOrEmpty(value.ToString()))
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using Avalonia.Data.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace WalletWasabi.Gui.Converters
{
internal class IsNotNullOrEmptyBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is null)
{
return false;
}
if (!string.IsNullOrEmpty(value.ToString()))
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
7b604e17864493f71cfcf61af369db39b2aea7b3
|
Improve comment about response formula
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
|
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
|
using NBitcoin.Secp256k1;
using WalletWasabi.Crypto.Groups;
using WalletWasabi.Helpers;
namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation
{
// Each proof of a linear relation consists of multiple knowledge of
// representation equations, all sharing a single witness comprised of several
// secret scalars.
//
// Knowledge of representation means that given a curve point P, the prover
// knows how to construct P from a set of predetermined generators. This is
// commonly referred to as multi-exponentiation but that term implies
// multiplicative notation for the group operation. Written additively and
// indexing by `i`, each equation is of the form:
//
// P_i = x_1 * G_{i,1} + x_2 * G_{i,2} + ... + x_n * G_{i,n}
//
// Note that some of the generators for an equation can be the point at
// infinity when a term in the witness does not play a part in the
// representation of a specific point.
public class Equation
{
public Equation(GroupElement publicPoint, GroupElementVector generators)
{
Guard.NotNullOrEmpty(nameof(generators), generators);
PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint);
Generators = generators;
}
// Knowledge of representation asserts
// P = x_1*G_1 + x_2*G_2 + ...
// so we need a single public input and several generators
public GroupElement PublicPoint { get; }
public GroupElementVector Generators { get; }
// Evaluate the verification equation corresponding to the one in the statement
internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses)
{
// A challenge of 0 does not place any constraint on the witness
if (challenge == Scalar.Zero)
{
return false;
}
// the verification equation (for 1 generator case) is:
// sG =? R + eP
// where:
// - R = kG is the public nonce, k is the secret nonce
// - P = xG is the public input, x is the secret
// - e is the challenge
// - s is the response
return responses * Generators == (publicNonce + challenge * PublicPoint);
}
// Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness
internal static ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge)
{
// blinding terms are required in order to protect the witness (unless the
// challenge is 0), so only respond if that is the case
foreach (var secretNonce in secretNonces)
{
CryptoGuard.NotZero(nameof(secretNonce), secretNonce);
}
// Taking the discrete logarithms of both sides of the verification
// equation with respect to G results in a formula for the response s
// given k, e and x:
// s = k + ex
return secretNonces + challenge * witness;
}
internal bool VerifySolution(ScalarVector witness)
=> PublicPoint == witness * Generators;
}
}
|
using NBitcoin.Secp256k1;
using WalletWasabi.Crypto.Groups;
using WalletWasabi.Helpers;
namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation
{
// Each proof of a linear relation consists of multiple knowledge of
// representation equations, all sharing a single witness comprised of several
// secret scalars.
//
// Knowledge of representation means that given a curve point P, the prover
// knows how to construct P from a set of predetermined generators. This is
// commonly referred to as multi-exponentiation but that term implies
// multiplicative notation for the group operation. Written additively and
// indexing by `i`, each equation is of the form:
//
// P_i = x_1 * G_{i,1} + x_2 * G_{i,2} + ... + x_n * G_{i,n}
//
// Note that some of the generators for an equation can be the point at
// infinity when a term in the witness does not play a part in the
// representation of a specific point.
public class Equation
{
public Equation(GroupElement publicPoint, GroupElementVector generators)
{
Guard.NotNullOrEmpty(nameof(generators), generators);
PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint);
Generators = generators;
}
// Knowledge of representation asserts
// P = x_1*G_1 + x_2*G_2 + ...
// so we need a single public input and several generators
public GroupElement PublicPoint { get; }
public GroupElementVector Generators { get; }
// Evaluate the verification equation corresponding to the one in the statement
internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses)
{
// A challenge of 0 does not place any constraint on the witness
if (challenge == Scalar.Zero)
{
return false;
}
// the verification equation (for 1 generator case) is:
// sG =? R + eP
// where:
// - R = kG is the public nonce, k is the secret nonce
// - P = xG is the public input, x is the secret
// - e is the challenge
// - s is the response
return responses * Generators == (publicNonce + challenge * PublicPoint);
}
// Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness
internal static ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge)
{
// blinding terms are required in order to protect the witness (unless the
// challenge is 0), so only respond if that is the case
foreach (var secretNonce in secretNonces)
{
CryptoGuard.NotZero(nameof(secretNonce), secretNonce);
}
// By canceling G on both sides of the verification equation above we can
// obtain a formula for the response s given k, e and x:
// s = k + ex
return secretNonces + challenge * witness;
}
internal bool VerifySolution(ScalarVector witness)
=> PublicPoint == witness * Generators;
}
}
|
mit
|
C#
|
982cbacc2e45d96f3640173d224ce7547c86cb88
|
Use 'Thread.Sleep' instead of 'await'-less 'Task.Delay'.
|
Miragecoder/Urbanization,Miragecoder/Urbanization,Miragecoder/Urbanization
|
src/Mirage.Urbanization.Simulation/NeverEndingTask.cs
|
src/Mirage.Urbanization.Simulation/NeverEndingTask.cs
|
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Mirage.Urbanization.Simulation
{
public class NeverEndingTask
{
private readonly CancellationToken _token;
private readonly Task _task;
public NeverEndingTask(string description, Action taskAction, CancellationToken token)
{
if (taskAction == null) throw new ArgumentNullException(nameof(taskAction));
_token = token;
_task = CreateTask(description.ToLower(), taskAction, token);
}
private static Task CreateTask(string description, Action taskAction, CancellationToken token)
{
return new Task(() =>
{
var stopWatch = new Stopwatch();
while (true)
{
stopWatch.Restart();
Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description}...");
taskAction();
Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description} completed in {stopWatch.Elapsed}.");
Thread.Sleep(2000);
}
// ReSharper disable once FunctionNeverReturns
}, token);
}
public void Start()
{
_task.Start();
}
public void Wait()
{
try
{
_task.Wait(_token);
}
catch (OperationCanceledException ex)
{
Mirage.Urbanization.Logger.Instance.WriteLine(ex);
}
}
}
}
|
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Mirage.Urbanization.Simulation
{
public class NeverEndingTask
{
private readonly CancellationToken _token;
private readonly Task _task;
public NeverEndingTask(string description, Action taskAction, CancellationToken token)
{
if (taskAction == null) throw new ArgumentNullException(nameof(taskAction));
_token = token;
_task = CreateTask(description.ToLower(), taskAction, token);
}
private static Task CreateTask(string description, Action taskAction, CancellationToken token)
{
return new Task(() =>
{
var stopWatch = new Stopwatch();
while (true)
{
stopWatch.Restart();
Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description}...");
taskAction();
Mirage.Urbanization.Logger.Instance.WriteLine($"Executing {description} completed in {stopWatch.Elapsed}.");
Task.Delay(2000, token).Wait(token);
}
// ReSharper disable once FunctionNeverReturns
}, token);
}
public void Start()
{
_task.Start();
}
public void Wait()
{
try
{
_task.Wait(_token);
}
catch (OperationCanceledException ex)
{
Mirage.Urbanization.Logger.Instance.WriteLine(ex);
}
}
}
}
|
mit
|
C#
|
ad6cd9dbb1f7f3528c473ada591346cea8a45be6
|
fix DefaultConfigReader.cs
|
Eskat0n/NArms
|
src/NArms.BunkerBuster/Readers/DefaultConfigReader.cs
|
src/NArms.BunkerBuster/Readers/DefaultConfigReader.cs
|
namespace NArms.BunkerBuster.Readers
{
using System.Configuration;
using System.Reflection;
using Annotations;
using Extensions;
public class DefaultConfigReader : IConfigReader
{
public void ReadTo(object configInstance)
{
var properties = configInstance.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var ignoreAttribute = property.GetCustomAttribute<ConfigIgnoreAttribute>();
if (ignoreAttribute != null)
continue;
var keyNameAttribute = property.GetCustomAttribute<ConfigKeyNameAttribute>();
var optionalAttribute = property.GetCustomAttribute<ConfigOptionalAttribute>();
var defaultAttribute = property.GetCustomAttribute<ConfigDefaultAttribute>();
var key = keyNameAttribute == null
? property.Name
: keyNameAttribute.Key;
if (ConfigurationManager.AppSettings.ContainsKey(key))
{
var value = ConfigurationManager.AppSettings[key];
property.SetValue(configInstance, value, null);
}
else if (defaultAttribute != null)
{
property.SetValue(configInstance, defaultAttribute.DefaultValue, null);
}
else if (optionalAttribute == null)
{
}
}
}
}
}
|
namespace NArms.BunkerBuster.Readers
{
using System.Configuration;
using System.Reflection;
using Annotations;
using Extensions;
public class DefaultConfigReader : IConfigReader
{
public void ReadTo(object configInstance)
{
var properties = GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var ignoreAttribute = property.GetCustomAttribute<ConfigIgnoreAttribute>();
if (ignoreAttribute != null)
continue;
var keyNameAttribute = property.GetCustomAttribute<ConfigKeyNameAttribute>();
var optionalAttribute = property.GetCustomAttribute<ConfigOptionalAttribute>();
var defaultAttribute = property.GetCustomAttribute<ConfigDefaultAttribute>();
var key = keyNameAttribute == null
? property.Name
: keyNameAttribute.Key;
if (ConfigurationManager.AppSettings.ContainsKey(key))
{
var value = ConfigurationManager.AppSettings[key];
property.SetValue(configInstance, value, null);
}
else if (defaultAttribute != null)
{
property.SetValue(configInstance, defaultAttribute.DefaultValue, null);
}
else if (optionalAttribute == null)
{
}
}
}
}
}
|
mit
|
C#
|
541596ee9d3b526f2f98a10c416a16511b931951
|
allow GetValidationErrors to extend any object
|
ahanusa/facile.net,peasy/Peasy.NET,ahanusa/Peasy.NET
|
src/Peasy/Peasy/Extensions/IDomainObjectExtensions.cs
|
src/Peasy/Peasy/Extensions/IDomainObjectExtensions.cs
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Peasy
{
public static class IDomainObjectExtensions
{
public static IEnumerable<ValidationResult> GetValidationErrors<T>(this T domainObject) where T : new()
{
var validationResults = new List<ValidationResult>();
var context = new ValidationContext(domainObject);
Validator.TryValidateObject(domainObject, context, validationResults, true);
return validationResults;
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Peasy
{
public static class IDomainObjectExtensions
{
public static IEnumerable<ValidationResult> GetValidationErrors<T>(this T domainObject) where T : IDomainObject
{
var validationResults = new List<ValidationResult>();
var context = new ValidationContext(domainObject);
Validator.TryValidateObject(domainObject, context, validationResults, true);
return validationResults;
}
}
}
|
mit
|
C#
|
68e9bb588ccd3ae1ca912270901b7bf4b0f9c059
|
Handle content types with additional tokens
|
stormpath/stormpath-dotnet-owin-middleware
|
src/Stormpath.Owin.Middleware/Internal/ContentType.cs
|
src/Stormpath.Owin.Middleware/Internal/ContentType.cs
|
// <copyright file="AbstractMiddlewareController.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
namespace Stormpath.Owin.Middleware.Internal
{
public sealed class ContentType
{
public static readonly ContentType Any = new ContentType("*/*");
public static readonly ContentType Json = new ContentType("application/json");
public static readonly ContentType Html = new ContentType("text/html");
public static readonly ContentType FormUrlEncoded = new ContentType("application/x-www-form-urlencoded");
private ContentType(string contentType)
{
this.value = contentType;
}
public static ContentType Parse(string contentType)
{
contentType = contentType.Split(';')?[0];
if (contentType.Equals(Any))
{
return Any;
}
if (contentType.Equals(Json, StringComparison.Ordinal))
{
return Json;
}
if (contentType.Equals(Html, StringComparison.Ordinal))
{
return Html;
}
if (contentType.Equals(FormUrlEncoded, StringComparison.Ordinal))
{
return FormUrlEncoded;
}
return new ContentType(contentType);
}
private readonly string value;
public override string ToString()
=> this.value;
public static implicit operator string(ContentType contentType)
=> contentType.value;
}
}
|
// <copyright file="AbstractMiddlewareController.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
namespace Stormpath.Owin.Middleware.Internal
{
public sealed class ContentType
{
public static readonly ContentType Any = new ContentType("*/*");
public static readonly ContentType Json = new ContentType("application/json");
public static readonly ContentType Html = new ContentType("text/html");
public static readonly ContentType FormUrlEncoded = new ContentType("application/x-www-form-urlencoded");
private ContentType(string contentType)
{
this.value = contentType;
}
public static ContentType Parse(string contentType)
{
if (contentType.Equals(Any))
{
return Any;
}
if (contentType.Equals(Json, StringComparison.Ordinal))
{
return Json;
}
if (contentType.Equals(Html, StringComparison.Ordinal))
{
return Html;
}
if (contentType.Equals(FormUrlEncoded, StringComparison.Ordinal))
{
return FormUrlEncoded;
}
return new ContentType(contentType);
}
private readonly string value;
public override string ToString()
=> this.value;
public static implicit operator string(ContentType contentType)
=> contentType.value;
}
}
|
apache-2.0
|
C#
|
894282be242ffb4896c331130b2e4d6a4ad38bd1
|
Fix warning.
|
Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x
|
src/unity/Runtime/Services/ServiceLocator.cs
|
src/unity/Runtime/Services/ServiceLocator.cs
|
using System;
using System.Collections.Generic;
namespace EE {
internal class ServiceLocatorImpl {
private readonly Dictionary<string, IService> _services = new Dictionary<string, IService>();
private readonly ServiceNameCache _nameCache = new ServiceNameCache();
public void Provide(IService service) {
var type = service.GetType();
var name = _nameCache.GetServiceName(type);
if (_services.TryGetValue(name, out var currentService)) {
currentService.Destroy();
}
_services.Remove(name);
_services.Add(name, service);
}
public T Resolve<T>() where T : IService {
var name = _nameCache.GetServiceName<T>();
if (_services.TryGetValue(name, out var item)) {
if (item is T service) {
return service;
}
}
throw new Exception($"Cannot find the requested service: {name}");
}
}
public static class ServiceLocator {
private static readonly ServiceLocatorImpl _impl = new ServiceLocatorImpl();
/// <summary>
/// Registers a service.
/// </summary>
/// <param name="service"></param>
public static void Provide(IService service) {
_impl.Provide(service);
}
/// <summary>
/// Resolves the specified service.
/// </summary>
public static T Resolve<T>() where T : IService {
return _impl.Resolve<T>();
}
}
}
|
using System;
using System.Collections.Generic;
namespace EE {
internal class ServiceLocatorImpl {
private readonly Dictionary<string, IService> _services = new Dictionary<string, IService>();
private readonly ServiceNameCache _nameCache = new ServiceNameCache();
public void Provide(IService service) {
var type = service.GetType();
var name = _nameCache.GetServiceName(type);
if (_services.TryGetValue(name, out var currentService)) {
currentService.Destroy();
}
_services.Remove(name);
_services.Add(name, service);
}
public T Resolve<T>() where T : IService {
var name = _nameCache.GetServiceName<T>();
if (_services.TryGetValue(name, out var item)) {
if (item is T service) {
return service;
}
}
throw new Exception($"Cannot find the requested service: {name}");
}
}
public class ServiceLocator {
private static readonly ServiceLocatorImpl _impl = new ServiceLocatorImpl();
/// <summary>
/// Registers a service.
/// </summary>
/// <param name="service"></param>
public static void Provide(IService service) {
_impl.Provide(service);
}
/// <summary>
/// Resolves the specified service.
/// </summary>
public static T Resolve<T>() where T : IService {
return _impl.Resolve<T>();
}
}
}
|
mit
|
C#
|
e52810e26c7eac9bb679b5584e3d369cce4e2e76
|
Update ArcDrawNode.cs
|
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Modules/Renderer/SkiaSharp/Nodes/ArcDrawNode.cs
|
src/Core2D/Modules/Renderer/SkiaSharp/Nodes/ArcDrawNode.cs
|
#nullable enable
using Core2D.Model.Renderer;
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class ArcDrawNode : DrawNode, IArcDrawNode
{
public ArcShapeViewModel Arc { get; set; }
public SKPath? Geometry { get; set; }
public ArcDrawNode(ArcShapeViewModel arc, ShapeStyleViewModel style)
{
Style = style;
Arc = arc;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = Arc.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = Arc.State.HasFlag(ShapeStateFlags.Size);
Geometry = PathGeometryConverter.ToSKPath(Arc);
if (Geometry is { })
{
Center = new SKPoint(Geometry.Bounds.MidX, Geometry.Bounds.MidY);
}
else
{
Center = SKPoint.Empty;
}
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (Arc.IsFilled)
{
canvas.DrawPath(Geometry, Fill);
}
if (Arc.IsStroked)
{
canvas.DrawPath(Geometry, Stroke);
}
}
}
|
#nullable enable
using Core2D.Model.Renderer;
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class ArcDrawNode : DrawNode, IArcDrawNode
{
public ArcShapeViewModel Arc { get; set; }
public SKPath? Geometry { get; set; }
public ArcDrawNode(ArcShapeViewModel arc, ShapeStyleViewModel style)
{
Style = style;
Arc = arc;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = Arc.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = Arc.State.HasFlag(ShapeStateFlags.Size);
Geometry = PathGeometryConverter.ToSKPath(Arc);
Center = new SKPoint(Geometry.Bounds.MidX, Geometry.Bounds.MidY);
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (Arc.IsFilled)
{
canvas.DrawPath(Geometry, Fill);
}
if (Arc.IsStroked)
{
canvas.DrawPath(Geometry, Stroke);
}
}
}
|
mit
|
C#
|
5c10582864a199508285bea88b829a91a97cdb27
|
Fix SQLLite-specific test to not rely on hardcoded year.
|
fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core
|
src/NHibernate.Test/NHSpecificTest/NH2224/Fixture.cs
|
src/NHibernate.Test/NHSpecificTest/NH2224/Fixture.cs
|
using System;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH2224
{
[TestFixture]
public class Fixture: BugTestCase
{
protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect)
{
return dialect is NHibernate.Dialect.SQLiteDialect;
}
protected override void OnSetUp()
{
base.OnSetUp();
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction())
{
var class1 = new Class1() { DateOfChange = DateTime.Now };
s.Save(class1);
t.Commit();
}
}
protected override void OnTearDown()
{
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction())
{
s.Delete("from Class1");
t.Commit();
}
base.OnTearDown();
}
[Test]
public void CanQueryBasedOnYearWithInOperator()
{
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction())
{
var criteria = s.CreateCriteria<Class1>();
criteria.Add(Restrictions.In(
Projections.SqlFunction(
"year",
NHibernateUtil.DateTime,
Projections.Property("DateOfChange")),
new string[] { "2010", DateTime.Now.Year.ToString() }));
var result = criteria.List();
Assert.That(result.Count, Is.EqualTo(1));
}
}
}
}
|
using System;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH2224
{
[TestFixture]
public class Fixture: BugTestCase
{
protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect)
{
return dialect is NHibernate.Dialect.SQLiteDialect;
}
protected override void OnSetUp()
{
base.OnSetUp();
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction())
{
var class1 = new Class1() { DateOfChange = DateTime.Now };
s.Save(class1);
t.Commit();
}
}
protected override void OnTearDown()
{
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction())
{
s.Delete("from Class1");
t.Commit();
}
base.OnTearDown();
}
[Test]
public void Test()
{
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction())
{
var criteria = s.CreateCriteria<Class1>();
criteria.Add(Restrictions.In(
Projections.SqlFunction(
"year",
NHibernateUtil.DateTime,
Projections.Property("DateOfChange")),
new string[] { "2010", "2011" }));
var result = criteria.List();
Assert.That(result.Count, Is.EqualTo(1));
}
}
}
}
|
lgpl-2.1
|
C#
|
0a5b284e4b2e46731b6bf87f5d53371bbd8af186
|
Remove workaround for xslt and use a XmlReader instead of a XPath navigator
|
Galad/tranquire,Galad/tranquire,Galad/tranquire
|
src/Tranquire/Reporting/XmlDocumentObserver.Net45.cs
|
src/Tranquire/Reporting/XmlDocumentObserver.Net45.cs
|
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace Tranquire.Reporting
{
partial class XmlDocumentObserver
{
/// <summary>
/// Returns a HTML document that contains the report.
/// </summary>
/// <returns></returns>
public string GetHtmlDocument()
{
var xmlDocument = GetXmlDocument();
var xslt = new XslCompiledTransform(false);
var xmlReader = XmlReader.Create(typeof(XmlDocumentObserver).Assembly.GetManifestResourceStream("Tranquire.Reporting.XmlReport.xsl"));
xslt.Load(xmlReader);
var result = new StringBuilder();
var xmlWriter = XmlWriter.Create(result);
xslt.Transform(xmlDocument.CreateReader(), xmlWriter);
return result.ToString()
.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE html>")
.Replace("<span class=\"glyphicon then-icon\" />", "<span class=\"glyphicon then-icon\"></span>");
}
}
}
|
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace Tranquire.Reporting
{
partial class XmlDocumentObserver
{
/// <summary>
/// Returns a HTML document that contains the report.
/// </summary>
/// <returns></returns>
public string GetHtmlDocument()
{
var xmlDocument = GetXmlDocument();
// enabling debug mode workaround an null reference exception occuring internally in .net core
var xslt = new XslCompiledTransform(true);
var xmlReader = XmlReader.Create(typeof(XmlDocumentObserver).Assembly.GetManifestResourceStream("Tranquire.Reporting.XmlReport.xsl"));
xslt.Load(xmlReader);
var result = new StringBuilder();
var xmlWriter = XmlWriter.Create(result);
xslt.Transform(xmlDocument.CreateNavigator(), xmlWriter);
return result.ToString()
.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE html>")
.Replace("<span class=\"glyphicon then-icon\" />", "<span class=\"glyphicon then-icon\"></span>");
}
}
}
|
mit
|
C#
|
005b88c63bdea2d2e5f4deb2bcbf61aba23105d1
|
delete recursively
|
Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache
|
NuCache.Tests/FileSystemTests/BaseFileSystemDirectoryTest.cs
|
NuCache.Tests/FileSystemTests/BaseFileSystemDirectoryTest.cs
|
using System;
using System.IO;
namespace NuCache.Tests.FileSystemTests
{
public class BaseFileSystemDirectoryTest : IDisposable
{
protected string DirectoryName;
protected FileSystem FileSystem;
public BaseFileSystemDirectoryTest()
{
FileSystem = new FileSystem();
DirectoryName = Guid.NewGuid().ToString();
Directory.CreateDirectory(DirectoryName);
}
public void Dispose()
{
try
{
if (Directory.Exists(DirectoryName))
{
Directory.Delete(DirectoryName, true);
}
}
catch (Exception ex)
{
Console.WriteLine("Enable to delete '{0}'", DirectoryName);
}
}
}
}
|
using System;
using System.IO;
namespace NuCache.Tests.FileSystemTests
{
public class BaseFileSystemDirectoryTest : IDisposable
{
protected string DirectoryName;
protected FileSystem FileSystem;
public BaseFileSystemDirectoryTest()
{
FileSystem = new FileSystem();
DirectoryName = Guid.NewGuid().ToString();
Directory.CreateDirectory(DirectoryName);
}
public void Dispose()
{
try
{
if (Directory.Exists(DirectoryName))
{
Directory.Delete(DirectoryName);
}
}
catch (Exception ex)
{
Console.WriteLine("Enable to delete '{0}'", DirectoryName);
}
}
}
}
|
lgpl-2.1
|
C#
|
0c81078570436a329c2ef45720ccadb666cf17fd
|
Update WireSerializer.cs
|
simonlaroche/akka.net,bruinbrown/akka.net,akoshelev/akka.net,trbngr/akka.net,nanderto/akka.net,alex-kondrashov/akka.net,dbolkensteyn/akka.net,eisendle/akka.net,eloraiby/akka.net,skotzko/akka.net,alexpantyukhin/akka.net,amichel/akka.net,alexvaluyskiy/akka.net,jordansjones/akka.net,amichel/akka.net,willieferguson/akka.net,eloraiby/akka.net,alex-kondrashov/akka.net,Silv3rcircl3/akka.net,trbngr/akka.net,alexpantyukhin/akka.net,ali-ince/akka.net,jordansjones/akka.net,stefansedich/akka.net,akoshelev/akka.net,JeffCyr/akka.net,alexvaluyskiy/akka.net,Micha-kun/akka.net,heynickc/akka.net,simonlaroche/akka.net,Micha-kun/akka.net,eisendle/akka.net,dbolkensteyn/akka.net,nanderto/akka.net,JeffCyr/akka.net,bruinbrown/akka.net,thelegendofando/akka.net,ali-ince/akka.net,willieferguson/akka.net,derwasp/akka.net,heynickc/akka.net,rogeralsing/akka.net,rogeralsing/akka.net,skotzko/akka.net,derwasp/akka.net,thelegendofando/akka.net,stefansedich/akka.net,Silv3rcircl3/akka.net
|
src/contrib/serializers/Akka.Serialization.Wire/WireSerializer.cs
|
src/contrib/serializers/Akka.Serialization.Wire/WireSerializer.cs
|
//-----------------------------------------------------------------------
// <copyright file="WireSerializer.cs" company="Akka.NET Project">
// Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.IO;
using Akka.Actor;
using Akka.Util;
using Wire;
// ReSharper disable once CheckNamespace
namespace Akka.Serialization
{
public class WireSerializer : Serializer
{
private readonly Wire.Serializer _seralizer;
public WireSerializer(ExtendedActorSystem system) : base(system)
{
var akkaSurrogate =
Surrogate
.Create<ISurrogated, ISurrogate>(
from => from.ToSurrogate(system),
to => to.FromSurrogate(system));
_seralizer =
new Wire.Serializer(new SerializerOptions(
preserveObjectReferences: true,
versionTolerance: true,
surrogates: new[]
{
akkaSurrogate
}));
}
public override int Identifier
{
get { return -4; }
}
public override bool IncludeManifest
{
get { return false; }
}
public override byte[] ToBinary(object obj)
{
using (var ms = new MemoryStream())
{
_seralizer.Serialize(obj, ms);
return ms.ToArray();
}
}
public override object FromBinary(byte[] bytes, Type type)
{
using (var ms = new MemoryStream(bytes))
{
var res = _seralizer.Deserialize<object>(ms);
return res;
}
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="WireSerializer.cs" company="Akka.NET Project">
// Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.IO;
using Akka.Actor;
using Akka.Util;
using Wire;
// ReSharper disable once CheckNamespace
namespace Akka.Serialization
{
public class WireSerializer : Serializer
{
private readonly Wire.Serializer _seralizer;
public WireSerializer(ExtendedActorSystem system) : base(system)
{
var akkaSurrogate =
Surrogate
.Create<ISurrogated, ISurrogate>(
from => from.ToSurrogate(system),
to => to.FromSurrogate(system));
_seralizer =
new Wire.Serializer(new SerializerOptions(
preserveObjectReferences: true,
versionTolerance: true,
surrogates: new[]
{
akkaSurrogate
}));
}
public override int Identifier
{
get { return -4; }
}
public override bool IncludeManifest
{
get { return false; }
}
public override byte[] ToBinary(object obj)
{
using (var ms = new MemoryStream())
{
_seralizer.Serialize(obj, ms);
return ms.ToArray();
}
}
public override object FromBinary(byte[] bytes, Type type)
{
using (var ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
ms.Position = 0;
var res = _seralizer.Deserialize<object>(ms);
return res;
}
}
}
}
|
apache-2.0
|
C#
|
37996413bec10c81d0f6a18d63241ffdb7835d18
|
Fix ExternalCounter Serialize method
|
bretcope/BosunReporter.NET
|
BosunReporter/Metrics/ExternalCounter.cs
|
BosunReporter/Metrics/ExternalCounter.cs
|
using System;
using System.Collections.Generic;
using System.Threading;
using BosunReporter.Infrastructure;
namespace BosunReporter.Metrics
{
[ExcludeDefaultTags("host")]
public class ExternalCounter : BosunMetric
{
private int _count;
public int Count => _count;
public override string MetricType => "counter";
public ExternalCounter()
{
}
public void Increment()
{
Interlocked.Increment(ref _count);
}
protected override void Serialize(MetricWriter writer, DateTime now)
{
var increment = Interlocked.Exchange(ref _count, 0);
if (increment == 0)
return;
WriteValue(writer, increment, now);
}
}
}
|
using System.Collections.Generic;
using System.Threading;
using BosunReporter.Infrastructure;
namespace BosunReporter.Metrics
{
[ExcludeDefaultTags("host")]
public class ExternalCounter : BosunMetric
{
private int _count;
public int Count => _count;
public override string MetricType => "counter";
public ExternalCounter()
{
}
public void Increment()
{
Interlocked.Increment(ref _count);
}
protected override IEnumerable<string> Serialize(string unixTimestamp)
{
var increment = Interlocked.Exchange(ref _count, 0);
if (increment == 0)
yield break;
yield return ToJson("", increment, unixTimestamp);
}
}
}
|
mit
|
C#
|
773244b63628c5c1b937c4032b97d49cf4db4ef8
|
Add tests for timeout of CommandLineRunner
|
ermshiperete/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,hatton/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,hatton/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso
|
Palaso.Tests/CommandLineProcessing/CommandLineRunnerTests.cs
|
Palaso.Tests/CommandLineProcessing/CommandLineRunnerTests.cs
|
using System;
using NUnit.Framework;
using Palaso.CommandLineProcessing;
using Palaso.Progress;
namespace Palaso.Tests.CommandLineProcessing
{
[TestFixture]
public class CommandLineRunnerTests
{
private const string App = "PalasoUIWindowsForms.TestApp.exe";
[Test]
public void CommandWith10Line_NoCallbackOption_Get10LinesSynchronously()
{
var progress = new StringBuilderProgress();
var result = CommandLineRunner.Run(App, "CommandLineRunnerTest", null, string.Empty, 100,
progress, null);
Assert.IsTrue(result.StandardOutput.Contains("0"));
Assert.IsTrue(result.StandardOutput.Contains("9"));
}
[Test]
public void CommandWith10Line_NoCallbackOption_TimeoutAfter3s()
{
var progress = new StringBuilderProgress();
var result = CommandLineRunner.Run(App, "CommandLineRunnerTest", null, string.Empty, 3,
progress, null);
Assert.That(result.DidTimeOut, Is.True);
Assert.That(result.StandardOutput, Is.Null);
Assert.That(result.StandardError, Contains.Substring("Timed Out after waiting 3 seconds."));
}
[Test, Category("KnownMonoIssue")]
[Platform(Exclude="Linux", Reason = "Test has problems on Mono")]
public void CommandWith10Line_CallbackOption_Get10LinesAsynchronously()
{
var progress = new StringBuilderProgress();
int linesReceivedAsynchronously = 0;
CommandLineRunner.Run(App, "CommandLineRunnerTest", null, string.Empty, 100,
progress, s => ++linesReceivedAsynchronously);
// The test fails on Linux because progress gets called 10x for StdOutput plus
// 1x for StdError (probably on the closing of the stream), so linesReceivedAsync is 11.
Assert.AreEqual(10, linesReceivedAsynchronously);
}
[Test]
public void CommandWith10Line_CallbackOption_TimeoutAfter3s()
{
var progress = new StringBuilderProgress();
int linesReceivedAsynchronously = 0;
var result = CommandLineRunner.Run(App, "CommandLineRunnerTest", null, string.Empty, 3,
progress, s => ++linesReceivedAsynchronously);
Assert.That(result.DidTimeOut, Is.True);
Assert.That(result.StandardOutput, Is.Null);
Assert.That(result.StandardError, Contains.Substring("Timed Out after waiting 3 seconds."));
}
}
}
|
using System;
using NUnit.Framework;
using Palaso.CommandLineProcessing;
using Palaso.Progress;
namespace Palaso.Tests.CommandLineProcessing
{
[TestFixture]
public class CommandLineRunnerTests
{
private const string App = "PalasoUIWindowsForms.TestApp.exe";
[Test]
public void CommandWith10Line_NoCallbackOption_Get10LinesSynchronously()
{
var progress = new StringBuilderProgress();
var result = CommandLineRunner.Run(App, "CommandLineRunnerTest", null, string.Empty, 100,
progress, null);
Assert.IsTrue(result.StandardOutput.Contains("0"));
Assert.IsTrue(result.StandardOutput.Contains("9"));
}
[Test, Category("KnownMonoIssue")]
[Platform(Exclude="Linux", Reason = "Test has problems on Mono")]
public void CommandWith10Line_CallbackOption_Get10LinesAsynchronously()
{
var progress = new StringBuilderProgress();
int linesReceivedAsynchronously = 0;
CommandLineRunner.Run(App, "CommandLineRunnerTest", null, string.Empty, 100,
progress, s => ++linesReceivedAsynchronously);
// The test fails on Linux because progress gets called 10x for StdOutput plus
// 1x for StdError (probably on the closing of the stream), so linesReceivedAsync is 11.
Assert.AreEqual(10, linesReceivedAsynchronously);
}
}
}
|
mit
|
C#
|
7c1e97c8a017d1a45fd6e7bdbfd2c856353014f6
|
Add test for storageprovider attribute
|
mhertis/Orleankka,yevhen/Orleankka,pkese/Orleankka,mhertis/Orleankka,OrleansContrib/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,pkese/Orleankka
|
Source/Orleankka.Tests/Features/Native_orleans_attributes.cs
|
Source/Orleankka.Tests/Features/Native_orleans_attributes.cs
|
using System;
using System.Reflection;
using NUnit.Framework;
using Orleans.CodeGeneration;
using Orleans.Concurrency;
using Orleans.Providers;
namespace Orleankka.Features
{
namespace Native_orleans_attributes
{
using Core;
using Testing;
[Version(22)]
public interface ITestVersionActor : IActor {}
public class TestVersionActor : Actor, ITestVersionActor {}
[StatelessWorker]
public class TestDefaultStatelessWorkerActor : Actor {}
[StatelessWorker(4)]
public class TestParameterizedStatelessWorkerActor : Actor {}
[StorageProvider]
public class TestDefaultStorageProviderActor : Actor {}
[TestFixture]
[RequiresSilo]
public class Tests
{
static TAttribute AssertHasCustomAttribute<TActor, TAttribute>() where TActor : Actor where TAttribute : Attribute =>
AssertHasCustomAttribute<TAttribute>(ActorType.Of<TActor>().Grain);
static TAttribute AssertHasCustomAttribute<TAttribute>(Type type) where TAttribute : Attribute
{
var attribute = type.GetCustomAttribute<TAttribute>();
Assert.That(attribute, Is.Not.Null);
return attribute;
}
[Test]
public void Version_attribute()
{
var @interface = ActorInterface.Of<TestVersionActor>();
var attribute = AssertHasCustomAttribute<VersionAttribute>(@interface.Grain);
Assert.That(attribute.Version, Is.EqualTo(22));
}
[Test]
public void StatelessWorker_attribute()
{
var attribute = AssertHasCustomAttribute<TestDefaultStatelessWorkerActor, StatelessWorkerAttribute>();
Assert.That(attribute.MaxLocalWorkers, Is.EqualTo(new StatelessWorkerAttribute().MaxLocalWorkers));
attribute = AssertHasCustomAttribute<TestParameterizedStatelessWorkerActor, StatelessWorkerAttribute>();
Assert.That(attribute.MaxLocalWorkers, Is.EqualTo(4));
}
[Test]
public void StorageProvider_attribute()
{
var attribute = AssertHasCustomAttribute<TestDefaultStorageProviderActor, StorageProviderAttribute>();
Assert.That(attribute.ProviderName, Is.EqualTo(new StorageProviderAttribute().ProviderName));
}
}
}
}
|
using System.Reflection;
using NUnit.Framework;
using Orleans.CodeGeneration;
using Orleans.Concurrency;
namespace Orleankka.Features
{
namespace Native_orleans_attributes
{
using Core;
using Testing;
[Version(22)]
public interface ITestVersionActor : IActor {}
public class TestVersionActor : Actor, ITestVersionActor {}
[StatelessWorker]
public class TestDefaultStatelessWorkerActor : Actor {}
[StatelessWorker(4)]
public class TestParameterizedStatelessWorkerActor : Actor {}
[TestFixture]
[RequiresSilo]
public class Tests
{
[Test]
public void Version_attribute()
{
var @interface = ActorInterface.Of<TestVersionActor>();
var attribute = @interface.Grain.GetCustomAttribute<VersionAttribute>();
Assert.That(attribute, Is.Not.Null);
Assert.That(attribute.Version, Is.EqualTo(22));
}
[Test]
public void StatelessWorker_attribute()
{
var type = ActorType.Of<TestDefaultStatelessWorkerActor>();
var attribute = type.Grain.GetCustomAttribute<StatelessWorkerAttribute>();
Assert.That(attribute, Is.Not.Null);
Assert.That(attribute.MaxLocalWorkers, Is.EqualTo(new StatelessWorkerAttribute().MaxLocalWorkers));
type = ActorType.Of<TestParameterizedStatelessWorkerActor>();
attribute = type.Grain.GetCustomAttribute<StatelessWorkerAttribute>();
Assert.That(attribute, Is.Not.Null);
Assert.That(attribute.MaxLocalWorkers, Is.EqualTo(4));
}
}
}
}
|
apache-2.0
|
C#
|
4fabcb7a62d9b05032cc27d0bc99c64232004ba1
|
Use culture invariant version of float.TryParse
|
feliwir/openSage,feliwir/openSage
|
src/OpenSage.Game/Data/Utilities/ParseUtility.cs
|
src/OpenSage.Game/Data/Utilities/ParseUtility.cs
|
using System.Globalization;
namespace OpenSage.Data.Utilities
{
internal static class ParseUtility
{
public static float ParseFloat(string s)
{
return float.Parse(s, CultureInfo.InvariantCulture);
}
public static bool TryParseFloat(string s, out float result)
{
return float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
}
}
}
|
using System.Globalization;
namespace OpenSage.Data.Utilities
{
internal static class ParseUtility
{
public static float ParseFloat(string s)
{
return float.Parse(s, CultureInfo.InvariantCulture);
}
public static bool TryParseFloat(string s, out float result)
{
return float.TryParse(s, out result);
}
}
}
|
mit
|
C#
|
e4b6cc5a1c8a523052ffac17e63078c23bdaa0ca
|
Order elements
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/RecoverWalletPageViewModel.cs
|
WalletWasabi.Fluent/ViewModels/RecoverWalletPageViewModel.cs
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;
using NBitcoin;
using ReactiveUI;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Models;
namespace WalletWasabi.Fluent.ViewModels
{
public class RecoveryPageViewModel : NavBarItemViewModel
{
private readonly ObservableAsPropertyHelper<Mnemonic?> _currentMnemonic;
private ObservableCollection<string> _mnemonics;
private IEnumerable<string> _suggestions;
private string _selectedTag;
public RecoveryPageViewModel(IScreen screen) : base(screen)
{
Suggestions = new Mnemonic(Wordlist.English, WordCount.Twelve).WordList.GetWords();
Mnemonics = new ObservableCollection<string>();
_currentMnemonic = Mnemonics.ToObservableChangeSet().ToCollection()
.Select(x => x.Count == 12 ? new Mnemonic(GetTagsAsConcatString()) : default)
.ToProperty(this, x => x.CurrentMnemonics);
this.WhenAnyValue(x => x.SelectedTag)
.Where(x => !string.IsNullOrEmpty(x))
.Subscribe(AddTag);
// TODO: Will try to find ways of doing this better...
this.WhenAnyValue(x => x.CurrentMnemonics)
.Subscribe(x => this.RaisePropertyChanged(nameof(Mnemonics)));
this.ValidateProperty(x => x.Mnemonics, ValidateMnemonics);
}
public ObservableCollection<string> Mnemonics
{
get => _mnemonics;
set => this.RaiseAndSetIfChanged(ref _mnemonics, value);
}
public IEnumerable<string> Suggestions
{
get => _suggestions;
set => this.RaiseAndSetIfChanged(ref _suggestions, value);
}
public string SelectedTag
{
get => _selectedTag;
set => this.RaiseAndSetIfChanged(ref _selectedTag, value);
}
public Mnemonic? CurrentMnemonics => _currentMnemonic.Value;
public override string IconName => "settings_regular";
private void ValidateMnemonics(IValidationErrors errors)
{
if (CurrentMnemonics is { } && !CurrentMnemonics.IsValidChecksum)
{
errors.Add(ErrorSeverity.Error, "Invalid recovery seed phrase.");
}
}
private void AddTag(string tagString)
{
Mnemonics.Add(tagString);
SelectedTag = string.Empty;
}
private string GetTagsAsConcatString()
{
return string.Join(' ', Mnemonics);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using DynamicData;
using DynamicData.Binding;
using NBitcoin;
using ReactiveUI;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Models;
namespace WalletWasabi.Fluent.ViewModels
{
public class RecoveryPageViewModel : NavBarItemViewModel
{
private readonly ObservableAsPropertyHelper<Mnemonic?> _currentMnemonic;
private ObservableCollection<string> _mnemonics;
private IEnumerable<string> _suggestions;
private string _selectedTag;
public ObservableCollection<string> Mnemonics
{
get => _mnemonics;
set => this.RaiseAndSetIfChanged(ref _mnemonics, value);
}
public IEnumerable<string> Suggestions
{
get => _suggestions;
set => this.RaiseAndSetIfChanged(ref _suggestions, value);
}
public string SelectedTag
{
get => _selectedTag;
set => this.RaiseAndSetIfChanged(ref _selectedTag, value);
}
public RecoveryPageViewModel(IScreen screen) : base(screen)
{
Suggestions = new Mnemonic(Wordlist.English, WordCount.Twelve).WordList.GetWords();
Mnemonics = new ObservableCollection<string>();
_currentMnemonic = Mnemonics.ToObservableChangeSet().ToCollection()
.Select(x => x.Count == 12 ? new Mnemonic(GetTagsAsConcatString()) : default)
.ToProperty(this, x => x.CurrentMnemonics);
this.WhenAnyValue(x => x.SelectedTag)
.Where(x => !string.IsNullOrEmpty(x))
.Subscribe(AddTag);
// TODO: Will try to find ways of doing this better...
this.WhenAnyValue(x => x.CurrentMnemonics)
.Subscribe(x => this.RaisePropertyChanged(nameof(Mnemonics)));
this.ValidateProperty(x => x.Mnemonics, ValidateMnemonics);
}
private void ValidateMnemonics(IValidationErrors errors)
{
if (CurrentMnemonics is { } && !CurrentMnemonics.IsValidChecksum)
{
errors.Add(ErrorSeverity.Error, "Invalid recovery seed phrase.");
}
}
private void AddTag(string tagString)
{
Mnemonics.Add(tagString);
SelectedTag = string.Empty;
}
private string GetTagsAsConcatString()
{
return string.Join(' ', Mnemonics);
}
public Mnemonic? CurrentMnemonics => _currentMnemonic.Value;
public override string IconName => "settings_regular";
}
}
|
mit
|
C#
|
0e2a7203237bdc20c60ee83d292813536eb357ae
|
Make case insensitive matching
|
jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos
|
src/Manos/Manos.Routing/StringMatchOperation.cs
|
src/Manos/Manos.Routing/StringMatchOperation.cs
|
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Specialized;
using Manos.Collections;
namespace Manos.Routing
{
public class StringMatchOperation : IMatchOperation
{
private string str;
public StringMatchOperation (string str)
{
String = str;
}
public string String {
get { return str; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("StringMatch operations should not use empty strings.");
str = value.ToLower();
}
}
public bool IsMatch (string input, int start, out DataDictionary data, out int end)
{
if (!StartsWith (input, start, String)) {
data = null;
end = start;
return false;
}
data = null;
end = start + String.Length;
return true;
}
public static bool StartsWith (string input, int start, string str)
{
string lowerInput = input.ToLower ();
if (lowerInput.Length < str.Length + start)
return false;
for (int i = 0; i < str.Length; i++) {
if (lowerInput [start + i] != str [i])
return false;
}
return true;
}
}
}
|
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Specialized;
using Manos.Collections;
namespace Manos.Routing
{
public class StringMatchOperation : IMatchOperation
{
private string str;
public StringMatchOperation (string str)
{
String = str;
}
public string String {
get { return str; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("StringMatch operations should not use empty strings.");
str = value;
}
}
public bool IsMatch (string input, int start, out DataDictionary data, out int end)
{
if (!StartsWith (input, start, String)) {
data = null;
end = start;
return false;
}
data = null;
end = start + String.Length;
return true;
}
public static bool StartsWith (string input, int start, string str)
{
if (input.Length < str.Length + start)
return false;
for (int i = 0; i < str.Length; i++) {
if (input [start + i] != str [i])
return false;
}
return true;
}
}
}
|
mit
|
C#
|
443a6353853891bc477ba36ad2d8a6fbdfef52ff
|
Return null public key token if public key is null
|
jorik041/dnlib,picrap/dnlib,yck1509/dnlib,modulexcite/dnlib,ilkerhalil/dnlib,Arthur2e5/dnlib,kiootic/dnlib,ZixiangBoy/dnlib,0xd4d/dnlib
|
src/DotNet/PublicKey.cs
|
src/DotNet/PublicKey.cs
|
namespace dot10.DotNet {
/// <summary>
/// Represents a public key
/// </summary>
public sealed class PublicKey : PublicKeyBase {
const AssemblyHashAlgorithm DEFAULT_ALGORITHM = AssemblyHashAlgorithm.SHA1;
AssemblyHashAlgorithm hashAlgo;
PublicKeyToken publicKeyToken;
/// <summary>
/// Gets the <see cref="PublicKeyToken"/>
/// </summary>
public PublicKeyToken Token {
get {
if (publicKeyToken == null && !IsNullOrEmpty)
publicKeyToken = AssemblyHash.CreatePublicKeyToken(data, hashAlgo);
return publicKeyToken;
}
}
/// <summary>
/// Gets/sets the <see cref="AssemblyHashAlgorithm"/>
/// </summary>
public AssemblyHashAlgorithm HashAlgorithm {
get { return hashAlgo; }
set {
if (hashAlgo == value)
return;
hashAlgo = value;
publicKeyToken = null;
}
}
/// <inheritdoc/>
public override byte[] Data {
get { return data; }
set {
if (data == value)
return;
data = value;
publicKeyToken = null;
}
}
/// <inheritdoc/>
public PublicKey()
: this(DEFAULT_ALGORITHM) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="hashAlgo">Hash algorithm</param>
public PublicKey(AssemblyHashAlgorithm hashAlgo)
: base() {
this.hashAlgo = hashAlgo;
}
/// <inheritdoc/>
public PublicKey(byte[] data)
: this(data, DEFAULT_ALGORITHM) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">Public key data</param>
/// <param name="hashAlgo">Hash algorithm</param>
public PublicKey(byte[] data, AssemblyHashAlgorithm hashAlgo)
: base(data) {
this.hashAlgo = hashAlgo;
}
/// <inheritdoc/>
public PublicKey(string hexString)
: this(hexString, DEFAULT_ALGORITHM) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="hexString">Public key data as a hex string or the string <c>"null"</c>
/// to set public key data to <c>null</c></param>
/// <param name="hashAlgo">Hash algorithm</param>
public PublicKey(string hexString, AssemblyHashAlgorithm hashAlgo)
: base(hexString) {
this.hashAlgo = hashAlgo;
}
}
}
|
namespace dot10.DotNet {
/// <summary>
/// Represents a public key
/// </summary>
public sealed class PublicKey : PublicKeyBase {
const AssemblyHashAlgorithm DEFAULT_ALGORITHM = AssemblyHashAlgorithm.SHA1;
AssemblyHashAlgorithm hashAlgo;
PublicKeyToken publicKeyToken;
/// <summary>
/// Gets the <see cref="PublicKeyToken"/>
/// </summary>
public PublicKeyToken Token {
get {
if (publicKeyToken == null)
publicKeyToken = AssemblyHash.CreatePublicKeyToken(data, hashAlgo);
return publicKeyToken;
}
}
/// <summary>
/// Gets/sets the <see cref="AssemblyHashAlgorithm"/>
/// </summary>
public AssemblyHashAlgorithm HashAlgorithm {
get { return hashAlgo; }
set {
if (hashAlgo == value)
return;
hashAlgo = value;
publicKeyToken = null;
}
}
/// <inheritdoc/>
public override byte[] Data {
get { return data; }
set {
if (data == value)
return;
data = value;
publicKeyToken = null;
}
}
/// <inheritdoc/>
public PublicKey()
: this(DEFAULT_ALGORITHM) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="hashAlgo">Hash algorithm</param>
public PublicKey(AssemblyHashAlgorithm hashAlgo)
: base() {
this.hashAlgo = hashAlgo;
}
/// <inheritdoc/>
public PublicKey(byte[] data)
: this(data, DEFAULT_ALGORITHM) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="data">Public key data</param>
/// <param name="hashAlgo">Hash algorithm</param>
public PublicKey(byte[] data, AssemblyHashAlgorithm hashAlgo)
: base(data) {
this.hashAlgo = hashAlgo;
}
/// <inheritdoc/>
public PublicKey(string hexString)
: this(hexString, DEFAULT_ALGORITHM) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="hexString">Public key data as a hex string or the string <c>"null"</c>
/// to set public key data to <c>null</c></param>
/// <param name="hashAlgo">Hash algorithm</param>
public PublicKey(string hexString, AssemblyHashAlgorithm hashAlgo)
: base(hexString) {
this.hashAlgo = hashAlgo;
}
}
}
|
mit
|
C#
|
7a43f61e1777bfdb1c7ba24ce6db5e75f9b81182
|
Correct Covalence provider name
|
Visagalis/Oxide,Visagalis/Oxide,LaserHydra/Oxide,LaserHydra/Oxide
|
Games/Unity/Oxide.Game.TheForest/Libraries/Covalence/TheForestCovalenceProvider.cs
|
Games/Unity/Oxide.Game.TheForest/Libraries/Covalence/TheForestCovalenceProvider.cs
|
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Game.TheForest.Libraries.Covalence
{
/// <summary>
/// Provides Covalence functionality for the game "The Forest"
/// </summary>
public class TheForestCovalenceProvider : ICovalenceProvider
{
/// <summary>
/// Gets the name of the game for which this provider provides
/// </summary>
public string GameName => "TheForest";
/// <summary>
/// Gets the singleton instance of this provider
/// </summary>
internal static TheForestCovalenceProvider Instance { get; private set; }
public TheForestCovalenceProvider()
{
Instance = this;
}
/// <summary>
/// Gets the player manager
/// </summary>
public TheForestPlayerManager PlayerManager { get; private set; }
/// <summary>
/// Gets the command system provider
/// </summary>
public TheForestCommandSystem CommandSystem { get; private set; }
/// <summary>
/// Creates the game-specific server object
/// </summary>
/// <returns></returns>
public IServer CreateServer() => new TheForestServer();
/// <summary>
/// Creates the game-specific player manager object
/// </summary>
/// <returns></returns>
public IPlayerManager CreatePlayerManager() => PlayerManager = new TheForestPlayerManager();
/// <summary>
/// Creates the game-specific command system provider object
/// </summary>
/// <returns></returns>
public ICommandSystem CreateCommandSystemProvider() => CommandSystem = new TheForestCommandSystem();
}
}
|
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Game.TheForest.Libraries.Covalence
{
/// <summary>
/// Provides Covalence functionality for the game "The Forest"
/// </summary>
public class TheForestCovalenceProvider : ICovalenceProvider
{
/// <summary>
/// Gets the name of the game for which this provider provides
/// </summary>
public string GameName => "The Forest";
/// <summary>
/// Gets the singleton instance of this provider
/// </summary>
internal static TheForestCovalenceProvider Instance { get; private set; }
public TheForestCovalenceProvider()
{
Instance = this;
}
/// <summary>
/// Gets the player manager
/// </summary>
public TheForestPlayerManager PlayerManager { get; private set; }
/// <summary>
/// Gets the command system provider
/// </summary>
public TheForestCommandSystem CommandSystem { get; private set; }
/// <summary>
/// Creates the game-specific server object
/// </summary>
/// <returns></returns>
public IServer CreateServer() => new TheForestServer();
/// <summary>
/// Creates the game-specific player manager object
/// </summary>
/// <returns></returns>
public IPlayerManager CreatePlayerManager() => PlayerManager = new TheForestPlayerManager();
/// <summary>
/// Creates the game-specific command system provider object
/// </summary>
/// <returns></returns>
public ICommandSystem CreateCommandSystemProvider() => CommandSystem = new TheForestCommandSystem();
}
}
|
mit
|
C#
|
b0b0278f54010e70d9077fd25c893797fd324760
|
Fix cache update exception typo
|
opentable/hobknob-client-net,opentable/hobknob-client-net
|
HobknobClientNet/HobknobClientFactory.cs
|
HobknobClientNet/HobknobClientFactory.cs
|
using System;
namespace HobknobClientNet
{
public interface IHobknobClientFactory
{
IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed);
}
public class HobknobClientFactory : IHobknobClientFactory
{
public IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed)
{
var etcdKeysPath = string.Format("http://{0}:{1}/v2/keys/", etcdHost, etcdPort);
var etcdClient = new EtcdClient(new Uri(etcdKeysPath));
var featureToggleProvider = new FeatureToggleProvider(etcdClient, applicationName);
var featureToggleCache = new FeatureToggleCache(featureToggleProvider, cacheUpdateInterval);
var hobknobClient = new HobknobClient(featureToggleCache, applicationName);
if (cacheUpdateFailed == null)
throw new ArgumentNullException("cacheUpdateFailed", "Cached update handler is empty");
featureToggleCache.CacheUpdateFailed += cacheUpdateFailed;
featureToggleCache.Initialize();
return hobknobClient;
}
}
}
|
using System;
namespace HobknobClientNet
{
public interface IHobknobClientFactory
{
IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed);
}
public class HobknobClientFactory : IHobknobClientFactory
{
public IHobknobClient Create(string etcdHost, int etcdPort, string applicationName, TimeSpan cacheUpdateInterval, EventHandler<CacheUpdateFailedArgs> cacheUpdateFailed)
{
var etcdKeysPath = string.Format("http://{0}:{1}/v2/keys/", etcdHost, etcdPort);
var etcdClient = new EtcdClient(new Uri(etcdKeysPath));
var featureToggleProvider = new FeatureToggleProvider(etcdClient, applicationName);
var featureToggleCache = new FeatureToggleCache(featureToggleProvider, cacheUpdateInterval);
var hobknobClient = new HobknobClient(featureToggleCache, applicationName);
if (cacheUpdateFailed == null)
throw new ArgumentNullException("cacheUpdateFailed", "Cached update handler is emtpy");
featureToggleCache.CacheUpdateFailed += cacheUpdateFailed;
featureToggleCache.Initialize();
return hobknobClient;
}
}
}
|
mit
|
C#
|
ea2044e9a0d3fb441dfe8d8c28276bffec4e0d67
|
Fix version.
|
OlegAxenow/Method.Injection
|
Method.Inject/Properties/AssemblyInfo.cs
|
Method.Inject/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0.0")]
[assembly: AssemblyTitle("Method.Inject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Method.Inject")]
[assembly: AssemblyCopyright("Copyright © Oleg Aksenov 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
[assembly: AssemblyTitle("Method.Inject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Method.Inject")]
[assembly: AssemblyCopyright("Copyright © Oleg Aksenov 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
|
mit
|
C#
|
753bdf3250585e25fdd264a85522af539351a283
|
Make HttpActorSustem public
|
OrleansContrib/Orleankka,OrleansContrib/Orleankka
|
Source/Orleankka/Http/HttpActorSystem.cs
|
Source/Orleankka/Http/HttpActorSystem.cs
|
using System;
using System.Net.Http;
using System.Text.Json;
namespace Orleankka.Http
{
public class HttpActorSystem : IActorSystem
{
readonly ActorRouteMapper mapper;
readonly HttpClient client;
readonly JsonSerializerOptions serializer;
readonly IActorRefMiddleware middleware;
public HttpActorSystem(HttpClient client, JsonSerializerOptions serializer, ActorRouteMapper mapper, IActorRefMiddleware middleware = null)
{
if (!client.BaseAddress.AbsoluteUri.EndsWith("/"))
throw new InvalidOperationException("The base address should end with /");
this.mapper = mapper;
this.client = client;
this.serializer = serializer;
this.middleware = middleware ?? DefaultActorRefMiddleware.Instance;
}
public ActorRef ActorOf(ActorPath path)
{
var endpoint = HttpActorEndpoint.From(client, serializer, mapper, path);
return new ActorRef(path, endpoint, middleware);
}
public StreamRef<TItem> StreamOf<TItem>(StreamPath path) => throw new NotImplementedException();
public ClientRef ClientOf(string path) => throw new NotImplementedException();
}
}
|
using System;
using System.Net.Http;
using System.Text.Json;
namespace Orleankka.Http
{
class HttpActorSystem : IActorSystem
{
readonly ActorRouteMapper mapper;
readonly HttpClient client;
readonly JsonSerializerOptions serializer;
readonly IActorRefMiddleware middleware;
public HttpActorSystem(HttpClient client, JsonSerializerOptions serializer, ActorRouteMapper mapper, IActorRefMiddleware middleware = null)
{
if (!client.BaseAddress.AbsoluteUri.EndsWith("/"))
throw new InvalidOperationException("The base address should end with /");
this.mapper = mapper;
this.client = client;
this.serializer = serializer;
this.middleware = middleware ?? DefaultActorRefMiddleware.Instance;
}
public ActorRef ActorOf(ActorPath path)
{
var endpoint = HttpActorEndpoint.From(client, serializer, mapper, path);
return new ActorRef(path, endpoint, middleware);
}
public StreamRef<TItem> StreamOf<TItem>(StreamPath path) => throw new NotImplementedException();
public ClientRef ClientOf(string path) => throw new NotImplementedException();
}
}
|
apache-2.0
|
C#
|
1c6afee8d82e04470c2c572240e39db1b0bb69b7
|
fix for testcase predicate
|
tudway/Qart,avao/Qart,mcraveiro/Qart
|
Src/Qart.Testing/Framework/TestSystem.cs
|
Src/Qart.Testing/Framework/TestSystem.cs
|
using Qart.Core.DataStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Qart.Testing.Framework
{
public class TestSystem : ITestSystem
{
public IDataStore DataStorage { get; private set; }
public IContentProcessor ContentProcessor { get; private set; }
private readonly Func<IDataStore, bool> _isTestCasePredicate;
public TestSystem(IDataStore dataStorage)
: this(dataStorage, _ => _.Contains(".test"))
{
}
public TestSystem(IDataStore dataStorage, Func<IDataStore, bool> isTestCasePredicate)
: this(dataStorage, isTestCasePredicate, null)
{
}
public TestSystem(IDataStore dataStorage, Func<IDataStore, bool> isTestCasePredicate, IContentProcessor processor)
{
_isTestCasePredicate = isTestCasePredicate;
ContentProcessor = processor;
DataStorage = dataStorage;
}
public TestCase GetTestCase(string id)
{
var testCaseDataStore = new ExtendedDataStore(new ScopedDataStore(DataStorage, id), (content, dataStore) => ContentProcessor.Process(content, dataStore));
return new TestCase(id, this, testCaseDataStore);
}
public IEnumerable<string> GetTestCaseIds()
{
return DataStorage.GetAllGroups().Concat(new[] { "." }).Where(_ => _isTestCasePredicate(new ScopedDataStore(DataStorage, _)));
}
}
}
|
using Qart.Core.DataStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Qart.Testing.Framework
{
public class TestSystem : ITestSystem
{
public IDataStore DataStorage { get; private set; }
public IContentProcessor ContentProcessor { get; private set; }
private readonly Func<IDataStore, bool> _isTestCasePredicate;
public TestSystem(IDataStore dataStorage)
: this(dataStorage, _ => _.Contains(".test"))
{
}
public TestSystem(IDataStore dataStorage, Func<IDataStore, bool> isTestCasePredicate)
: this(dataStorage, isTestCasePredicate, null)
{
}
public TestSystem(IDataStore dataStorage, Func<IDataStore, bool> isTestCasePredicate, IContentProcessor processor)
{
_isTestCasePredicate = isTestCasePredicate;
ContentProcessor = processor;
DataStorage = dataStorage;
}
public TestCase GetTestCase(string id)
{
var testCaseDataStore = new ExtendedDataStore(new ScopedDataStore(DataStorage, id), (content, dataStore) => ContentProcessor.Process(content, dataStore));
return new TestCase(id, this, testCaseDataStore);
}
public IEnumerable<string> GetTestCaseIds()
{
return DataStorage.GetAllGroups().Concat(new[] { "." }).Where(_ => _isTestCasePredicate(new ScopedDataStore(DataStorage, _)) != null);
}
}
}
|
apache-2.0
|
C#
|
1a89733ca6a94050f8892f5ba255e015241775fc
|
Fix NullReferenceException when RemoteIpAddress is null
|
MiniProfiler/dotnet,MiniProfiler/dotnet
|
src/MiniProfiler.AspNetCore/MiniProfilerOptions.cs
|
src/MiniProfiler.AspNetCore/MiniProfilerOptions.cs
|
using System;
using Microsoft.AspNetCore.Http;
using StackExchange.Profiling.Internal;
namespace StackExchange.Profiling
{
/// <summary>
/// Options for configuring MiniProfiler
/// </summary>
public class MiniProfilerOptions : MiniProfilerBaseOptions
{
/// <summary>
/// The path under which ALL routes are registered in, defaults to the application root. For example, "/myDirectory/" would yield
/// "/myDirectory/includes.min.js" rather than "/mini-profiler-resources/includes.min.js"
/// Any setting here should be absolute for the application, e.g. "/myDirectory/"
/// </summary>
public PathString RouteBasePath { get; set; } = "/mini-profiler-resources";
/// <summary>
/// Set a function to control whether a given request should be profiled at all.
/// </summary>
public Func<HttpRequest, bool> ShouldProfile { get; set; } = _ => true;
/// <summary>
/// A function that determines who can access the MiniProfiler results URL and list URL. It should return true when
/// the request client has access to results, false for a 401 to be returned. HttpRequest parameter is the current request and
/// </summary>
/// <remarks>
/// The HttpRequest parameter that will be passed into this function should never be null.
/// </remarks>
public Func<HttpRequest, bool> ResultsAuthorize { get; set; }
/// <summary>
/// Special authorization function that is called for the list results (listing all the profiling sessions),
/// we also test for results authorize always. This must be set and return true, to enable the listing feature.
/// </summary>
public Func<HttpRequest, bool> ResultsListAuthorize { get; set; }
/// <summary>
/// Function to provide the unique user ID based on the request, to store MiniProfiler IDs user
/// </summary>
public Func<HttpRequest, string> UserIdProvider { get; set; } = request => request.HttpContext.Connection.RemoteIpAddress?.ToString();
}
}
|
using System;
using Microsoft.AspNetCore.Http;
using StackExchange.Profiling.Internal;
namespace StackExchange.Profiling
{
/// <summary>
/// Options for configuring MiniProfiler
/// </summary>
public class MiniProfilerOptions : MiniProfilerBaseOptions
{
/// <summary>
/// The path under which ALL routes are registered in, defaults to the application root. For example, "/myDirectory/" would yield
/// "/myDirectory/includes.min.js" rather than "/mini-profiler-resources/includes.min.js"
/// Any setting here should be absolute for the application, e.g. "/myDirectory/"
/// </summary>
public PathString RouteBasePath { get; set; } = "/mini-profiler-resources";
/// <summary>
/// Set a function to control whether a given request should be profiled at all.
/// </summary>
public Func<HttpRequest, bool> ShouldProfile { get; set; } = _ => true;
/// <summary>
/// A function that determines who can access the MiniProfiler results URL and list URL. It should return true when
/// the request client has access to results, false for a 401 to be returned. HttpRequest parameter is the current request and
/// </summary>
/// <remarks>
/// The HttpRequest parameter that will be passed into this function should never be null.
/// </remarks>
public Func<HttpRequest, bool> ResultsAuthorize { get; set; }
/// <summary>
/// Special authorization function that is called for the list results (listing all the profiling sessions),
/// we also test for results authorize always. This must be set and return true, to enable the listing feature.
/// </summary>
public Func<HttpRequest, bool> ResultsListAuthorize { get; set; }
/// <summary>
/// Function to provide the unique user ID based on the request, to store MiniProfiler IDs user
/// </summary>
public Func<HttpRequest, string> UserIdProvider { get; set; } = request => request.HttpContext.Connection.RemoteIpAddress.ToString();
}
}
|
mit
|
C#
|
ac6b8cfbb96a40948d4d9d18b44cc982e9a219f9
|
clean up
|
asipe/Nucs,asipe/Nucs
|
src/Nucs.UnitTests/Serialization/SerializerTest.cs
|
src/Nucs.UnitTests/Serialization/SerializerTest.cs
|
using NUnit.Framework;
using Nucs.Core.Model.External;
using Nucs.Core.Serialization;
namespace Nucs.UnitTests.Serialization {
[TestFixture]
public class SerializerTest : NucsBaseTestCase {
[Test]
public void TestBasicSerialization() {
var serializer = new Serializer();
var expected = CA<Plan>();
var json = serializer.Serialize(expected);
Compare(serializer.Deserialize<Plan>(json), expected);
}
}
}
|
using NUnit.Framework;
using Nucs.Core.Model;
using Nucs.Core.Model.External;
using Nucs.Core.Serialization;
namespace Nucs.UnitTests.Serialization {
[TestFixture]
public class SerializerTest : NucsBaseTestCase {
[Test]
public void TestBasicSerialization() {
var serializer = new Serializer();
var expected = CA<Plan>();
var json = serializer.Serialize(expected);
Compare(serializer.Deserialize<Plan>(json), expected);
}
}
}
|
mit
|
C#
|
b2fade0d7286817139363bf4b62d99cc22577422
|
Add XML doc to Verbosity
|
AMDL/amdl2maml
|
amdl2maml/Converter.Console/Verbosity.cs
|
amdl2maml/Converter.Console/Verbosity.cs
|
using System.ComponentModel;
namespace Amdl.Maml.Converter.Console
{
/// <summary>
/// Verbosity.
/// </summary>
enum Verbosity
{
/// <summary>
/// No output.
/// </summary>
[Description("No output")]
Silent,
/// <summary>
/// Minimal output.
/// </summary>
[Description("Minimal output")]
Minimal,
/// <summary>
/// Normal output.
/// </summary>
[Description("Normal output")]
Normal,
/// <summary>
/// Detailed output.
/// </summary>
[Description("Detailed output")]
Detailed,
/// <summary>
/// Very detailed output.
/// </summary>
[Description("Very detailed output")]
Insane,
}
}
|
using System.ComponentModel;
namespace Amdl.Maml.Converter.Console
{
enum Verbosity
{
[Description("No output")]
Silent,
[Description("Minimal output")]
Minimal,
[Description("Normal output")]
Normal,
[Description("Detailed output")]
Detailed,
[Description("Very detailed output")]
Insane,
}
}
|
apache-2.0
|
C#
|
4f90e5d04e241368aa4158c955d87d25a8fdf288
|
exclude cases when classifier is null
|
strotz/pustota,strotz/pustota,strotz/pustota
|
src/Pustota.Maven/Actions/ApplyClassifierAction.cs
|
src/Pustota.Maven/Actions/ApplyClassifierAction.cs
|
using System.Linq;
using Pustota.Maven.Models;
namespace Pustota.Maven.Actions
{
public class ApplyClassifierAction
{
private readonly IProjectsRepository _projects;
private readonly string _classifierName;
private readonly string _classifierValue;
public ApplyClassifierAction(IProjectsRepository projects, string classifierName, string classifierValue)
{
_projects = projects;
_classifierName = classifierName;
_classifierValue = classifierValue;
}
internal static string WrapProperty(string propertyName)
{
return "${" + propertyName + "}";
}
public void Execute()
{
string classifier = WrapProperty(_classifierName);
foreach (var dependency in _projects.AllProjects.SelectMany(p => p.Operations().AllDependencies).Where(d => !string.IsNullOrEmpty(d.Classifier) && d.Classifier.Contains(classifier)))
{
dependency.Classifier = dependency.Classifier.Replace(classifier, _classifierValue);
}
}
}
}
|
using System.Linq;
using Pustota.Maven.Models;
namespace Pustota.Maven.Actions
{
public class ApplyClassifierAction
{
private readonly IProjectsRepository _projects;
private readonly string _classifierName;
private readonly string _classifierValue;
public ApplyClassifierAction(IProjectsRepository projects, string classifierName, string classifierValue)
{
_projects = projects;
_classifierName = classifierName;
_classifierValue = classifierValue;
}
internal static string WrapProperty(string propertyName)
{
return "${" + propertyName + "}";
}
public void Execute()
{
string classifier = WrapProperty(_classifierName);
foreach (var dependency in _projects.AllProjects.SelectMany(p => p.Operations().AllDependencies).Where(d => d.Classifier.Contains(classifier)))
{
dependency.Classifier = dependency.Classifier.Replace(classifier, _classifierValue);
}
}
}
}
|
mit
|
C#
|
8913e277fda21727032fe2d8292c97aa53bf9dd4
|
increment patch version,
|
jwChung/Experimentalism,jwChung/Experimentalism
|
build/CommonAssemblyInfo.cs
|
build/CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.23.1")]
[assembly: AssemblyInformationalVersion("0.23.1")]
/*
* Version 0.23.1
*
* - [FIX] introduced Jwc.Expereiment.AssemblyFixtureConfigurationAttribute
* instead of Jwc.Expereiment.Xunit.AssemblyCustomizationAttribute.
* (BREAKING-CHANGE)
*
* - [FIX] moved DefaultFixtureFactory from Jwc.Expereiment.Xunit to
* Jwc.Expereiment. (BREAKING-CHANGE)
*
* - [FIX] introduced DefaultFixtureFactoryConfigurationAttribute to supply the
* default factory of test fixture.
*/
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.23.0")]
[assembly: AssemblyInformationalVersion("0.23.0")]
/*
* Version 0.23.1
*
* - [FIX] introduced Jwc.Expereiment.AssemblyFixtureConfigurationAttribute
* instead of Jwc.Expereiment.Xunit.AssemblyCustomizationAttribute.
* (BREAKING-CHANGE)
*
* - [FIX] moved DefaultFixtureFactory from Jwc.Expereiment.Xunit to
* Jwc.Expereiment. (BREAKING-CHANGE)
*
* - [FIX] introduced DefaultFixtureFactoryConfigurationAttribute to supply the
* default factory of test fixture.
*/
|
mit
|
C#
|
b23682c1268d9c9e78c053a4a3e9a31e0d56b0ad
|
Add failing test case for setting colour at creation
|
ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework
|
osu.Framework.Tests/Visual/UserInterface/TestSceneColourPicker.cs
|
osu.Framework.Tests/Visual/UserInterface/TestSceneColourPicker.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneColourPicker : FrameworkTestScene
{
[Test]
public void TestExternalColourSetAfterCreation()
{
ColourPicker colourPicker = null;
AddStep("create picker", () => Child = colourPicker = new BasicColourPicker());
AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod);
AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
}
[Test]
public void TestExternalColourSetAtCreation()
{
ColourPicker colourPicker = null;
AddStep("create picker", () => Child = colourPicker = new BasicColourPicker
{
Current = { Value = Colour4.Goldenrod }
});
AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneColourPicker : FrameworkTestScene
{
[SetUpSteps]
public void SetUpSteps()
{
ColourPicker colourPicker = null;
AddStep("create picker", () => Child = colourPicker = new BasicColourPicker());
AddStep("set colour externally", () => colourPicker.Current.Value = Colour4.Goldenrod);
AddAssert("colour is correct", () => colourPicker.Current.Value == Colour4.Goldenrod);
}
}
}
|
mit
|
C#
|
adae810b3860d3adcd241aedf30fc03f2778ac10
|
remove Home/About and Home/Contact from tests
|
jittuu/AzureLog,jittuu/AzureLog,jittuu/AzureLog
|
AzureLog.Web.Tests/Controllers/HomeControllerTest.cs
|
AzureLog.Web.Tests/Controllers/HomeControllerTest.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AzureLog.Web;
using AzureLog.Web.Controllers;
namespace AzureLog.Web.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AzureLog.Web;
using AzureLog.Web.Controllers;
namespace AzureLog.Web.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
|
mit
|
C#
|
573a75a955a0eb52e6c1f7cb6916a0e2cb5c2c9e
|
Fix compile null ref
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Models/VehicleListViewModel.cs
|
Battery-Commander.Web/Models/VehicleListViewModel.cs
|
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BatteryCommander.Web.Models
{
public class VehicleListViewModel
{
public IEnumerable<SelectListItem> Soldiers { get; set; } = Enumerable.Empty<SelectListItem>();
public Array Statuses => Enum.GetNames(typeof(Vehicle.VehicleStatus));
public Array Locations => Enum.GetNames(typeof(Vehicle.VehicleLocation));
public IEnumerable<Vehicle> Vehicles { get; set; } = Enumerable.Empty<Vehicle>();
public int FMC => Vehicles.Where(_ => _.Available).Count();
public int? PAX => Vehicles.Where(_ => _.Available).Select(_ => _.Occupancy).Sum();
public int Capacity => Vehicles.Where(_ => _.Available).Select(_ => _.TotalCapacity).Sum();
}
}
|
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BatteryCommander.Web.Models
{
public class VehicleListViewModel
{
public IEnumerable<SelectListItem> Soldiers { get; set; } = Enumerable.Empty<SelectListItem>();
public Array Statuses => Enum.GetNames(typeof(Vehicle.VehicleStatus));
public Array Locations => Enum.GetNames(typeof(Vehicle.VehicleLocation));
public IEnumerable<Vehicle> Vehicles { get; set; } = Enumerable.Empty<Vehicle>();
public int FMC => Vehicles.Where(_ => _.Available).Count();
public int PAX => Vehicles.Where(_ => _.Available).Select(_ => _.Occupancy).Sum();
public int Capacity => Vehicles.Where(_ => _.Available).Select(_ => _.TotalCapacity).Sum();
}
}
|
mit
|
C#
|
63adac9937afd03f4bf0addde58dcfc3a589dc97
|
Fix symmetric algorithms benchmarks
|
sergezhigunov/OpenGost
|
benchmarks/OpenGost.Security.Cryptography.Benchmarks/SymmetricAlgorithmBenchmark.cs
|
benchmarks/OpenGost.Security.Cryptography.Benchmarks/SymmetricAlgorithmBenchmark.cs
|
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using BenchmarkDotNet.Attributes;
namespace OpenGost.Security.Cryptography.Benchmarks
{
public abstract class SymmetricAlgorithmBenchmark<T> : IDisposable
where T : SymmetricAlgorithm, new()
{
private static readonly byte[] _data =
Encoding.ASCII.GetBytes("The quick brown fox jumped over the extremely lazy frogs!");
private readonly byte[] _encryptedData;
private bool _disposed;
protected T SymmetricAlgorithm = new T { Padding = PaddingMode.Zeros };
protected SymmetricAlgorithmBenchmark()
{
using var encryptor = SymmetricAlgorithm.CreateEncryptor();
using var output = new MemoryStream();
using (var input = new MemoryStream(_data))
using (var cryptoStream = new CryptoStream(input, encryptor, CryptoStreamMode.Read))
cryptoStream.CopyTo(output);
_encryptedData = output.ToArray();
}
[Benchmark]
public byte[] EncryptData()
{
using var encryptor = SymmetricAlgorithm.CreateEncryptor();
using var output = new MemoryStream();
using (var input = new MemoryStream(_data))
using (var cryptoStream = new CryptoStream(input, encryptor, CryptoStreamMode.Read))
cryptoStream.CopyTo(output);
return output.ToArray();
}
[Benchmark]
public byte[] DecryptData()
{
using var decryptor = SymmetricAlgorithm.CreateDecryptor();
using var output = new MemoryStream();
using (var input = new MemoryStream(_encryptedData))
using (var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
cryptoStream.CopyTo(output);
return output.ToArray();
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
SymmetricAlgorithm.Dispose();
_disposed = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
|
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using BenchmarkDotNet.Attributes;
namespace OpenGost.Security.Cryptography.Benchmarks
{
public abstract class SymmetricAlgorithmBenchmark<T> : IDisposable
where T : SymmetricAlgorithm, new()
{
private static readonly byte[] _data =
Encoding.ASCII.GetBytes("The quick brown fox jumped over the extremely lazy frogs!");
private readonly byte[] _encryptedData;
private bool _disposed;
protected T SymmetricAlgorithm = new T();
protected SymmetricAlgorithmBenchmark()
{
using var encryptor = SymmetricAlgorithm.CreateEncryptor();
_encryptedData = encryptor.TransformFinalBlock(_data, 0, _data.Length);
}
[Benchmark]
public byte[] EncryptData()
{
using var encryptor = SymmetricAlgorithm.CreateEncryptor();
using var output = new MemoryStream();
using (var input = new MemoryStream(_data))
using (var cryptoStream = new CryptoStream(input, encryptor, CryptoStreamMode.Read))
cryptoStream.CopyTo(output);
return output.ToArray();
}
[Benchmark]
public byte[] DecryptData()
{
using var decryptor = SymmetricAlgorithm.CreateDecryptor();
using var output = new MemoryStream();
using (var input = new MemoryStream(_encryptedData))
using (var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
cryptoStream.CopyTo(output);
return output.ToArray();
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
SymmetricAlgorithm.Dispose();
_disposed = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
|
mit
|
C#
|
c765b222f13548aea8bee32112b519fb1bb1ae50
|
Make plots more informationail
|
joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net
|
Joinrpg/Views/Shared/_PlotForCharacterPartial.cshtml
|
Joinrpg/Views/Shared/_PlotForCharacterPartial.cshtml
|
@using JoinRpg.Web.Models.Plot
@model IEnumerable<PlotElementViewModel>
@if (Model != null && Model.Any())
{
<div class="panel panel-default">
<div class="panel-heading" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
@DisplayCount.OfX(Model.Count(), "загруз", "загруза", "загрузов")
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse" aria-labelledby="headingOne">
<div class="panel-body">
@if (Model.Any(item => item.Status == PlotStatus.InWork && !item.HasMasterAccess))
{
<p>
<b>Часть загрузов пока в работе и скрыта. Мастера откроют их вам, когда они будут готовы.</b>
</p>
}
@foreach (var plot in Model)
{
@Html.Partial("../Plot/ShowElementPartial", plot)
}
</div>
</div>
</div>
}
|
@using JoinRpg.Web.Models.Plot
@model IEnumerable<PlotElementViewModel>
@if (Model != null && Model.Any())
{
<div class="panel panel-default">
<div class="panel-heading" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Загрузы
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse" aria-labelledby="headingOne">
<div class="panel-body">
@if (Model.Any(item => item.Status == PlotStatus.InWork && !item.HasMasterAccess))
{
<p>
<b>Часть загрузов пока в работе и скрыта. Мастера откроют их вам, когда они будут готовы.</b>
</p>
}
@foreach (var plot in Model)
{
@Html.Partial("../Plot/ShowElementPartial", plot)
}
</div>
</div>
</div>
}
|
mit
|
C#
|
70a1497d20fade7bce1375cd58915aaffc4c48a1
|
Fix comments
|
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer
|
LmpClient/Systems/VesselFairingsSys/VesselFairing.cs
|
LmpClient/Systems/VesselFairingsSys/VesselFairing.cs
|
using LmpClient.VesselUtilities;
using System;
namespace LmpClient.Systems.VesselFairingsSys
{
/// <summary>
/// Class that maps a message class to a system class. This way we avoid the message caching issues
/// </summary>
public class VesselFairing
{
#region Fields and Properties
public double GameTime;
public Guid VesselId;
public uint PartFlightId;
#endregion
public void ProcessFairing()
{
if (!VesselCommon.DoVesselChecks(VesselId))
return;
var vessel = FlightGlobals.FindVessel(VesselId);
if (vessel == null) return;
var protoPart = VesselCommon.FindProtoPartInProtovessel(vessel.protoVessel, PartFlightId);
if (protoPart != null)
{
ProcessFairingChange(protoPart);
}
}
private static void ProcessFairingChange(ProtoPartSnapshot protoPart)
{
var module = VesselCommon.FindProtoPartModuleInProtoPart(protoPart, "ModuleProceduralFairing");
module?.moduleValues.SetValue("fsm", "st_flight_deployed");
module?.moduleValues.RemoveNodesStartWith("XSECTION");
try
{
(module?.moduleRef as ModuleProceduralFairing)?.DeployFairing();
}
catch (Exception)
{
//TODO reload the module
}
}
}
}
|
using System;
using LmpClient.Extensions;
using LmpClient.VesselUtilities;
namespace LmpClient.Systems.VesselFairingsSys
{
/// <summary>
/// Class that maps a message class to a system class. This way we avoid the message caching issues
/// </summary>
public class VesselFairing
{
#region Fields and Properties
public double GameTime;
public Guid VesselId;
public uint PartFlightId;
#endregion
public void ProcessFairing()
{
if (!VesselCommon.DoVesselChecks(VesselId))
return;
//Finding using persistentId failed, try searching it with the flightId...
var vessel = FlightGlobals.FindVessel(VesselId);
if (vessel == null) return;
var protoPart = VesselCommon.FindProtoPartInProtovessel(vessel.protoVessel, PartFlightId);
if (protoPart != null)
{
ProcessFairingChange(protoPart);
}
}
private static void ProcessFairingChange(ProtoPartSnapshot protoPart)
{
var module = VesselCommon.FindProtoPartModuleInProtoPart(protoPart, "ModuleProceduralFairing");
module?.moduleValues.SetValue("fsm", "st_flight_deployed");
module?.moduleValues.RemoveNodesStartWith("XSECTION");
try
{
(module?.moduleRef as ModuleProceduralFairing)?.DeployFairing();
}
catch (Exception)
{
//TODO reload the module
}
}
}
}
|
mit
|
C#
|
04297f0030701575741cf4923812708976717a45
|
Update ParserLanguage.cs
|
taotsetung/guild-translation-tool
|
GTT.Common/ParserLanguage.cs
|
GTT.Common/ParserLanguage.cs
|
namespace GTT.Common
{
public enum ParserLanguage
{
English = 2,
French = 3,
Russian = 4,
Italian = 5,
Spanish = 6,
Dutch = 7,
Korean = 8,
Japanese = 9,
Chinese = 10,
Portuguese = 11,
Czech = 12,
}
}
|
namespace GTT.Common
{
public enum ParserLanguage
{
English = 2,
French = 3,
Russian = 4,
Italian = 5,
Spanish = 6,
Dutch = 7,
Korean = 8,
Japanese = 9,
Chinese = 10,
Portuguese = 11,
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.