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 |
|---|---|---|---|---|---|---|---|---|
53aa46fd7a565e52dd6c4978aa44a7683e89b4ab | Disable native mac file dialogs in GtkOnMac engine | residuum/xwt,mono/xwt,TheBrainTech/xwt,lytico/xwt,antmicro/xwt,hwthomas/xwt,cra0zy/xwt,hamekoz/xwt,akrisiun/xwt | Xwt.Gtk.Mac/MacPlatformBackend.cs | Xwt.Gtk.Mac/MacPlatformBackend.cs | //
// GtkMacEngine.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.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 Xwt.GtkBackend;
using Xwt.Backends;
using AppKit;
namespace Xwt.Gtk.Mac
{
public class MacPlatformBackend: GtkPlatformBackend
{
public override void Initialize (ToolkitEngineBackend toolit)
{
/* var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.Init ();
}*/
toolit.RegisterBackend <IWebViewBackend,WebViewBackend> ();
toolit.RegisterBackend <DesktopBackend,GtkMacDesktopBackend> ();
toolit.RegisterBackend <FontBackendHandler,GtkMacFontBackendHandler> ();
toolit.RegisterBackend <IPopoverBackend,GtkMacPopoverBackend> ();
/* toolit.RegisterBackend <IOpenFileDialogBackend, GtkMacOpenFileDialogBackend> ();
toolit.RegisterBackend <ISaveFileDialogBackend, GtkMacSaveFileDialogBackend> ();
toolit.RegisterBackend <ISelectFolderDialogBackend, GtkMacSelectFolderBackend> ();*/
}
}
}
| //
// GtkMacEngine.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.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 Xwt.GtkBackend;
using Xwt.Backends;
using AppKit;
namespace Xwt.Gtk.Mac
{
public class MacPlatformBackend: GtkPlatformBackend
{
public override void Initialize (ToolkitEngineBackend toolit)
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.Init ();
}
toolit.RegisterBackend <IWebViewBackend,WebViewBackend> ();
toolit.RegisterBackend <DesktopBackend,GtkMacDesktopBackend> ();
toolit.RegisterBackend <FontBackendHandler,GtkMacFontBackendHandler> ();
toolit.RegisterBackend <IPopoverBackend,GtkMacPopoverBackend> ();
toolit.RegisterBackend <IOpenFileDialogBackend, GtkMacOpenFileDialogBackend> ();
toolit.RegisterBackend <ISaveFileDialogBackend, GtkMacSaveFileDialogBackend> ();
toolit.RegisterBackend <ISelectFolderDialogBackend, GtkMacSelectFolderBackend> ();
}
}
}
| mit | C# |
df7525b8d840e8accb19c116936b5c42dfce95a4 | use lowercase for issues to make v3 work. | mps/OctoNet | OctoNet/Models/Dto/IssueDto.cs | OctoNet/Models/Dto/IssueDto.cs | using Newtonsoft.Json;
namespace OctoNet.Models.Dto
{
[JsonObject]
public class IssueDto
{
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("body")]
public string body { get; set; }
[JsonProperty("assignee")]
public string assignee { get; set; }
[JsonProperty("milestone")]
public string milestone { get; set; }
[JsonProperty("labels")]
public string[] labels { get; set; }
}
} | using Newtonsoft.Json;
namespace OctoNet.Models.Dto
{
[JsonObject]
public class IssueDto
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("body")]
public string Body { get; set; }
[JsonProperty("assignee")]
public string Assignee { get; set; }
[JsonProperty("milestone")]
public string Milestone { get; set; }
[JsonProperty("labels")]
public string[] Labels { get; set; }
}
} | mit | C# |
78df04213b87fde4f41ae7868a7ff3f6ec734cd9 | Add an Explicit test that tries to use AsParallel(). It will hang after the exercise is completed, if the solution is the same as mine. | peterchase/parallel-workshop | ParallelWorkshopTests/Ex10WaitHalfWay/LimitedModeCharacterCounterTests.cs | ParallelWorkshopTests/Ex10WaitHalfWay/LimitedModeCharacterCounterTests.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lurchsoft.FileData;
using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay;
using NUnit.Framework;
namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay
{
[TestFixture]
public class LimitedModeCharacterCounterTests
{
[Test]
public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently()
{
LimitedModeCharacterCounter[] counters = CreateCounters();
Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray();
Task.WaitAll(tasks);
}
[Test, Explicit("This will probably hang, once you make it use your Barrier-based solution. Can you work out why?")]
public void GetCharCounts_UsingAsParallel()
{
LimitedModeCharacterCounter[] counters = CreateCounters();
var results = counters.AsParallel().Select(c => c.GetCharCounts()).ToArray();
Assert.That(results, Is.Not.Empty);
}
private static LimitedModeCharacterCounter[] CreateCounters()
{
const int NumConcurrent = 10;
ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray();
IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]);
// To solve the exercise, you may need to pass additional synchronisation information to the constructor.
var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray();
return counters;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lurchsoft.FileData;
using Lurchsoft.ParallelWorkshop.Ex10WaitHalfWay;
using NUnit.Framework;
namespace Lurchsoft.ParallelWorkshopTests.Ex10WaitHalfWay
{
[TestFixture]
public class LimitedModeCharacterCounterTests
{
[Test]
public void GetCharCounts_ShouldSucceed_WhenSeveralInstancesRunConcurrently()
{
const int NumConcurrent = 10;
ITextFile[] allFiles = EmbeddedFiles.AllFiles.ToArray();
IEnumerable<ITextFile> textFiles = Enumerable.Range(0, NumConcurrent).Select(i => allFiles[i % allFiles.Length]);
// To solve the exercise, you may need to pass additional synchronisation information to the constructor.
var counters = textFiles.Select(textFile => new LimitedModeCharacterCounter(textFile)).ToArray();
// When you've succeeded, try changing this to use AsParallel(). Does it still work? It didn't for me. Explain why!
Task[] tasks = counters.Select(c => (Task)Task.Factory.StartNew(() => c.GetCharCounts())).ToArray();
Task.WaitAll(tasks);
}
}
}
| apache-2.0 | C# |
8c567c63261e202b91ed79d6224646d205178b42 | Make GeneratorContext internal. | PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1 | Source/Eto/GeneratorContext.cs | Source/Eto/GeneratorContext.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eto
{
/// <summary>
/// Sets the current generator for a block of code,
/// and verifies that all objects created in that
/// block were created using that generator.
/// </summary>
internal class GeneratorContext : IDisposable
{
Generator previous;
Generator previousValidate;
public GeneratorContext(Generator g)
{
previous = Generator.Current;
previousValidate = Generator.ValidateGenerator;
Generator.Initialize(g);
Eto.Generator.ValidateGenerator = g;
}
public void Dispose()
{
Generator.Initialize(previous);
Generator.ValidateGenerator = previousValidate;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eto
{
/// <summary>
/// Sets the current generator for a block of code,
/// and verifies that all objects created in that
/// block were created using that generator.
/// </summary>
public class GeneratorContext : IDisposable
{
Generator previous;
Generator previousValidate;
public GeneratorContext(Generator g)
{
previous = Generator.Current;
previousValidate = Generator.ValidateGenerator;
Generator.Initialize(g);
Eto.Generator.ValidateGenerator = g;
}
public void Dispose()
{
Generator.Initialize(previous);
Generator.ValidateGenerator = previousValidate;
}
}
}
| bsd-3-clause | C# |
a35dba3edc47a1f3a58b0874c3396cff32310f92 | Add a space. | darrencauthon/AutoMoq,darrencauthon/AutoMoq,darrencauthon/AutoMoq | AutoMoq/AutoMoq/Unity/AutoMockingBuilderStrategy.cs | AutoMoq/AutoMoq/Unity/AutoMockingBuilderStrategy.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.ObjectBuilder2;
using Moq;
namespace AutoMoq.Unity
{
public class AutoMockingBuilderStrategy : BuilderStrategy
{
private readonly MockFactory mockFactory;
private readonly IEnumerable<Type> registeredTypes;
public AutoMockingBuilderStrategy(IEnumerable<Type> registeredTypes)
{
mockFactory = new MockFactory(MockBehavior.Loose);
this.registeredTypes = registeredTypes;
}
public override void PreBuildUp(IBuilderContext context)
{
var type = GetTheTypeFromTheBuilderContext(context);
if (AMockObjectShouldBeCreatedForThisType(type))
context.Existing = CreateAMockObject(type).Object;
}
#region private methods
private bool AMockObjectShouldBeCreatedForThisType(Type type)
{
return TypeIsNotRegistered(type) && type.IsInterface;
}
private static Type GetTheTypeFromTheBuilderContext(IBuilderContext context)
{
return ((NamedTypeBuildKey)context.OriginalBuildKey).Type;
}
private bool TypeIsNotRegistered(Type type)
{
return registeredTypes.Any(x => x.Equals(type)) == false;
}
private Mock CreateAMockObject(Type type)
{
var createMethod = GenerateAnInterfaceMockCreationMethod(type);
return InvokeTheMockCreationMethod(createMethod);
}
private Mock InvokeTheMockCreationMethod(MethodInfo createMethod)
{
return (Mock)createMethod.Invoke(mockFactory, new object[] {new List<object>().ToArray()});
}
private MethodInfo GenerateAnInterfaceMockCreationMethod(Type type)
{
var createMethodWithNoParameters = mockFactory.GetType().GetMethod("Create", EmptyArgumentList());
return createMethodWithNoParameters.MakeGenericMethod(new[] {type});
}
private static Type[] EmptyArgumentList()
{
return new[] {typeof (object[])};
}
#endregion
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.ObjectBuilder2;
using Moq;
namespace AutoMoq.Unity
{
public class AutoMockingBuilderStrategy : BuilderStrategy
{
private readonly MockFactory mockFactory;
private readonly IEnumerable<Type> registeredTypes;
public AutoMockingBuilderStrategy(IEnumerable<Type> registeredTypes)
{
mockFactory = new MockFactory(MockBehavior.Loose);
this.registeredTypes = registeredTypes;
}
public override void PreBuildUp(IBuilderContext context)
{
var type = GetTheTypeFromTheBuilderContext(context);
if (AMockObjectShouldBeCreatedForThisType(type))
context.Existing = CreateAMockObject(type).Object;
}
#region private methods
private bool AMockObjectShouldBeCreatedForThisType(Type type)
{
return TypeIsNotRegistered(type) && type.IsInterface;
}
private static Type GetTheTypeFromTheBuilderContext(IBuilderContext context)
{
return ((NamedTypeBuildKey)context.OriginalBuildKey).Type;
}
private bool TypeIsNotRegistered(Type type)
{
return registeredTypes.Any(x => x.Equals(type)) == false;
}
private Mock CreateAMockObject(Type type)
{
var createMethod = GenerateAnInterfaceMockCreationMethod(type);
return InvokeTheMockCreationMethod(createMethod);
}
private Mock InvokeTheMockCreationMethod(MethodInfo createMethod)
{
return (Mock)createMethod.Invoke(mockFactory, new object[] {new List<object>().ToArray()});
}
private MethodInfo GenerateAnInterfaceMockCreationMethod(Type type)
{
var createMethodWithNoParameters = mockFactory.GetType().GetMethod("Create", EmptyArgumentList());
return createMethodWithNoParameters.MakeGenericMethod(new[] {type});
}
private static Type[] EmptyArgumentList()
{
return new[] {typeof (object[])};
}
#endregion
}
} | mit | C# |
75acaeb22853b5eb82077e11e7f21ec569e1f5cd | Use Task.Run instead of .Start() | FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative,FetzenRndy/Creative | Creative/StatoBot/StatoBot.Analytics/AnalyzerBot.cs | Creative/StatoBot/StatoBot.Analytics/AnalyzerBot.cs | using System;
using System.IO;
using System.Timers;
using System.Threading.Tasks;
using StatoBot.Core;
namespace StatoBot.Analytics
{
public class AnalyzerBot : TwitchBot
{
public ChatAnalyzer Analyzer;
public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel)
{
Analyzer = new ChatAnalyzer();
OnMessageReceived += AnalyzeMessage;
}
private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args)
{
Task.Run(() =>
Analyzer
.AnalyzeAsync(args)
);
}
}
}
| using System;
using System.IO;
using System.Timers;
using StatoBot.Core;
namespace StatoBot.Analytics
{
public class AnalyzerBot : TwitchBot
{
public ChatAnalyzer Analyzer;
public AnalyzerBot(Credentials credentials, string channel) : base(credentials, channel)
{
Analyzer = new ChatAnalyzer();
OnMessageReceived += AnalyzeMessage;
}
private void AnalyzeMessage(object sender, OnMessageReceivedEventArgs args)
{
Analyzer
.AnalyzeAsync(args)
.Start();
}
}
}
| mit | C# |
eb1ecc6fc77daad761d4ab947ed518f131a05cdb | put dynamic objects into a common hierarchy | guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft | unity/Assets/Scripts/Engine/GameObjects/MonoBehaviourEx.cs | unity/Assets/Scripts/Engine/GameObjects/MonoBehaviourEx.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonoBehaviourEx : MonoBehaviour
{
static GameObject m_dynHolder;
public GameObject Instantiate(GameObject prefab)
{
return Instantiate(prefab, Vector3.zero, Quaternion.identity);
}
public GameObject Instantiate(GameObject prefab, Vector3 position, Quaternion rotation)
{
if (m_dynHolder == null)
{
m_dynHolder = new GameObject("_Dyn");
m_dynHolder.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
}
GameObject gameObject = MonoBehaviour.Instantiate(prefab, position, rotation);
if (gameObject != null)
{
gameObject.transform.SetParent(m_dynHolder.transform);
}
return gameObject;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonoBehaviourEx : MonoBehaviour
{
public GameObject Instantiate(GameObject prefab)
{
return MonoBehaviour.Instantiate(prefab);
}
public GameObject Instantiate(GameObject parent, Vector3 position, Quaternion rotation)
{
return MonoBehaviour.Instantiate(parent, position, rotation);
}
}
| mit | C# |
aec5bd0355354ada7a7e2b4d8427cf94fb9b67ac | Update AssemblyInfo.cs | dstiert/Wox,danisein/Wox,AlexCaranha/Wox,AlexCaranha/Wox,yozora-hitagi/Saber,mika76/Wox,dstiert/Wox,18098924759/Wox,JohnTheGr8/Wox,shangvven/Wox,danisein/Wox,zlphoenix/Wox,gnowxilef/Wox,apprentice3d/Wox,apprentice3d/Wox,EmuxEvans/Wox,18098924759/Wox,mika76/Wox,EmuxEvans/Wox,AlexCaranha/Wox,gnowxilef/Wox,yozora-hitagi/Saber,JohnTheGr8/Wox,renzhn/Wox,Launchify/Launchify,derekforeman/Wox,vebin/Wox,vebin/Wox,gnowxilef/Wox,kayone/Wox,renzhn/Wox,kdar/Wox,jondaniels/Wox,Launchify/Launchify,medoni/Wox,jondaniels/Wox,sanbinabu/Wox,kayone/Wox,dstiert/Wox,shangvven/Wox,vebin/Wox,derekforeman/Wox,shangvven/Wox,zlphoenix/Wox,sanbinabu/Wox,Megasware128/Wox,EmuxEvans/Wox,kayone/Wox,sanbinabu/Wox,Megasware128/Wox,mika76/Wox,medoni/Wox,18098924759/Wox,apprentice3d/Wox,kdar/Wox,kdar/Wox,derekforeman/Wox | Wox/Properties/AssemblyInfo.cs | Wox/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyTitle("Wox")]
[assembly: AssemblyDescription("https://github.com/qianlifeng/Wox")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Wox")]
[assembly: AssemblyCopyright("The MIT License (MIT)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly
)]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Wox")]
[assembly: AssemblyDescription("https://github.com/qianlifeng/Wox")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Wox")]
[assembly: AssemblyCopyright("The MIT License (MIT)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请在
//<PropertyGroup> 中的 .csproj 文件中
//设置 <UICulture>CultureYouAreCodingWith</UICulture>。例如,如果您在源文件中
//使用的是美国英语,请将 <UICulture> 设置为 en-US。然后取消
//对以下 NeutralResourceLanguage 特性的注释。更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(在页面或应用程序资源词典中
// 未找到某个资源的情况下使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(在页面、应用程序或任何主题特定资源词典中
// 未找到某个资源的情况下使用)
)]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | mit | C# |
77b7f3c1dcbe51da06652054bb21239e4925a295 | Add additional tests | restsharp/RestSharp,PKRoma/RestSharp | RestSharp.Tests/RequestHeaderTests.cs | RestSharp.Tests/RequestHeaderTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace RestSharp.Tests
{
public class RequestHeaderTests
{
[Test]
public void AddHeaders_SameCaseDuplicatesExist_ThrowsException()
{
ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Accept", "application/json"),
new KeyValuePair<string, string>("Accept-Language", "en-us,en;q=0.5"),
new KeyValuePair<string, string>("Keep-Alive", "300"),
new KeyValuePair<string, string>("Accept", "application/json")
};
RestRequest request = new RestRequest();
ArgumentException exception = Assert.Throws<ArgumentException>(() => request.AddHeaders(headers));
Assert.AreEqual("Duplicate header names exist: ACCEPT", exception.Message);
}
[Test]
public void AddHeaders_DifferentCaseDuplicatesExist_ThrowsException()
{
ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Accept", "application/json"),
new KeyValuePair<string, string>("Accept-Language", "en-us,en;q=0.5"),
new KeyValuePair<string, string>("Keep-Alive", "300"),
new KeyValuePair<string, string>("acCEpt", "application/json")
};
RestRequest request = new RestRequest();
ArgumentException exception = Assert.Throws<ArgumentException>(() => request.AddHeaders(headers));
Assert.AreEqual("Duplicate header names exist: ACCEPT", exception.Message);
}
[Test]
public void AddHeaders_NoDuplicatesExist_Has3Headers()
{
ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Accept", "application/json"),
new KeyValuePair<string, string>("Accept-Language", "en-us,en;q=0.5"),
new KeyValuePair<string, string>("Keep-Alive", "300")
};
RestRequest request = new RestRequest();
request.AddHeaders(headers);
IEnumerable<Parameter> httpParameters = request.Parameters.Where(parameter => parameter.Type == ParameterType.HttpHeader);
Assert.AreEqual(3, httpParameters.Count());
}
[Test]
public void AddHeaders_NoDuplicatesExistUsingDictionary_Has3Headers()
{
Dictionary<string, string> headers = new Dictionary<string, string>()
{
{ "Accept", "application/json" },
{ "Accept-Language", "en-us,en;q=0.5" },
{ "Keep-Alive", "300" }
};
RestRequest request = new RestRequest();
request.AddHeaders(headers);
IEnumerable<Parameter> httpParameters = request.Parameters.Where(parameter => parameter.Type == ParameterType.HttpHeader);
Assert.AreEqual(3, httpParameters.Count());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace RestSharp.Tests
{
public class RequestHeaderTests
{
[Test]
public void AddHeaders_SameCaseDuplicatesExist_ThrowsException()
{
ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Accept", "application/json"),
new KeyValuePair<string, string>("Accept-Language", "en-us,en;q=0.5"),
new KeyValuePair<string, string>("Keep-Alive", "300"),
new KeyValuePair<string, string>("Accept", "application/json")
};
RestRequest request = new RestRequest();
ArgumentException exception = Assert.Throws<ArgumentException>(() => request.AddHeaders(headers));
Assert.AreEqual("Duplicate header names exist: ACCEPT", exception.Message);
}
}
}
| apache-2.0 | C# |
b039c5ced077058d2fa9031ce54681a15e341283 | Monitor for database connection | jona8690/Project-Exam | RoomReservationSystem/DAL/Database.cs | RoomReservationSystem/DAL/Database.cs | using System;
using System.Data.SqlClient;
using System.Threading;
namespace DAL {
public abstract class Database {
private static string _connInfo = DatabaseConn.ConnString;
private static SqlConnection _conn;
protected object locked;
protected SqlConnection OpenConnection() {
Monitor.Enter(locked);
if (_conn == null) {
_conn = new SqlConnection(_connInfo);
}
_conn.Open();
return _conn;
}
protected void CloseConnection() {
_conn.Close();
Monitor.Exit(locked);
}
}
}
| using System;
using System.Data.SqlClient;
namespace DAL {
public abstract class Database {
private static string _connInfo = DatabaseConn.ConnString;
private static SqlConnection _conn;
protected SqlConnection OpenConnection() {
if (_conn == null) {
_conn = new SqlConnection(_connInfo);
}
_conn.Open();
return _conn;
}
protected void CloseConnection() {
_conn.Close();
}
}
}
| mit | C# |
48b4864e73427b21bd60b694561bd0af725865b4 | Update ShortBioOrTagLine and use IAmACommunityMember (#387) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/DevlinDuldulao.cs | src/Firehose.Web/Authors/DevlinDuldulao.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class DevlinDuldulao : IFilterMyBlogPosts, IAmACommunityMember
{
public string FirstName => "Devlin";
public string LastName => "Duldulao";
public string ShortBioOrTagLine => "Xamarin certified, a trainer, a speaker";
public string StateOrRegion => "Manila";
public string EmailAddress => "webmasterdevlin@gmail.com";
public string TwitterHandle => "DevlinDuldulao";
public string GitHubHandle => "webmasterdevlin";
public string GravatarHash => "7dc408ee2ccfa6fb9eac30cdf08926bf";
public GeoPosition Position => new GeoPosition(14.6841162, 120.9921632);
public Uri WebSite => new Uri("https://devlinduldulao.pro/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://devlinduldulao.pro/feed/"); } }
public bool Filter(SyndicationItem item) =>
item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using Firehose.Web.Infrastructure;
namespace Firehose.Web
{
public class DevlinDuldulao : IFilterMyBlogPosts
{
public string FirstName => "Devlin";
public string LastName => "Duldulao";
public string ShortBioOrTagLine => "";
public string StateOrRegion => "Manila";
public string EmailAddress => "webmasterdevlin@gmail.com";
public string TwitterHandle => "DevlinDuldulao";
public string GitHubHandle => "webmasterdevlin";
public string GravatarHash => "7dc408ee2ccfa6fb9eac30cdf08926bf";
public GeoPosition Position => new GeoPosition(14.6841162, 120.9921632);
public Uri WebSite => new Uri("https://devlinduldulao.pro/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://devlinduldulao.pro/feed/"); } }
public bool Filter(SyndicationItem item) =>
item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
} | mit | C# |
6b0662a9435113b68e546cd28e4d2112659c3bec | Use HasMore and NextOffset | libertyernie/WeasylSync | CrosspostSharp3/DeviantArt/DeviantArtFolderSelectionForm.cs | CrosspostSharp3/DeviantArt/DeviantArtFolderSelectionForm.cs | using DeviantArtFs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CrosspostSharp3 {
public partial class DeviantArtFolderSelectionForm : Form {
public IEnumerable<DeviantArtFs.Gallery.Folder> InitialFolders { get; set; }
private readonly IDeviantArtAccessToken _token;
private List<DeviantArtFs.Gallery.Folder> _selectedFolders;
public IEnumerable<DeviantArtFs.Gallery.Folder> SelectedFolders => _selectedFolders;
public DeviantArtFolderSelectionForm(IDeviantArtAccessToken token) {
InitializeComponent();
_token = token;
_selectedFolders = new List<DeviantArtFs.Gallery.Folder>();
}
private async void DeviantArtFolderSelectionForm_Load(object sender, EventArgs e) {
try {
this.Enabled = false;
var resp = await DeviantArtFs.Gallery.Folders.ExecuteAsync(_token, new DeviantArtFs.Gallery.FoldersRequest { });
while (true) {
foreach (var f in resp.Results) {
var chk = new CheckBox {
AutoSize = true,
Text = f.Name,
Checked = InitialFolders?.Any(f2 => f.Folderid == f2.Folderid) == true
};
chk.CheckedChanged += (o, ea) => {
if (chk.Checked) {
_selectedFolders.Add(f);
} else {
_selectedFolders.Remove(f);
}
};
flowLayoutPanel1.Controls.Add(chk);
}
if (!resp.HasMore) break;
resp = await DeviantArtFs.Gallery.Folders.ExecuteAsync(_token, new DeviantArtFs.Gallery.FoldersRequest {
Offset = resp.NextOffset.Value
});
}
this.Enabled = true;
} catch (Exception ex) {
MessageBox.Show(this.ParentForm, ex.Message, $"{this.GetType().Name}: {ex.GetType().Name}");
this.Close();
}
}
}
}
| using DeviantArtFs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CrosspostSharp3 {
public partial class DeviantArtFolderSelectionForm : Form {
public IEnumerable<DeviantArtFs.Gallery.Folder> InitialFolders { get; set; }
private readonly IDeviantArtAccessToken _token;
private List<DeviantArtFs.Gallery.Folder> _selectedFolders;
public IEnumerable<DeviantArtFs.Gallery.Folder> SelectedFolders => _selectedFolders;
public DeviantArtFolderSelectionForm(IDeviantArtAccessToken token) {
InitializeComponent();
_token = token;
_selectedFolders = new List<DeviantArtFs.Gallery.Folder>();
}
private async void DeviantArtFolderSelectionForm_Load(object sender, EventArgs e) {
try {
this.Enabled = false;
var resp = await DeviantArtFs.Gallery.Folders.ExecuteAsync(_token, new DeviantArtFs.Gallery.FoldersRequest { });
int skip = 0;
while (resp.Results.Any()) {
foreach (var f in resp.Results) {
var chk = new CheckBox {
AutoSize = true,
Text = f.Name,
Checked = InitialFolders?.Any(f2 => f.Folderid == f2.Folderid) == true
};
chk.CheckedChanged += (o, ea) => {
if (chk.Checked) {
_selectedFolders.Add(f);
} else {
_selectedFolders.Remove(f);
}
};
flowLayoutPanel1.Controls.Add(chk);
}
skip += resp.Results.Count();
resp = await DeviantArtFs.Gallery.Folders.ExecuteAsync(_token, new DeviantArtFs.Gallery.FoldersRequest {
Offset = skip
});
}
this.Enabled = true;
} catch (Exception ex) {
MessageBox.Show(this.ParentForm, ex.Message, $"{this.GetType().Name}: {ex.GetType().Name}");
this.Close();
}
}
}
}
| mit | C# |
c64c21ef02a0a28c513026642c3698418b625b30 | Update Merchant.cs | hugobritobh/Cielo3.0 | Cielo/Merchant.cs | Cielo/Merchant.cs | using System;
namespace Cielo
{
public class Merchant
{
/// <summary>
/// FIX: UTILIZAR A SUA CHAVE
/// </summary>
public static readonly Merchant SANDBOX = new Merchant(Guid.Parse("d0274285-581c-4f35-a495-3314590b6642"), "UPVHCCVVUJRLXNYGJYKMVHTEATEPTPEPQOTRBDES");
public Merchant(Guid id, string key)
{
this.Id = id;
this.Key = key;
}
public Guid Id { get; }
public string Key { get; }
}
}
| using System;
namespace Cielo
{
public class Merchant
{
/// <summary>
/// FIX: UTILIZAR A SUA CHAVE
/// </summary>
public static readonly Merchant SANDBOX = new Merchant(Guid.Parse("00000000-0000-0000-0000-000000000000"), "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
public Merchant(Guid id, string key)
{
this.Id = id;
this.Key = key;
}
public Guid Id { get; }
public string Key { get; }
}
}
| mit | C# |
7d76fcf2b64766c14dce7c54c6af03ab0cdb4b37 | Fix hit object placement not receiving input when outside playfield | peppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu-new | osu.Game.Rulesets.Catch/Edit/Blueprints/CatchPlacementBlueprint.cs | osu.Game.Rulesets.Catch/Edit/Blueprints/CatchPlacementBlueprint.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint
where THitObject : CatchHitObject, new()
{
protected new THitObject HitObject => (THitObject)base.HitObject;
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
public CatchPlacementBlueprint()
: base(new THitObject())
{
}
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => 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 osu.Framework.Allocation;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
namespace osu.Game.Rulesets.Catch.Edit.Blueprints
{
public class CatchPlacementBlueprint<THitObject> : PlacementBlueprint
where THitObject : CatchHitObject, new()
{
protected new THitObject HitObject => (THitObject)base.HitObject;
protected ScrollingHitObjectContainer HitObjectContainer => (ScrollingHitObjectContainer)playfield.HitObjectContainer;
[Resolved]
private Playfield playfield { get; set; }
public CatchPlacementBlueprint()
: base(new THitObject())
{
}
}
}
| mit | C# |
9c5fddd79b6c8613d8190e51b270b235d8ec26c1 | Add log to JobFactory | mattgwagner/Task-Processor | TaskProcessor/Utilities/JobFactory.cs | TaskProcessor/Utilities/JobFactory.cs | using Common.Logging;
using Quartz;
using Quartz.Spi;
using System;
namespace TaskProcessor.Utilities
{
public class JobFactory : IJobFactory
{
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
// Configure your IoC container to return a job instance based on jobType
var jobDetail = bundle.JobDetail;
Type jobType = jobDetail.JobType;
Log.TraceFormat("Getting instance of job type {0}", jobType);
throw new NotImplementedException();
}
public void ReturnJob(IJob job)
{
// Not needed.
}
}
} | using Quartz;
using Quartz.Spi;
using System;
namespace TaskProcessor.Utilities
{
public class JobFactory : IJobFactory
{
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
// Configure your IoC container to return a job instance based on jobType
var jobDetail = bundle.JobDetail;
Type jobType = jobDetail.JobType;
throw new NotImplementedException();
}
public void ReturnJob(IJob job)
{
// Not needed.
}
}
} | mit | C# |
310afdaaf4f67f2ede3ee490fd608182961cfffb | Fix warning | tom-englert/TomsToolbox | TomsToolbox.Composition.Tests/MetadataReaderTest.cs | TomsToolbox.Composition.Tests/MetadataReaderTest.cs | namespace TomsToolbox.Composition.Tests
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ApprovalTests;
using ApprovalTests.Reporters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
[TestClass]
[UseReporter(typeof(DiffReporter))]
public class MetadataReaderTest
{
private static readonly Regex _versionRegex = new Regex(@"Version=2\.\d+\.\d+\.\d+");
[TestMethod]
public void ReadSampleAppTest()
{
var assembly = typeof(SampleApp.Mef1.App).Assembly;
var result = MetadataReader.Read(assembly);
var data = Serialize(result);
Approvals.VerifyJson(data);
}
[TestMethod]
public void ReadSampleAppMef2Test()
{
var assembly = typeof(SampleApp.App).Assembly;
var result = MetadataReader.Read(assembly);
var data = Serialize(result);
Approvals.VerifyJson(data);
}
private static string Serialize(IList<ExportInfo> result)
{
return _versionRegex.Replace(JsonConvert.SerializeObject(result), "Version=2.0.0.0");
}
}
}
| namespace TomsToolbox.Composition.Tests
{
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using ApprovalTests;
using ApprovalTests.Reporters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
[TestClass]
[UseReporter(typeof(DiffReporter))]
public class MetadataReaderTest
{
private static readonly Regex _versionRegex = new Regex(@"Version=2\.\d+\.\d+\.\d+");
[TestMethod]
public void ReadSampleAppTest()
{
var assembly = typeof(SampleApp.Mef1.App).Assembly;
var result = MetadataReader.Read(assembly);
var data = Serialize(result);
Approvals.VerifyJson(data);
}
[TestMethod]
public void ReadSampleAppMef2Test()
{
var assembly = typeof(SampleApp.App).Assembly;
var result = MetadataReader.Read(assembly);
var data = Serialize(result);
Approvals.VerifyJson(data);
}
private static string Serialize(IList<ExportInfo> result)
{
return _versionRegex.Replace(JsonConvert.SerializeObject(result), "Version=2.0.0.0");
}
}
}
| mit | C# |
2b1ba1ca1aa6882606d21f0a27eb8da80e9fae15 | make plugins config files be optional | AntShares/AntShares,shargon/neo | neo/Plugins/Helper.cs | neo/Plugins/Helper.cs | using Microsoft.Extensions.Configuration;
using System.IO;
using System.Reflection;
namespace Neo.Plugins
{
public static class Helper
{
public static IConfigurationSection GetConfiguration(this Assembly assembly)
{
string path = Path.Combine("Plugins", assembly.GetName().Name, "config.json");
return new ConfigurationBuilder().AddJsonFile(path, optional: true).Build().GetSection("PluginConfiguration");
}
}
}
| using Microsoft.Extensions.Configuration;
using System.IO;
using System.Reflection;
namespace Neo.Plugins
{
public static class Helper
{
public static IConfigurationSection GetConfiguration(this Assembly assembly)
{
string path = Path.Combine("Plugins", assembly.GetName().Name, "config.json");
return new ConfigurationBuilder().AddJsonFile(path).Build().GetSection("PluginConfiguration");
}
}
}
| mit | C# |
c4a1dddb94f34800403fc2d79711829c3ea3ddea | Simplify access token implementation. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Authentication/TraktAccessToken.cs | Source/Lib/TraktApiSharp/Authentication/TraktAccessToken.cs | namespace TraktApiSharp.Authentication
{
using Enums;
using Newtonsoft.Json;
using System;
public class TraktAccessToken
{
public TraktAccessToken()
{
Created = DateTime.UtcNow;
}
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty(PropertyName = "scope")]
[JsonConverter(typeof(TraktAccessScopeConverter))]
public TraktAccessScope AccessScope { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresInSeconds { get; set; }
[JsonProperty(PropertyName = "token_type")]
[JsonConverter(typeof(TraktAccessTokenTypeConverter))]
public TraktAccessTokenType TokenType { get; set; }
[JsonIgnore]
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && DateTime.UtcNow.AddSeconds(ExpiresInSeconds) > DateTime.UtcNow;
[JsonIgnore]
public DateTime Created { get; private set; }
}
}
| namespace TraktApiSharp.Authentication
{
using Enums;
using Newtonsoft.Json;
using System;
public class TraktAccessToken
{
public TraktAccessToken()
{
Created = DateTime.UtcNow;
}
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty(PropertyName = "scope")]
[JsonConverter(typeof(TraktAccessScopeConverter))]
public TraktAccessScope AccessScope { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresInSeconds { get; set; }
private long? _createdAt;
[JsonIgnore]
public long? CreatedAt
{
get { return _createdAt; }
set
{
_createdAt = value;
Created = DateTime.FromFileTimeUtc(value.GetValueOrDefault());
}
}
[JsonProperty(PropertyName = "token_type")]
[JsonConverter(typeof(TraktAccessTokenTypeConverter))]
public TraktAccessTokenType TokenType { get; set; }
[JsonIgnore]
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && DateTime.UtcNow.AddSeconds(ExpiresInSeconds) >= DateTime.UtcNow;
[JsonIgnore]
public DateTime Created { get; private set; }
}
}
| mit | C# |
989fff843974f06c722461a904c4c417f7bd1b98 | fix konec | joeazbest/CompetitionSimulation | WPF/MainWindow.xaml.cs | WPF/MainWindow.xaml.cs | namespace CompetitionSimulationWPF
{
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using Microsoft.Research.DynamicDataDisplay.PointMarkers;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
for (var teamCount = 18; teamCount <= 36; teamCount = teamCount + 6)
{
TeamCount.Items.Add(teamCount);
}
for (var round = 6; round <= 18; round = round + 6)
{
RoundCount.Items.Add(round);
}
//plotter.AddLineGraph(ds, Colors.Green, 2, "Volts"); // to use this method you need "using Microsoft.Research.DynamicDataDisplay;"
}
private void GenerateButtonClick(object sender, RoutedEventArgs e)
{
var points1 = new List<Tuple<double, double>>();
var points2 = new List<Tuple<double, double>>();
var points3 = new List<Tuple<double, double>>();
for (int i = 0; i < 1000; i++)
{
points1.Add(new Tuple<double, double>(i * Math.PI / 50, Math.Cos(i * Math.PI / 50)));
points2.Add(new Tuple<double, double>(i * Math.PI / 50, Math.Cos(i * Math.PI / 50 + 0.01)));
}
var ds1 = new EnumerableDataSource<Tuple<double, double>>(points1);
ds1.SetXMapping(x => x.Item1);
ds1.SetYMapping(y => y.Item2);
var ds2 = new EnumerableDataSource<Tuple<double, double>>(points2);
ds2.SetXMapping(x => x.Item1);
ds2.SetYMapping(y => y.Item2);
plotter.AddLineGraph(ds1, null, new CirclePointMarker { Size = 5, Fill = Brushes.Red }, null);
plotter.AddLineGraph(ds2, null, new CirclePointMarker { Size = 5, Fill = Brushes.Green }, null);
}
}
} | namespace CompetitionSimulationWPF
{
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using Microsoft.Research.DynamicDataDisplay.PointMarkers;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
for (var teamCount = 18; teamCount <= 36; teamCount = teamCount + 6)
{
TeamCount.Items.Add(teamCount);
}
for (var round = 6; round <= 18; round = round + 6)
{
RoundCount.Items.Add(round);
}
var points1 = new List<Tuple<double, double>>();
var points2 = new List<Tuple<double, double>>();
for (int i = 0; i < 1000; i++)
{
points1.Add(new Tuple<double, double>(i * Math.PI / 50, Math.Cos(i * Math.PI / 50)));
points2.Add(new Tuple<double, double>(i * Math.PI / 50, Math.Cos(i * Math.PI / 50 + 0.01)));
}
var ds1 = new EnumerableDataSource<Tuple<double, double>>(points1);
ds1.SetXMapping(x => x.Item1);
ds1.SetYMapping(y => y.Item2);
var ds2 = new EnumerableDataSource<Tuple<double, double>>(points2);
ds2.SetXMapping(x => x.Item1);
ds2.SetYMapping(y => y.Item2);
plotter.AddLineGraph(ds1, null, new CirclePointMarker { Size = 5, Fill = Brushes.Red }, null);
plotter.AddLineGraph(ds2, null, new CirclePointMarker { Size = 5, Fill = Brushes.Green }, null);
//plotter.AddLineGraph(ds, Colors.Green, 2, "Volts"); // to use this method you need "using Microsoft.Research.DynamicDataDisplay;"
}
private void GenerateButtonClick(object sender, RoutedEventArgs e)
{
}
}
} | mit | C# |
52dd95ffbb872df704a4f30084795018147342af | add summary comment. | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | src/DotNetCore.CAP/MessageContext.cs | src/DotNetCore.CAP/MessageContext.cs | namespace DotNetCore.CAP
{
/// <summary>
/// Message context
/// </summary>
public class MessageContext
{
/// <summary>
/// Gets or sets the message group.
/// </summary>
public string Group { get; set; }
/// <summary>
/// Message name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Message content
/// </summary>
public string Content { get; set; }
public override string ToString()
{
return $"Group:{Group}, Name:{Name}, Content:{Content}";
}
}
} | namespace DotNetCore.CAP
{
public class MessageContext
{
public string Group { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public override string ToString()
{
return $"Group:{Group}, Name:{Name}, Content:{Content}";
}
}
} | mit | C# |
9f4a0b448ae6631911df2c66d35b5023b483a959 | mark as background thread | emitter-io/csharp | Emitter/Net/Fx.cs | Emitter/Net/Fx.cs | /*
Copyright (c) 2016 Roman Atachiants
Copyright (c) 2013, 2014 Paolo Patierno
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License: http://www.eclipse.org/legal/epl-v10.html
The Eclipse Distribution License: http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Paolo Patierno - initial API and implementation and/or initial documentation
Roman Atachiants - integrating with emitter.io
*/
using System.Threading;
namespace Emitter
{
/// <summary>
/// Support methods fos specific framework
/// </summary>
public class Fx
{
public static void StartThread(ThreadStart threadStart)
{
var thread = new Thread(threadStart);
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || MF_FRAMEWORK_VERSION_V4_4)
thread.IsBackground = true;
#endif
thread.Start();
}
public static void SleepThread(int millisecondsTimeout)
{
Thread.Sleep(millisecondsTimeout);
}
}
}
| /*
Copyright (c) 2016 Roman Atachiants
Copyright (c) 2013, 2014 Paolo Patierno
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License: http://www.eclipse.org/legal/epl-v10.html
The Eclipse Distribution License: http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Paolo Patierno - initial API and implementation and/or initial documentation
Roman Atachiants - integrating with emitter.io
*/
using System.Threading;
namespace Emitter
{
/// <summary>
/// Support methods fos specific framework
/// </summary>
public class Fx
{
public static void StartThread(ThreadStart threadStart)
{
new Thread(threadStart).Start();
}
public static void SleepThread(int millisecondsTimeout)
{
Thread.Sleep(millisecondsTimeout);
}
}
}
| epl-1.0 | C# |
8f375dc9eed097d9921deb60d03d829cba7a16ab | Add methods intto User Api | skacofonix/WhatTheMovie,skacofonix/WhatTheMovie,skacofonix/WhatTheMovie | WTM.Api/Controllers/UserController.cs | WTM.Api/Controllers/UserController.cs | using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WTM.Core.Services;
using WTM.Crawler;
using WTM.Crawler.Services;
using WTM.Domain;
namespace WTM.Api.Controllers
{
public class UserController : ApiController
{
private readonly IUserService userService;
public UserController()
{
var webClient = new WebClientWTM();
var htmlParser = new HtmlParser();
userService = new UserService(webClient, htmlParser);
}
public UserController(IUserService userService)
{
this.userService = userService;
}
// GET api/User/Login?username={username}&password={password}
[Route("api/User/Login")]
[HttpGet]
public User Login([FromUri]string username, [FromUri]string password)
{
return userService.Login(username, password);
}
[Route("api/User/{username}")]
[HttpGet]
public User Get(string username)
{
return userService.GetByUsername(username);
}
//[Route("api/User/Search")]
[HttpGet]
public List<UserSummary> Search(string search, [FromUri]int? page = null)
{
return userService.Search(search, page).ToList();
}
}
} | using System.Web.Http;
using WTM.Core.Services;
using WTM.Crawler;
using WTM.Crawler.Services;
using WTM.Domain;
namespace WTM.Api.Controllers
{
public class UserController : ApiController
{
private readonly IUserService userService;
public UserController()
{
var webClient = new WebClientWTM();
var htmlParser = new HtmlParser();
userService = new UserService(webClient, htmlParser);
}
public UserController(IUserService userService)
{
this.userService = userService;
}
// GET api/User/Login?username={username}&password={password}
[Route("api/User/Login")]
[HttpGet]
public User Login([FromUri]string username, [FromUri]string password)
{
return userService.Login(username, password);
}
}
} | mit | C# |
f38262f775d35ff1bc9eae9ecedb84463ce8705d | Remove unused imports. | sshnet/SSH.NET,miniter/SSH.NET,Bloomcredit/SSH.NET | src/Renci.SshNet/Session.NET40.cs | src/Renci.SshNet/Session.NET40.cs | using Renci.SshNet.Messages;
namespace Renci.SshNet
{
/// <summary>
/// Provides functionality to connect and interact with SSH server.
/// </summary>
public partial class Session
{
partial void HandleMessageCore(Message message)
{
HandleMessage((dynamic)message);
}
}
}
| using System.Threading.Tasks;
using System.Linq;
using Renci.SshNet.Messages;
namespace Renci.SshNet
{
/// <summary>
/// Provides functionality to connect and interact with SSH server.
/// </summary>
public partial class Session
{
partial void HandleMessageCore(Message message)
{
HandleMessage((dynamic)message);
}
}
}
| mit | C# |
b04b78df1c70ea784a1fc5d7edfe4b0354adc117 | return to normal error page and remove appInsights | jyarbro/forum,jyarbro/forum,jyarbro/forum | Forum3/Startup.cs | Forum3/Startup.cs | using Forum3.Filters;
using Forum3.Contexts;
using Forum3.Controllers;
using Forum3.Extensions;
using Forum3.Models.DataModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Forum3 {
public class Startup {
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
// services.AddApplicationInsightsTelemetry(Configuration);
// Loads from the environment
var dbConnectionString = Configuration["DefaultConnection"];
// Or use the one defined in appsettings.json
if (string.IsNullOrEmpty(dbConnectionString))
dbConnectionString = Configuration.GetConnectionString("DefaultConnection");
// TODO Look into AddDbContextPool limitations
services.AddDbContextPool<ApplicationDbContext>(options =>
options.UseSqlServer(dbConnectionString)
);
services.AddIdentity<ApplicationUser, ApplicationRole>(options => {
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 3;
options.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options => options.LoginPath = $"/{nameof(Account)}/{nameof(Account.Login)}");
services.Configure<MvcOptions>(options => {
//options.Filters.Add<RequireRemoteHttpsAttribute>();
options.Filters.Add<UserContextActionFilter>();
});
services.AddForum(Configuration);
services.AddDistributedMemoryCache();
services.AddSession();
services.AddMvc(config => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
app.UseExceptionHandler("/Boards/Error");
app.UseStaticFiles();
app.UseAuthentication();
app.UseSession();
app.UseForum();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Boards}/{action=Index}/{id?}/{pageId?}/{target?}");
});
}
}
} | using Forum3.Filters;
using Forum3.Contexts;
using Forum3.Controllers;
using Forum3.Extensions;
using Forum3.Models.DataModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Forum3 {
public class Startup {
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddApplicationInsightsTelemetry(Configuration);
// Loads from the environment
var dbConnectionString = Configuration["DefaultConnection"];
// Or use the one defined in appsettings.json
if (string.IsNullOrEmpty(dbConnectionString))
dbConnectionString = Configuration.GetConnectionString("DefaultConnection");
// TODO Look into AddDbContextPool limitations
services.AddDbContextPool<ApplicationDbContext>(options =>
options.UseSqlServer(dbConnectionString)
);
services.AddIdentity<ApplicationUser, ApplicationRole>(options => {
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 3;
options.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options => options.LoginPath = $"/{nameof(Account)}/{nameof(Account.Login)}");
services.Configure<MvcOptions>(options => {
//options.Filters.Add<RequireRemoteHttpsAttribute>();
options.Filters.Add<UserContextActionFilter>();
});
services.AddForum(Configuration);
services.AddDistributedMemoryCache();
services.AddSession();
services.AddMvc(config => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
// Keep for future reference on rewriting.
//app.UseRewriter(new RewriteOptions().AddRedirect("forum(.*)", "Boards/Index"));
if (env.IsDevelopment()) {
//app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else {
// Temporarily make everyone see this page until bugs are worked out.
app.UseDeveloperExceptionPage();
//app.UseExceptionHandler("/Boards/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseSession();
app.UseForum();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Boards}/{action=Index}/{id?}/{pageId?}/{target?}");
});
}
}
} | unlicense | C# |
3b86c63631418a1e9b91a6f4ee2113f6c50ccc91 | Fix up formatting in RuntimePolicy documentation | rho24/Glimpse,gabrielweyer/Glimpse,SusanaL/Glimpse,Glimpse/Glimpse,flcdrg/Glimpse,elkingtonmcb/Glimpse,flcdrg/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,codevlabs/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,SusanaL/Glimpse,codevlabs/Glimpse,dudzon/Glimpse,Glimpse/Glimpse,sorenhl/Glimpse,SusanaL/Glimpse,dudzon/Glimpse,paynecrl97/Glimpse,paynecrl97/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,paynecrl97/Glimpse,codevlabs/Glimpse,flcdrg/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,sorenhl/Glimpse,gabrielweyer/Glimpse | source/Glimpse.Core/RuntimePolicy.cs | source/Glimpse.Core/RuntimePolicy.cs | using System;
namespace Glimpse.Core
{
/// <summary>
/// Enum RuntimePolicy used to describe what activity level Glimpse
/// is allowed to operate in.
/// </summary>
/// <remarks>
/// This is used at a request by request level.
/// </remarks>
[Flags]
public enum RuntimePolicy
{
/// <summary>
/// The off
/// </summary>
/// <remarks>
/// Will not modify any part of the request
/// </remarks>
Off = 1,
/// <summary>
/// The execute resource only
/// </summary>
/// <remarks>
/// Will only resource endpoints to execute
/// </remarks>
ExecuteResourceOnly = 2 | Off,
/// <summary>
/// The persist results
/// </summary>
/// <remarks>
/// Will allow results to be persisted to the data store
/// </remarks>
PersistResults = 4,
/// <summary>
/// The modify response headers
/// </summary>
/// <remarks>
/// Allows the modification of response headers
/// </remarks>
ModifyResponseHeaders = 8 | PersistResults,
/// <summary>
/// The modify response body
/// </summary>
/// <remarks>
/// Allows the modification of response body
/// </remarks>
ModifyResponseBody = 16 | ModifyResponseHeaders,
/// <summary>
/// The display glimpse client
/// </summary>
/// <remarks>
/// Whether the client should show in the client browser
/// </remarks>
DisplayGlimpseClient = 32 | ModifyResponseBody,
/// <summary>
/// The on
/// </summary>
/// <remarks>
/// Everything is turned on
/// </remarks>
On = DisplayGlimpseClient
}
} | using System;
namespace Glimpse.Core
{
/// <summary>
/// Enum RuntimePolicy used to describe what activity level Glimpse
/// is allowed to operate in.
/// </summary>
/// <remarks>
/// This is used at a request by request level.
/// </remarks>
[Flags]
public enum RuntimePolicy
{
/// <summary>
/// The off
/// </summary>
/// <remarks>
/// Will not modify any part of the request
/// </remarks>
Off = 1,
/// <summary>
/// The execute resource only
/// </summary>
/// <remarks>
/// Will only resource endpoints to execute
/// </remarks>
ExecuteResourceOnly = 2 | Off,
/// <summary>
/// The persist results
/// </summary>
/// <remarks>
/// Will allow results to be persisted to the data store
/// </remarks>
PersistResults = 4,
/// <summary>
/// The modify response headers
/// </summary>
/// <remarks>
/// Allows the modification of response headers
/// </remarks>
ModifyResponseHeaders = 8 | PersistResults,
/// <summary>
/// The modify response body
/// </summary>
/// <remarks>
/// Allows the modification of response body
/// </remarks>
ModifyResponseBody = 16 | ModifyResponseHeaders,
/// <summary>
/// The display glimpse client
/// </summary>
/// <remarks>
/// Whether the client should show in the client browser
/// </remarks>
DisplayGlimpseClient = 32 | ModifyResponseBody,
/// <summary>
/// The on
/// </summary>
/// <remarks>
/// Everything is turned on
/// </remarks>
On = DisplayGlimpseClient
}
} | apache-2.0 | C# |
04e0e1b844bafda7700bc618a110838267b7a8b1 | update version | takuya-takeuchi/RedArmory | source/RedArmory/AssemblyProperty.cs | source/RedArmory/AssemblyProperty.cs | namespace Ouranos.RedArmory
{
internal static class AssemblyProperty
{
/// <summary>
/// アセンブリ マニフェストに含める、製品名に関するカスタム属性を定義します。
/// </summary>
public const string Product = "Red Armory";
/// <summary>
/// RedArmory.exe の説明を指定します。
/// </summary>
public const string Title = "Red Armory";
/// <summary>
/// アセンブリ マニフェストに含める、会社名に関するカスタム属性を定義します。
/// </summary>
public const string Company = "";
/// <summary>
/// アセンブリ マニフェストに含める、著作権に関するカスタム属性を表します。
/// </summary>
public const string Copyright = "Copyright © Takuya Takeuchi All Rights Reserved.";
/// <summary>
/// アセンブリ マニフェストに含める、ファイル バージョンを定義します。
/// </summary>
public const string FileVersion = "1.9.1.0";
/// <summary>
/// アセンブリ マニフェストに含める、アセンブリ バージョンを定義します。
/// </summary>
public const string Version = "1.9.1.0";
}
}
| namespace Ouranos.RedArmory
{
internal static class AssemblyProperty
{
/// <summary>
/// アセンブリ マニフェストに含める、製品名に関するカスタム属性を定義します。
/// </summary>
public const string Product = "Red Armory";
/// <summary>
/// RedArmory.exe の説明を指定します。
/// </summary>
public const string Title = "Red Armory";
/// <summary>
/// アセンブリ マニフェストに含める、会社名に関するカスタム属性を定義します。
/// </summary>
public const string Company = "";
/// <summary>
/// アセンブリ マニフェストに含める、著作権に関するカスタム属性を表します。
/// </summary>
public const string Copyright = "Copyright © Takuya Takeuchi All Rights Reserved.";
/// <summary>
/// アセンブリ マニフェストに含める、ファイル バージョンを定義します。
/// </summary>
public const string FileVersion = "1.9.0.1";
/// <summary>
/// アセンブリ マニフェストに含める、アセンブリ バージョンを定義します。
/// </summary>
public const string Version = "1.9.0.1";
}
}
| mit | C# |
294564d769e3702c8f49cbbd461b967f5f947217 | add missing namespace | DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/Core/Attributes/PreserveAttribute.cs | Assets/MRTK/Core/Attributes/PreserveAttribute.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
namespace Microsoft.MixedReality.Toolkit
{
/// <summary>
/// Custom preserve attribute that is inheritable.
/// </summary>
[AttributeUsage(
AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Property |
AttributeTargets.Field |
AttributeTargets.Event |
AttributeTargets.Interface |
AttributeTargets.Delegate,
Inherited = true)]
public class MixedRealityToolkitPreserveAttribute : UnityEngine.Scripting.PreserveAttribute
{
// No methods on PreserveAttribue for overriding.
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
/// <summary>
/// Custom preserve attribute that is inheritable.
/// </summary>
[AttributeUsage(
AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Property |
AttributeTargets.Field |
AttributeTargets.Event |
AttributeTargets.Interface |
AttributeTargets.Delegate,
Inherited = true)]
public class MixedRealityToolkitPreserveAttribute : UnityEngine.Scripting.PreserveAttribute
{
// No methods on PreserveAttribue for overriding.
}
| mit | C# |
67b9414ccf0cd268ea063c4ebf55c4f3c7db6e31 | Fix IModelBinder docs | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Mvc.Abstractions/ModelBinding/IModelBinder.cs | src/Microsoft.AspNet.Mvc.Abstractions/ModelBinding/IModelBinder.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
/// <summary>
/// Defines an interface for model binders.
/// </summary>
public interface IModelBinder
{
/// <summary>
/// Attempts to bind a model.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
/// <returns>
/// <para>
/// A <see cref="Task"/> which on completion returns a <see cref="ModelBindingResult"/> which
/// represents the result of the model binding process.
/// </para>
/// <para>
/// If model binding was successful, the <see cref="ModelBindingResult"/> should be a value created
/// with <see cref="ModelBindingResult.Success"/>. If model binding failed, the
/// <see cref="ModelBindingResult"/> should be a value created with <see cref="ModelBindingResult.Failed"/>.
/// If there was no data, or this model binder cannot handle the operation, the
/// <see cref="ModelBindingResult"/> should be <see cref="ModelBindingResult.NoResult"/>.
/// </para>
/// </returns>
Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
/// <summary>
/// Interface for model binding.
/// </summary>
public interface IModelBinder
{
/// <summary>
/// Async function to bind to a particular model.
/// </summary>
/// <param name="bindingContext">The binding context which has the object to be bound.</param>
/// <returns>A Task which on completion returns a <see cref="ModelBindingResult"/> which represents the result
/// of the model binding process.
/// </returns>
/// <remarks>
/// A <c>null</c> return value means that this model binder was not able to handle the request.
/// Returning <c>null</c> ensures that subsequent model binders are run. If a non <c>null</c> value indicates
/// that the model binder was able to handle the request.
/// </remarks>
Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext);
}
}
| apache-2.0 | C# |
c1a02d9d8648df5ae49e250ee943be937cb2f23e | 更新.NET 4.5项目版本号 | JeffreySu/Senparc.WebSocket | src/Senparc.WebSocket/Senparc.WebSocket/Properties/AssemblyInfo.cs | src/Senparc.WebSocket/Senparc.WebSocket/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
//[assembly: AssemblyTitle("Senparc.WebSocket")]
//[assembly: AssemblyDescription("")]
//[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("")]
//[assembly: AssemblyProduct("Senparc.WebSocket")]
//[assembly: AssemblyCopyright("Copyright © 2017")]
//[assembly: AssemblyTrademark("")]
//[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b745f5f5-9120-4d56-a86d-ed34eadb703c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.3.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
//[assembly: AssemblyTitle("Senparc.WebSocket")]
//[assembly: AssemblyDescription("")]
//[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("")]
//[assembly: AssemblyProduct("Senparc.WebSocket")]
//[assembly: AssemblyCopyright("Copyright © 2017")]
//[assembly: AssemblyTrademark("")]
//[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b745f5f5-9120-4d56-a86d-ed34eadb703c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.4.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
201b1bec89b9316cbb9c34268c4c16c7a17daede | Fix time management bugs in RadiationPulseSystem (#4743) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Radiation/RadiationPulseSystem.cs | Content.Server/Radiation/RadiationPulseSystem.cs | using System.Linq;
using Content.Shared.Radiation;
using Content.Shared.Sound;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
namespace Content.Server.Radiation
{
[UsedImplicitly]
public sealed class RadiationPulseSystem : EntitySystem
{
[Dependency] private readonly IEntityLookup _lookup = default!;
private const float RadiationCooldown = 0.5f;
private float _accumulator;
public override void Update(float frameTime)
{
base.Update(frameTime);
_accumulator += frameTime;
while (_accumulator > RadiationCooldown)
{
_accumulator -= RadiationCooldown;
// All code here runs effectively every RadiationCooldown seconds, so use that as the "frame time".
foreach (var comp in EntityManager.EntityQuery<RadiationPulseComponent>(true))
{
comp.Update(RadiationCooldown);
var ent = comp.Owner;
if (ent.Deleted) continue;
foreach (var entity in _lookup.GetEntitiesInRange(ent.Transform.Coordinates, comp.Range))
{
// For now at least still need this because it uses a list internally then returns and this may be deleted before we get to it.
if (entity.Deleted) continue;
// Note: Radiation is liable for a refactor (stinky Sloth coding a basic version when he did StationEvents)
// so this ToArray doesn't really matter.
foreach (var radiation in entity.GetAllComponents<IRadiationAct>().ToArray())
{
radiation.RadiationAct(RadiationCooldown, comp);
}
}
}
}
}
}
}
| using System.Linq;
using Content.Shared.Radiation;
using Content.Shared.Sound;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
namespace Content.Server.Radiation
{
[UsedImplicitly]
public sealed class RadiationPulseSystem : EntitySystem
{
[Dependency] private readonly IEntityLookup _lookup = default!;
private const float RadiationCooldown = 0.5f;
private float _accumulator;
public override void Update(float frameTime)
{
base.Update(frameTime);
_accumulator += RadiationCooldown;
while (_accumulator > RadiationCooldown)
{
_accumulator -= RadiationCooldown;
foreach (var comp in EntityManager.EntityQuery<RadiationPulseComponent>(true))
{
comp.Update(frameTime);
var ent = comp.Owner;
if (ent.Deleted) continue;
foreach (var entity in _lookup.GetEntitiesInRange(ent.Transform.Coordinates, comp.Range))
{
// For now at least still need this because it uses a list internally then returns and this may be deleted before we get to it.
if (entity.Deleted) continue;
// Note: Radiation is liable for a refactor (stinky Sloth coding a basic version when he did StationEvents)
// so this ToArray doesn't really matter.
foreach (var radiation in entity.GetAllComponents<IRadiationAct>().ToArray())
{
radiation.RadiationAct(RadiationCooldown, comp);
}
}
}
}
}
}
}
| mit | C# |
558b9882a74a1c1b3c74e785effedd4d98ebe075 | Change commandReceiver to accept only pending commands #37685 | takenet/messaginghub-client-csharp | src/Takenet.MessagingHub.Client/Listener/CommandReceivedHandler.cs | src/Takenet.MessagingHub.Client/Listener/CommandReceivedHandler.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client.Sender;
namespace Takenet.MessagingHub.Client.Listener
{
internal class CommandReceivedHandler : EnvelopeReceivedHandler<Command>
{
public CommandReceivedHandler(IMessagingHubSender sender, EnvelopeReceiverManager envelopeManager, CancellationTokenSource cts)
: base(sender, envelopeManager, cts)
{ }
protected override async Task CallReceiversAsync(Command command, CancellationToken cancellationToken)
{
if (command.Status != CommandStatus.Pending) return;
try
{
await base.CallReceiversAsync(command, cancellationToken);
}
catch (Exception ex)
{
await Sender.SendCommandResponseAsync(new Command
{
Id = command.Id,
To = command.From,
Method = command.Method,
Status = CommandStatus.Failure,
Reason = ex.ToReason(),
}, cancellationToken);
}
}
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client.Sender;
namespace Takenet.MessagingHub.Client.Listener
{
internal class CommandReceivedHandler : EnvelopeReceivedHandler<Command>
{
public CommandReceivedHandler(IMessagingHubSender sender, EnvelopeReceiverManager envelopeManager, CancellationTokenSource cts)
: base(sender, envelopeManager, cts)
{ }
protected override async Task CallReceiversAsync(Command command, CancellationToken cancellationToken)
{
try
{
await base.CallReceiversAsync(command, cancellationToken);
}
catch (Exception ex)
{
await Sender.SendCommandResponseAsync(new Command
{
Id = command.Id,
To = command.From,
Method = command.Method,
Status = CommandStatus.Failure,
Reason = ex.ToReason(),
}, cancellationToken);
}
}
}
} | apache-2.0 | C# |
eb515d4ed7723b02ca4349cab0346e8d18cdcb96 | Update Summary w/ large image card documentation | peterblazejewicz/TwitterCardsTagHelpers,peterblazejewicz/TwitterCardsTagHelpers | src/TwitterCardTagHelpers.Web/Views/Cards/SummaryLargeImage.cshtml | src/TwitterCardTagHelpers.Web/Views/Cards/SummaryLargeImage.cshtml | @*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
// ViewBag.Title = "SummaryLargeImage Page";
}
<section>
<div class="page-header">
<h1>Summary Card with Large Image <small>tag helper</small></h1>
</div>
<blockquote cite="https://dev.twitter.com/cards/types/summary-large-image">
<p>The Summary Card with Large Image features a large, full-width prominent image alongside a tweet. It is designed to give the reader a rich photo experience, and clicking on the image brings the user to your website.</p>
</blockquote>
<a href="https://dev.twitter.com/cards/types/summary-large-image">https://dev.twitter.com/cards/types/summary-large-image</a>
<pre>
<code class="html"><twitter-summary-large-image site="@@nytimes"
creator="@@SarahMaslinNir"
title="Parade of Fans for Houston’s Funeral"
description="NEWARK - The guest list and parade of limousines with celebrities emerging from them seemed more suited to a red carpet event in Hollywood or New York than than a gritty stretch of Sussex Avenue near the former site of the James M. Baxter Terrace public housing project here."
image="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg" /></code>
</pre>
<p>
This will produce:
</p>
<pre>
<code class="html"><meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@@nytimes">
<meta name="twitter:creator" content="@@SarahMaslinNir">
<meta name="twitter:title" content="Parade of Fans for Houston’s Funeral">
<meta name="twitter:description" content="NEWARK - The guest list and parade of limousines with celebrities emerging from them seemed more suited to a red carpet event in Hollywood or New York than than a gritty stretch of Sussex Avenue near the former site of the James M. Baxter Terrace public housing project here.">
<meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg"></code>
</pre>
<twitter-summary-large-image site="@@nytimes"
creator="@@SarahMaslinNir"
title="Parade of Fans for Houston’s Funeral"
description="NEWARK - The guest list and parade of limousines with celebrities emerging from them seemed more suited to a red carpet event in Hollywood or New York than than a gritty stretch of Sussex Avenue near the former site of the James M. Baxter Terrace public housing project here."
image="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg" />
</section>
| @*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
// ViewBag.Title = "SummaryLargeImage Page";
}
| unlicense | C# |
2b8ae3e92fe613a2d52a07775fb2486276ae546c | Make handler shim abstract. | jasonmalinowski/roslyn,gafter/roslyn,KirillOsenkov/roslyn,brettfo/roslyn,agocke/roslyn,aelij/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,heejaechang/roslyn,davkean/roslyn,sharwell/roslyn,bartdesmet/roslyn,tannergooding/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,reaction1989/roslyn,wvdd007/roslyn,genlu/roslyn,tannergooding/roslyn,tmat/roslyn,mavasani/roslyn,jmarolf/roslyn,davkean/roslyn,abock/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,diryboy/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,wvdd007/roslyn,reaction1989/roslyn,reaction1989/roslyn,eriawan/roslyn,agocke/roslyn,jmarolf/roslyn,dotnet/roslyn,gafter/roslyn,eriawan/roslyn,bartdesmet/roslyn,eriawan/roslyn,AlekseyTs/roslyn,genlu/roslyn,aelij/roslyn,dotnet/roslyn,aelij/roslyn,physhi/roslyn,diryboy/roslyn,physhi/roslyn,stephentoub/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,abock/roslyn,stephentoub/roslyn,brettfo/roslyn,agocke/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,tmat/roslyn,weltkante/roslyn,diryboy/roslyn,weltkante/roslyn,brettfo/roslyn,gafter/roslyn,tannergooding/roslyn,mavasani/roslyn,genlu/roslyn,sharwell/roslyn,AmadeusW/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,abock/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,weltkante/roslyn,davkean/roslyn,mavasani/roslyn,panopticoncentral/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn | src/VisualStudio/LiveShare/Impl/Shims/GoToDefinitionHandlerShim.cs | src/VisualStudio/LiveShare/Impl/Shims/GoToDefinitionHandlerShim.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Shims
{
internal abstract class AbstractGoToDefinitionHandlerShim : AbstractLiveShareHandlerShim<TextDocumentPositionParams, object>
{
public AbstractGoToDefinitionHandlerShim(IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers)
: base(requestHandlers, Methods.TextDocumentDefinitionName)
{
}
}
[ExportLspRequestHandler(LiveShareConstants.CSharpContractName, Methods.TextDocumentDefinitionName)]
internal class CSharpGoToDefinitionHandlerShim : AbstractGoToDefinitionHandlerShim
{
[ImportingConstructor]
public CSharpGoToDefinitionHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers)
: base(requestHandlers)
{
}
}
[ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, Methods.TextDocumentDefinitionName)]
internal class VisualBasicGoToDefinitionHandlerShim : AbstractGoToDefinitionHandlerShim
{
[ImportingConstructor]
public VisualBasicGoToDefinitionHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers)
: base(requestHandlers)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Shims
{
internal class GoToDefinitionHandlerShim : AbstractLiveShareHandlerShim<TextDocumentPositionParams, object>
{
public GoToDefinitionHandlerShim(IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers)
: base(requestHandlers, Methods.TextDocumentDefinitionName)
{
}
}
[ExportLspRequestHandler(LiveShareConstants.CSharpContractName, Methods.TextDocumentDefinitionName)]
internal class CSharpGoToDefinitionHandlerShim : GoToDefinitionHandlerShim
{
[ImportingConstructor]
public CSharpGoToDefinitionHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers)
: base(requestHandlers)
{
}
}
[ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, Methods.TextDocumentDefinitionName)]
internal class VisualBasicGoToDefinitionHandlerShim : GoToDefinitionHandlerShim
{
[ImportingConstructor]
public VisualBasicGoToDefinitionHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers)
: base(requestHandlers)
{
}
}
}
| mit | C# |
9e03cb5f40d5565b392ad7af7614b6714f8d92a4 | fix test case | jefking/King.Service | King.Azure.BackgroundWorker.Tests/TimingTests.cs | King.Azure.BackgroundWorker.Tests/TimingTests.cs | namespace King.Azure.BackgroundWorker.Tests
{
using NUnit.Framework;
using System;
[TestFixture]
public class TimingTests
{
[Test]
public void Constructor()
{
new Timing();
}
[Test]
public void IsITiming()
{
Assert.IsNotNull(new Timing() as ITiming);
}
[Test]
public void Attempt()
{
var random = new Random();
var min = random.Next();
var time = new Timing();
var ex = time.Exponential(min, 60, 0);
Assert.AreEqual(min, ex);
}
[Test]
public void AttemptMax()
{
var random = new Random();
var max = random.Next(1, 60);
var time = new Timing();
var ex = time.Exponential(0, max, random.Next(61, 500));
Assert.AreEqual(max, ex);
}
[Test]
public void FirstAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 1);
Assert.AreEqual(2, ex);
}
[Test]
public void SecondAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 2);
Assert.AreEqual(4, ex);
}
[Test]
public void ThirdAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 3);
Assert.AreEqual(8, ex);
}
[Test]
public void FourthAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 4);
Assert.AreEqual(16, ex);
}
}
} | namespace King.Azure.BackgroundWorker.Tests
{
using NUnit.Framework;
using System;
[TestFixture]
public class TimingTests
{
[Test]
public void Constructor()
{
new Timing();
}
[Test]
public void IsITiming()
{
Assert.IsNotNull(new Timing() as ITiming);
}
[Test]
public void Attempt()
{
var random = new Random();
var min = random.Next();
var time = new Timing();
var ex = time.Exponential(min, 60, 0);
Assert.AreEqual(min, ex);
}
[Test]
public void AttemptMax()
{
var random = new Random();
var max = random.Next(1, 60);
var time = new Timing();
var ex = time.Exponential(0, max, random.Next(61));
Assert.AreEqual(max, ex);
}
[Test]
public void FirstAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 1);
Assert.AreEqual(2, ex);
}
[Test]
public void SecondAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 2);
Assert.AreEqual(4, ex);
}
[Test]
public void ThirdAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 3);
Assert.AreEqual(8, ex);
}
[Test]
public void FourthAttempt()
{
var time = new Timing();
var ex = time.Exponential(0, 60, 4);
Assert.AreEqual(16, ex);
}
}
} | mit | C# |
744ab9ef61063453c4f1f81d5c14ef5dc7fb3dc2 | Upgrade version to 1.3.5 | geffzhang/equeue,tangxuehua/equeue,geffzhang/equeue,Aaron-Liu/equeue,tangxuehua/equeue,tangxuehua/equeue,Aaron-Liu/equeue | src/EQueue/Properties/AssemblyInfo.cs | src/EQueue/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.5")]
[assembly: AssemblyFileVersion("1.3.5")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.4")]
[assembly: AssemblyFileVersion("1.3.4")]
| mit | C# |
bd5b2e58f5ed295fae74e57310d5de2aab4e3b8b | remove comment out for dinke MVP award date | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/DougFinke.cs | src/Firehose.Web/Authors/DougFinke.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class DougFinke : IFilterMyBlogPosts, IAmAMicrosoftMVP
{
public string FirstName => "Doug";
public string LastName => "Finke";
public string ShortBioOrTagLine => "Microsoft PowerShell MVP, Author: Windows PowerShell for Developers http://goo.gl/D3gsQ , consultant, speaker, father";
public string StateOrRegion => "New York City, United States";
public string EmailAddress => "finked@hotmail.com";
public string TwitterHandle => "dfinke";
public string GravatarHash => "94c48c63e7e63f5e713f7f7a5cdbcac0";
public Uri WebSite => new Uri("https://dfinke.github.io/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://dfinke.github.io/feed.xml"); }
}
public string GitHubHandle => "dfinke";
public bool Filter(SyndicationItem item)
{
return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any();
}
public GeoPosition Position => new GeoPosition(40.7526970, -73.9749950);
DateTime IAmAMicrosoftMVP.FirstAwarded => new DateTime(2008, 4, 1);
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class DougFinke : IFilterMyBlogPosts, IAmAMicrosoftMVP
{
public string FirstName => "Doug";
public string LastName => "Finke";
public string ShortBioOrTagLine => "Microsoft PowerShell MVP, Author: Windows PowerShell for Developers http://goo.gl/D3gsQ , consultant, speaker, father";
public string StateOrRegion => "New York City, United States";
public string EmailAddress => "finked@hotmail.com";
public string TwitterHandle => "dfinke";
public string GravatarHash => "94c48c63e7e63f5e713f7f7a5cdbcac0";
public Uri WebSite => new Uri("https://dfinke.github.io/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://dfinke.github.io/feed.xml"); }
}
public string GitHubHandle => "dfinke";
public bool Filter(SyndicationItem item)
{
return item.Categories.Where(i => i.Name.Equals("powershell", StringComparison.OrdinalIgnoreCase)).Any();
}
public GeoPosition Position => new GeoPosition(40.7526970, -73.9749950);
//DateTime IAmAMicrosoftMVP.FirstAwarded => new DateTime(2008, 4, 1);
}
} | mit | C# |
0446d2d14e915956ae9e0d27ea2d229f53ed625d | Reduce the number of slice operations performed during an Advance, when those slices were used only for their length. | plioi/parsley | src/Parsley/ReadOnlySpanExtensions.cs | src/Parsley/ReadOnlySpanExtensions.cs | namespace Parsley;
public static class ReadOnlySpanExtensions
{
public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length)
=> length >= input.Length
? input.Slice(0)
: input.Slice(0, length);
public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length)
{
var traversed = length >= input.Length
? input.Length
: length;
input = input.Slice(traversed);
index += traversed;
}
public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test)
{
int i = 0;
while (i < input.Length && test(input[i]))
i++;
return input.Peek(i);
}
}
| namespace Parsley;
public static class ReadOnlySpanExtensions
{
public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length)
=> length >= input.Length
? input.Slice(0)
: input.Slice(0, length);
public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length)
{
var traversed = input.Peek(length);
input = input.Slice(traversed.Length);
index += traversed.Length;
}
public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test)
{
int i = 0;
while (i < input.Length && test(input[i]))
i++;
return input.Peek(i);
}
}
| mit | C# |
560ed0f4b734262b963086a9fe50e052c3c6c4e7 | Fix aiming bug | jkereako/PillBlasta | Assets/Scripts/Player/Player.cs | Assets/Scripts/Player/Player.cs | using UnityEngine;
// Declare the file's dependencies
[RequireComponent(typeof(PlayerController))]
[RequireComponent(typeof(WeaponController))]
public class Player: LiveEntity {
public EntityTrait trait;
public CrossHair crossHair;
PlayerController playerController;
WeaponController weaponController;
Camera mainCamera;
void Awake() {
playerController = GetComponent<PlayerController>();
weaponController = GetComponent<WeaponController>();
mainCamera = Camera.main;
// Set entity traits
GetComponent<Renderer>().material.color = trait.color;
health = trait.health;
}
void Update() {
// The code below allows the player's "eyes" to follow the mouse movement.
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
// Debug.DrawLine(ray.origin, point, Color.red);
// Emulate the playing surface by creating a new, flat plane. This simplifies the code as we
// don't have to depend on the actual in-game plane.
//
// `Vector3.up` Shorthand for writing `Vector3(0, 1, 0)`.
Plane plane = new Plane(Vector3.up, Vector3.up * weaponController.weaponHold.position.y);
float rayLength;
// This function sets enter to the distance along the ray, where it intersects the plane. If the
// ray is parallel or pointing in the opposite direction to the plane then `Raycast()` is false
// and `rayLength` is 0 and negative, respectively.
if (!plane.Raycast(ray, out rayLength)) {
return;
}
const int threshold = 6;
Vector3 point = ray.GetPoint(rayLength);
Vector2 newPoint = new Vector2(point.x, point.z);
Vector2 newPosition = new Vector2(transform.position.x, transform.position.z);
playerController.LookAt(point);
if ((newPoint - newPosition).sqrMagnitude > threshold) {
weaponController.Aim(point);
}
crossHair.transform.position = point;
crossHair.DetectTargets(ray);
if (Input.GetMouseButton(0)) {
weaponController.OnTriggerPull();
}
else if (Input.GetMouseButtonUp(0)) {
weaponController.OnTriggerRelease();
}
Move();
}
void Move() {
// `GetAxisRaw` returns the unmolested input value. We use it here to make the pill stop on a
// dime.
Vector3 movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
Vector3 velocity = movement.normalized * trait.locomotiveSpeed;
playerController.Move(velocity);
}
}
| using UnityEngine;
// Declare the file's dependencies
[RequireComponent(typeof(PlayerController))]
[RequireComponent(typeof(WeaponController))]
public class Player: LiveEntity {
public EntityTrait trait;
public CrossHair crossHair;
PlayerController playerController;
WeaponController weaponController;
Camera mainCamera;
void Awake() {
playerController = GetComponent<PlayerController>();
weaponController = GetComponent<WeaponController>();
mainCamera = Camera.main;
// Set entity traits
GetComponent<Renderer>().material.color = trait.color;
health = trait.health;
}
void Update() {
// `GetAxisRaw` returns the unmolested input value. We use it here to make the pill stop on a dime.
Vector3 movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
Vector3 velocity = movement.normalized * trait.locomotiveSpeed;
playerController.Move(velocity);
// The code below allows the player's "eyes" to follow the mouse movement.
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
// Emulate the playing surface by creating a new, flat plane. This simplifies the code as we
// don't have to depend on the actual in-game plane.
//
// `Vector3.up` Shorthand for writing `Vector3(0, 1, 0)`.
Plane plane = new Plane(Vector3.up, Vector3.up * weaponController.weaponHold.position.y);
float rayLength;
if (plane.Raycast(ray, out rayLength)) {
Vector3 point = ray.GetPoint(rayLength);
// Debug.DrawLine(ray.origin, point, Color.red);
playerController.LookAt(point);
weaponController.Aim(point);
crossHair.transform.position = point;
crossHair.DetectTargets(ray);
}
if (Input.GetMouseButton(0)) {
weaponController.OnTriggerPull();
}
else if (Input.GetMouseButtonUp(0)) {
weaponController.OnTriggerRelease();
}
}
}
| mit | C# |
2ef5aa84350f2ae3b72eddf1cecd2c53921d5372 | Introduce caching of ShouldIgnore request so that the ignorer pipeline is only executed once per request | peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype | src/Glimpse.Agent.Web/Framework/DefaultRequestIgnorerManager.cs | src/Glimpse.Agent.Web/Framework/DefaultRequestIgnorerManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.JsonPatch.Helpers;
namespace Glimpse.Agent.Web
{
public class DefaultRequestIgnorerManager : IRequestIgnorerManager
{
public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
{
RequestIgnorers = requestIgnorerProvider.Instances;
HttpContextAccessor = httpContextAccessor;
}
private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public bool ShouldIgnore()
{
return ShouldIgnore(HttpContextAccessor.HttpContext);
}
public bool ShouldIgnore(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var result = GetCachedResult(context);
if (result == null)
{
if (RequestIgnorers.Any())
{
foreach (var policy in RequestIgnorers)
{
if (policy.ShouldIgnore(context))
{
result = true;
break;
}
}
}
if (!result.HasValue)
{
result = false;
}
SetCachedResult(context, result);
}
return result.Value;
}
private bool? GetCachedResult(HttpContext context)
{
return context.Items["Glimpse.ShouldIgnoreRequest"] as bool?;
}
private void SetCachedResult(HttpContext context, bool? value)
{
context.Items["Glimpse.ShouldIgnoreRequest"] = value;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.Web
{
public class DefaultRequestIgnorerManager : IRequestIgnorerManager
{
public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
{
RequestIgnorers = requestIgnorerProvider.Instances;
HttpContextAccessor = httpContextAccessor;
}
private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
public bool ShouldIgnore()
{
return ShouldIgnore(HttpContextAccessor.HttpContext);
}
public bool ShouldIgnore(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (RequestIgnorers.Any())
{
foreach (var policy in RequestIgnorers)
{
if (policy.ShouldIgnore(context))
{
return true;
}
}
}
return false;
}
}
} | mit | C# |
fdd5438123c1b9a5b02494955f9acec66e5fed5e | remove DeviceTimestamp from SensorValues model | MCeddy/IoT-core | IoT-Core/Models/SensorValues.cs | IoT-Core/Models/SensorValues.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace IoT_Core.Models
{
public class SensorValues
{
public int Id { get; set; }
public DateTime Date { get; set; }
//public int? DeviceTimestamp { get; set; }
[Required]
public float Temperature { get; set; }
[Required]
public float Humidity { get; set; }
[Required]
public int SoilMoisture { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace IoT_Core.Models
{
public class SensorValues
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int? DeviceTimestamp { get; set; }
[Required]
public float Temperature { get; set; }
[Required]
public float Humidity { get; set; }
[Required]
public int SoilMoisture { get; set; }
}
}
| mit | C# |
8dea2b1630714a644070a2fd6351995fbafd5e20 | Update to version | chaowlert/Mapster,eswann/Mapster | src/Fpr/Properties/AssemblyInfo.cs | src/Fpr/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("Fpr")]
[assembly: AssemblyDescription("A fast, fun and stimulating object to object mapper. Kind of like AutoMapper, just simpler and way, way faster.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Fpr")]
[assembly: AssemblyCopyright("Copyright © Swannee 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("df5bd29d-85e6-4621-b3cb-1561e98f9697")]
// 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.7.2.*")]
[assembly: AssemblyFileVersion("1.7.2.*")]
[assembly: InternalsVisibleTo("Fpr.Tests")]
| 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("Fpr")]
[assembly: AssemblyDescription("A fast, fun and stimulating object to object mapper. Kind of like AutoMapper, just simpler and way, way faster.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Fpr")]
[assembly: AssemblyCopyright("Copyright © Swannee 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("df5bd29d-85e6-4621-b3cb-1561e98f9697")]
// 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.7.1.*")]
[assembly: AssemblyFileVersion("1.7.1.*")]
[assembly: InternalsVisibleTo("Fpr.Tests")]
| mit | C# |
106365f2e83cc999e0d83fac7d4eb6f3e0960c0d | Add CodeGenUtilityTests. | FacilityApi/Facility | tests/Facility.Definition.UnitTests/CodeGen/CodeGenUtilityTests.cs | tests/Facility.Definition.UnitTests/CodeGen/CodeGenUtilityTests.cs | using Facility.Definition.CodeGen;
using FluentAssertions;
using NUnit.Framework;
namespace Facility.Definition.UnitTests.CodeGen
{
public sealed class CodeGenUtilityTests
{
[TestCase("xyZzy", "XyZzy")]
[TestCase("XyZzy", "XyZzy")]
[TestCase("1234", "1234")]
public void Capitalize(string before, string after)
{
CodeGenUtility.Capitalize(before).Should().Be(after);
}
[TestCase("xyZzy", "xyZzy")]
[TestCase("XyZzy", "xyZzy")]
[TestCase("1234", "1234")]
public void Uncapitalize(string before, string after)
{
CodeGenUtility.Uncapitalize(before).Should().Be(after);
}
[TestCase("xyZzy", "xyZzy")]
[TestCase("XyZzy", "xyZzy")]
[TestCase("1234", "1234")]
[TestCase("xy_zzy", "xyZzy")]
[TestCase("me2you", "me2You")]
[TestCase("IOStream", "ioStream")]
public void CamelCase(string before, string after)
{
CodeGenUtility.ToCamelCase(before).Should().Be(after);
}
[TestCase("xyZzy", "XyZzy")]
[TestCase("XyZzy", "XyZzy")]
[TestCase("1234", "1234")]
[TestCase("xy_zzy", "XyZzy")]
[TestCase("me2you", "Me2You")]
[TestCase("IOStream", "IOStream")]
public void PascalCase(string before, string after)
{
CodeGenUtility.ToPascalCase(before).Should().Be(after);
}
[TestCase("xyZzy", "xy_zzy")]
[TestCase("XyZzy", "xy_zzy")]
[TestCase("1234", "1234")]
[TestCase("xy_zzy", "xy_zzy")]
[TestCase("me2you", "me_2_you")]
[TestCase("IOStream", "io_stream")]
public void SnakeCase(string before, string after)
{
CodeGenUtility.ToSnakeCase(before).Should().Be(after);
}
}
}
| using Facility.Definition.CodeGen;
using FluentAssertions;
using NUnit.Framework;
namespace Facility.Definition.UnitTests.CodeGen
{
public sealed class CodeGenUtilityTests
{
[Test]
public void CapitalizeLowerCase()
{
CodeGenUtility.Capitalize("xyzzy").Should().Be("Xyzzy");
}
[Test]
public void CapitalizeUpperCase()
{
CodeGenUtility.Capitalize("Xyzzy").Should().Be("Xyzzy");
}
[Test]
public void CapitalizeNumber()
{
CodeGenUtility.Capitalize("1234").Should().Be("1234");
}
}
}
| mit | C# |
dd64f8d27c1665221a94e2a519b4adee9c41c3b1 | check if config entry already exists | int32at/utils | src/Utils/Configuration/Config.cs | src/Utils/Configuration/Config.cs | using System;
using System.Collections.Generic;
using System.Linq;
using int32.Utils.Extensions;
namespace int32.Utils.Configuration
{
public class Config
{
private readonly List<ConfigEntry> _entries;
public object this[string key]
{
get { return GetConfigEntry(key).Value; }
set { Set(key, value); }
}
public Config()
{
_entries = new List<ConfigEntry>();
}
public void Set(ConfigEntry entry)
{
entry.ThrowIfNull("entry");
if (_entries.Contains(entry))
throw new ArgumentException(string.Format("Entry with key {0} already exists", entry.Key));
_entries.Add(entry);
}
public void Set(string key, object value)
{
Set(new ConfigEntry(key, value));
}
public T Get<T>(string key)
{
return GetConfigEntry(key).Value.As<T>();
}
public void Remove(string key)
{
Remove(i => i.Key.Equals(key));
}
public void Remove(Func<ConfigEntry, bool> where)
{
for (var i = 0; i < _entries.Count; i++)
if (where(_entries[i]))
_entries.RemoveAt(i);
}
private ConfigEntry GetConfigEntry(string key)
{
return _entries.SingleOrDefault(i => i.Key.Equals(key)).ThrowIfNull(key);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using int32.Utils.Extensions;
namespace int32.Utils.Configuration
{
public class Config
{
private readonly List<ConfigEntry> _entries;
public object this[string key]
{
get { return GetConfigEntry(key).Value; }
}
public Config()
{
_entries = new List<ConfigEntry>();
}
public void Set(ConfigEntry entry)
{
_entries.Add(entry);
}
public void Set(string key, object value)
{
_entries.Add(new ConfigEntry(key, value));
}
public T Get<T>(string key)
{
return GetConfigEntry(key).Value.As<T>();
}
public void Remove(string key)
{
Remove(i => i.Key.Equals(key));
}
public void Remove(Func<ConfigEntry, bool> where)
{
for (var i = 0; i < _entries.Count; i++)
if (where(_entries[i]))
_entries.RemoveAt(i);
}
private ConfigEntry GetConfigEntry(string key)
{
return _entries.SingleOrDefault(i => i.Key.Equals(key)).ThrowIfNull(key);
}
}
}
| mit | C# |
e5631bb8ef7657a84529d72b571b9b41448a8b0c | Make sure we register stuff | akavache/Akavache,MarcMagnin/Akavache,bbqchickenrobot/Akavache,gimsum/Akavache,jcomtois/Akavache,PureWeen/Akavache,Loke155/Akavache,christer155/Akavache,martijn00/Akavache,ghuntley/AkavacheSandpit,shana/Akavache,mms-/Akavache,shana/Akavache,MathieuDSTP/MyAkavache,kmjonmastro/Akavache | Akavache/Portable/DependencyResolverMixin.cs | Akavache/Portable/DependencyResolverMixin.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Splat;
namespace Akavache
{
internal interface IWantsToRegisterStuff
{
void Register(IMutableDependencyResolver resolverToUse);
}
public static class DependencyResolverMixin
{
/// <summary>
/// Initializes a ReactiveUI dependency resolver with classes that
/// Akavache uses internally.
/// </summary>
public static void InitializeAkavache(this IMutableDependencyResolver This)
{
var namespaces = new[] {
"Akavache",
"Akavache.Mac",
"Akavache.Deprecated",
"Akavache.Mobile",
"Akavache.Http",
"Akavache.Sqlite3",
};
var fdr = typeof(DependencyResolverMixin);
var assmName = new AssemblyName(
fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", ""));
foreach (var ns in namespaces)
{
var targetType = ns + ".Registrations";
string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns);
var registerTypeClass = Type.GetType(fullName, false);
if (registerTypeClass == null) continue;
var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass);
registerer.Register(This);
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Splat;
namespace Akavache
{
internal interface IWantsToRegisterStuff
{
void Register(IMutableDependencyResolver resolverToUse);
}
public static class DependencyResolverMixin
{
/// <summary>
/// Initializes a ReactiveUI dependency resolver with classes that
/// Akavache uses internally.
/// </summary>
public static void InitializeAkavache(this IMutableDependencyResolver This)
{
var namespaces = new[] {
"Akavache",
"Akavache.Mac",
"Akavache.Mobile",
"Akavache.Sqlite3",
};
var fdr = typeof(DependencyResolverMixin);
var assmName = new AssemblyName(
fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", ""));
foreach (var ns in namespaces)
{
var targetType = ns + ".Registrations";
string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns);
var registerTypeClass = Type.GetType(fullName, false);
if (registerTypeClass == null) continue;
var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass);
registerer.Register(This);
};
}
}
}
| mit | C# |
cad0aed18b445a24a65c1fb699eb8eec12c3d4bf | Add the warrant security type. | krs43/ib-csharp,qusma/ib-csharp,sebfia/ib-csharp | Krs.Ats.IBNet/Enums/SecurityType.cs | Krs.Ats.IBNet/Enums/SecurityType.cs | using System;
using System.ComponentModel;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Contract Security Types
/// </summary>
[Serializable()]
public enum SecurityType
{
/// <summary>
/// Stock
/// </summary>
[Description("STK")] Stock,
/// <summary>
/// Option
/// </summary>
[Description("OPT")] Option,
/// <summary>
/// Future
/// </summary>
[Description("FUT")] Future,
/// <summary>
/// Indice
/// </summary>
[Description("IND")] Index,
/// <summary>
/// FOP = options on futures
/// </summary>
[Description("FOP")] FutureOption,
/// <summary>
/// Cash
/// </summary>
[Description("CASH")] Cash,
/// <summary>
/// For Combination Orders - must use combo leg details
/// </summary>
[Description("BAG")] Bag,
/// <summary>
/// Bond
/// </summary>
[Description("BOND")] Bond,
/// <summary>
/// Warrant
/// </summary>
[Description("WAR")] Warrant,
/// <summary>
/// Undefined Security Type
/// </summary>
[Description("")] Undefined
}
} | using System;
using System.ComponentModel;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Contract Security Types
/// </summary>
[Serializable()]
public enum SecurityType
{
/// <summary>
/// Stock
/// </summary>
[Description("STK")] Stock,
/// <summary>
/// Option
/// </summary>
[Description("OPT")] Option,
/// <summary>
/// Future
/// </summary>
[Description("FUT")] Future,
/// <summary>
/// Indice
/// </summary>
[Description("IND")] Index,
/// <summary>
/// FOP = options on futures
/// </summary>
[Description("FOP")] FutureOption,
/// <summary>
/// Cash
/// </summary>
[Description("CASH")] Cash,
/// <summary>
/// For Combination Orders - must use combo leg details
/// </summary>
[Description("BAG")] Bag,
/// <summary>
/// Bond
/// </summary>
[Description("BOND")] Bond,
/// <summary>
/// Undefined Security Type
/// </summary>
[Description("")] Undefined
}
} | mit | C# |
59c997194ff92f52ce203fc4a2d9b4b494c2f1ca | Test for element equality | JBTech/ExtraLINQ,mariusschulz/ExtraLINQ,modulexcite/ExtraLINQ | ExtraLINQ.Tests/Extensions/NameValueCollection/ToDictionaryTests.cs | ExtraLINQ.Tests/Extensions/NameValueCollection/ToDictionaryTests.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using ExtraLinq;
using FluentAssertions;
using NUnit.Framework;
namespace ExtraLINQ.Tests
{
[TestFixture]
public class ToDictionaryTests
{
[ExpectedException(typeof(ArgumentNullException))]
[Test]
public void ThrowsArgumentNullExceptionWhenCollectionIsNull()
{
NameValueCollection collection = null;
Dictionary<string, string> dictionary = collection.ToDictionary();
}
[Test]
public void ReturnedDictionaryContainsExactlyTheElementsFromTheNameValueCollection()
{
var collection = new NameValueCollection
{
{ "a", "1" },
{ "b", "2" },
{ "c", "3" }
};
Dictionary<string, string> dictionary = collection.ToDictionary();
dictionary.Should().Equal(new Dictionary<string, string>
{
{ "a", "1" },
{ "b", "2" },
{ "c", "3" }
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using ExtraLinq;
using NUnit.Framework;
namespace ExtraLINQ.Tests
{
[TestFixture]
public class ToDictionaryTests
{
[ExpectedException(typeof(ArgumentNullException))]
[Test]
public void ThrowsArgumentNullExceptionWhenCollectionIsNull()
{
NameValueCollection collection = null;
Dictionary<string, string> dictionary = collection.ToDictionary();
}
}
}
| mit | C# |
8afeb4d0943688ac267679c10e6c744e167275b2 | Add helpers for converting to and from Fahrenheit | space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Shared/Utility/TemperatureHelpers.cs | Content.Shared/Utility/TemperatureHelpers.cs | using Content.Shared.Maths;
namespace Content.Shared.Utility
{
public static class TemperatureHelpers
{
public static float CelsiusToKelvin(float celsius)
{
return celsius + PhysicalConstants.ZERO_CELCIUS;
}
public static float CelsiusToFahrenheit(float celsius)
{
return celsius * 9 / 5 + 32;
}
public static float KelvinToCelsius(float kelvin)
{
return kelvin - PhysicalConstants.ZERO_CELCIUS;
}
public static float KelvinToFahrenheit(float kelvin)
{
var celsius = KelvinToCelsius(kelvin);
return CelsiusToFahrenheit(celsius);
}
public static float FahrenheitToCelsius(float fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
public static float FahrenheitToKelvin(float fahrenheit)
{
var celsius = FahrenheitToCelsius(fahrenheit);
return CelsiusToKelvin(celsius);
}
}
}
| using Content.Shared.Maths;
namespace Content.Shared.Utility
{
public static class TemperatureHelpers
{
public static float CelsiusToKelvin(float celsius)
{
return celsius + PhysicalConstants.ZERO_CELCIUS;
}
public static float KelvinToCelsius(float kelvin)
{
return kelvin - PhysicalConstants.ZERO_CELCIUS;
}
}
}
| mit | C# |
dc6170191611470d1dcd8aafe552c5f0d5c84314 | Fix broken tests | mike-ward/Nancy.Pile,mike-ward/Nancy.Pile,mike-ward/Nancy.Pile,mike-ward/Nancy.Pile | Nancy.Pile.Tests/SampleTests.cs | Nancy.Pile.Tests/SampleTests.cs | using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nancy.Testing;
namespace Nancy.Pile.Tests
{
[TestClass]
public class SampleTests
{
[TestMethod]
public void UnminifiedStyleSheetBundleShouldBeCorrectLength()
{
var bootstrapper = new Sample.Bootstrapper();
var browser = new Browser(bootstrapper);
var result = browser.Get("/styles.css", with => with.HttpRequest());
result.StatusCode.Should().Be(HttpStatusCode.OK);
result.Body.ToArray().Length.Should().Be(35358);
}
[TestMethod]
public void UnminifiedScriptBundleShouldBeCorrectLength()
{
var bootstrapper = new Sample.Bootstrapper();
var browser = new Browser(bootstrapper);
var result = browser.Get("/scripts.js", with => with.HttpRequest());
result.StatusCode.Should().Be(HttpStatusCode.OK);
result.Body.ToArray().Length.Should().Be(133503);
}
}
} | using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nancy.Testing;
namespace Nancy.Pile.Tests
{
[TestClass]
public class SampleTests
{
[TestMethod]
public void UnminifiedStyleSheetBundleShouldBeCorrectLength()
{
var bootstrapper = new Sample.Bootstrapper();
var browser = new Browser(bootstrapper);
var result = browser.Get("/styles.css", with => with.HttpRequest());
result.StatusCode.Should().Be(HttpStatusCode.OK);
result.Body.ToArray().Length.Should().Be(35356);
}
[TestMethod]
public void UnminifiedScriptBundleShouldBeCorrectLength()
{
var bootstrapper = new Sample.Bootstrapper();
var browser = new Browser(bootstrapper);
var result = browser.Get("/scripts.js", with => with.HttpRequest());
result.StatusCode.Should().Be(HttpStatusCode.OK);
result.Body.ToArray().Length.Should().Be(133498);
}
}
} | mit | C# |
4d05dd2526698cc3aa47f5e50c0833f95cc8421f | Update Startup.cs | tugberkugurlu/travis-test,tugberkugurlu/travis-test | src/HelloWeb/Startup.cs | src/HelloWeb/Startup.cs | using Microsoft.AspNet.Builder;
using Microsoft.Framework.Logging;
namespace HelloWeb
{
public class Startup
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseStaticFiles();
app.UseWelcomePage();
}
}
}
| using Microsoft.AspNet.Builder;
using Microsoft.Framework.Logging;
namespace HelloWeb
{
public class Startup
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole()
app.UseStaticFiles();
app.UseWelcomePage();
}
}
| mit | C# |
030608ca26ebf72e4bce6a12bc8f103e3c1f8477 | update version | baikangwang/Aeronet,CIMEL/CIMEL | CIMEL.Chart/Properties/AssemblyInfo.cs | CIMEL.Chart/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("大气气溶胶光学参数处理软件(适用于CIMEL太阳光度计数据处理)")]
[assembly: AssemblyDescription("大气气溶胶光学参数处理软件\r\n适用于CIMEL太阳光度计数据反演软件")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Developed and Designed by AYFY")]
[assembly: AssemblyProduct("大气气溶胶光学参数处理软件")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("99fd81db-6c34-49c0-b4eb-52d1e428b497")]
// 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.2.0.18255")]
[assembly: AssemblyFileVersion("1.2.0.18255")]
[assembly: NeutralResourcesLanguageAttribute("zh-CN")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("大气气溶胶光学参数处理软件(适用于CIMEL太阳光度计数据处理)")]
[assembly: AssemblyDescription("大气气溶胶光学参数处理软件\r\n适用于CIMEL太阳光度计数据反演软件")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Developed and Designed by AYFY")]
[assembly: AssemblyProduct("大气气溶胶光学参数处理软件")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("99fd81db-6c34-49c0-b4eb-52d1e428b497")]
// 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.2.0.18254")]
[assembly: AssemblyFileVersion("1.2.0.18254")]
[assembly: NeutralResourcesLanguageAttribute("zh-CN")]
| apache-2.0 | C# |
b24a11e0aacc03ea00fe223ac55d250a8e1bc3c6 | Fix null reference exception | roman-yagodin/R7.News,roman-yagodin/R7.News,roman-yagodin/R7.News | R7.News/Components/NewsPortalConfig.cs | R7.News/Components/NewsPortalConfig.cs | //
// NewsPortalConfig.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 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using YamlDotNet.Serialization;
using System.Collections.ObjectModel;
using R7.News.Providers;
namespace R7.News.Components
{
public class NewsPortalConfig
{
public int DataCacheTime { get; set; }
public string DefaultImagesPath { get; set; }
#region TermUrlProviders
public Collection<string> TermUrlProviders { get; set; }
protected readonly Collection<ITermUrlProvider> TermUrlProvidersInternal = new Collection<ITermUrlProvider> ();
public Collection<ITermUrlProvider> GetTermUrlProviders ()
{
return TermUrlProvidersInternal;
}
public void AddTermUrlProvider (ITermUrlProvider provider)
{
TermUrlProvidersInternal.Add (provider);
}
#endregion
}
}
| //
// NewsPortalConfig.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 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using YamlDotNet.Serialization;
using System.Collections.ObjectModel;
using R7.News.Providers;
namespace R7.News.Components
{
public class NewsPortalConfig
{
public int DataCacheTime { get; set; }
public string DefaultImagesPath { get; set; }
#region TermUrlProviders
public Collection<string> TermUrlProviders { get; set; }
protected Collection<ITermUrlProvider> TermUrlProvidersInternal { get; set; }
public Collection<ITermUrlProvider> GetTermUrlProviders ()
{
return TermUrlProvidersInternal;
}
public void AddTermUrlProvider (ITermUrlProvider provider)
{
TermUrlProvidersInternal.Add (provider);
}
#endregion
}
}
| agpl-3.0 | C# |
83ef7471cc74054e74538dc883f9aadadf80ce0c | Add DebugUtilities.AssertSameRotation | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Viewer/src/common/DebugUtilities.cs | Viewer/src/common/DebugUtilities.cs | using SharpDX;
using System;
using System.Diagnostics;
using System.Threading;
static class DebugUtilities {
public static void Burn(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
}
}
public static void Sleep(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
Thread.Yield();
}
}
[Conditional("DEBUG")]
public static void AssertSamePosition(Vector3 v1, Vector3 v2) {
float distance = Vector3.Distance(v1, v2);
float denominator = (Vector3.Distance(v1, Vector3.Zero) + Vector3.Distance(v2, Vector3.Zero)) / 2 + 1e-1f;
float relativeDistance = distance / denominator;
Debug.Assert(relativeDistance < 1e-2, "not same position");
}
[Conditional("DEBUG")]
public static void AssertSameDirection(Vector3 v1, Vector3 v2) {
Vector3 u1 = Vector3.Normalize(v1);
Vector3 u2 = Vector3.Normalize(v2);
float dotProduct = Vector3.Dot(u1, u2);
Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same direction");
}
[Conditional("DEBUG")]
public static void AssertSameRotation(Quaternion q1, Quaternion q2) {
float dotProduct = Quaternion.Dot(q1, q2);
Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same rotation");
}
}
| using SharpDX;
using System;
using System.Diagnostics;
using System.Threading;
static class DebugUtilities {
public static void Burn(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
}
}
public static void Sleep(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
Thread.Yield();
}
}
[Conditional("DEBUG")]
public static void AssertSamePosition(Vector3 v1, Vector3 v2) {
float distance = Vector3.Distance(v1, v2);
float denominator = (Vector3.Distance(v1, Vector3.Zero) + Vector3.Distance(v2, Vector3.Zero)) / 2 + 1e-1f;
float relativeDistance = distance / denominator;
Debug.Assert(relativeDistance < 1e-2, "not same position");
}
[Conditional("DEBUG")]
public static void AssertSameDirection(Vector3 v1, Vector3 v2) {
Vector3 u1 = Vector3.Normalize(v1);
Vector3 u2 = Vector3.Normalize(v2);
float dotProduct = Vector3.Dot(u1, u2);
Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same direction");
}
}
| mit | C# |
a0c35c247ef52efc8267b3bb18b1220924949c90 | Remove git automerge duplication disaster. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Stores/BitcoinStore.cs | WalletWasabi/Stores/BitcoinStore.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Mempool;
using WalletWasabi.Transactions;
namespace WalletWasabi.Stores
{
/// <summary>
/// The purpose of this class is to safely and performantly manage all the Bitcoin related data
/// that's being serialized to disk, like transactions, wallet files, keys, blocks, index files, etc...
/// </summary>
public class BitcoinStore
{
public bool IsInitialized { get; private set; }
private string WorkFolderPath { get; set; }
private Network Network { get; set; }
public IndexStore IndexStore { get; private set; }
public AllTransactionStore TransactionStore { get; private set; }
public HashChain HashChain { get; private set; }
public MempoolService MempoolService { get; private set; }
/// <summary>
/// This should not be a property, but a creator function, because it'll be cloned left and right by NBitcoin later.
/// So it should not be assumed it's some singleton.
/// </summary>
public MempoolBehavior CreateMempoolBehavior() => new MempoolBehavior(MempoolService);
public async Task InitializeAsync(string workFolderPath, Network network)
{
using (BenchmarkLogger.Measure())
{
WorkFolderPath = Guard.NotNullOrEmptyOrWhitespace(nameof(workFolderPath), workFolderPath, trim: true);
IoHelpers.EnsureDirectoryExists(WorkFolderPath);
Network = Guard.NotNull(nameof(network), network);
IndexStore = new IndexStore();
TransactionStore = new AllTransactionStore();
var networkWorkFolderPath = Path.Combine(WorkFolderPath, Network.ToString());
var indexStoreFolderPath = Path.Combine(networkWorkFolderPath, "IndexStore");
HashChain = new HashChain();
MempoolService = new MempoolService();
var initTasks = new[]
{
IndexStore.InitializeAsync(indexStoreFolderPath, Network, HashChain),
TransactionStore.InitializeAsync(networkWorkFolderPath, Network)
};
await Task.WhenAll(initTasks).ConfigureAwait(false);
IsInitialized = true;
}
}
}
}
| using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Mempool;
using WalletWasabi.Transactions;
namespace WalletWasabi.Stores
{
/// <summary>
/// The purpose of this class is to safely and performantly manage all the Bitcoin related data
/// that's being serialized to disk, like transactions, wallet files, keys, blocks, index files, etc...
/// </summary>
public class BitcoinStore
{
public bool IsInitialized { get; private set; }
private string WorkFolderPath { get; set; }
private Network Network { get; set; }
public IndexStore IndexStore { get; private set; }
public AllTransactionStore TransactionStore { get; private set; }
public HashChain HashChain { get; private set; }
public MempoolService MempoolService { get; private set; }
/// <summary>
/// This should not be a property, but a creator function, because it'll be cloned left and right by NBitcoin later.
/// So it should not be assumed it's some singleton.
/// </summary>
public MempoolBehavior CreateMempoolBehavior() => new MempoolBehavior(MempoolService);
public async Task InitializeAsync(string workFolderPath, Network network)
{
using (BenchmarkLogger.Measure())
{
WorkFolderPath = Guard.NotNullOrEmptyOrWhitespace(nameof(workFolderPath), workFolderPath, trim: true);
IoHelpers.EnsureDirectoryExists(WorkFolderPath);
Network = Guard.NotNull(nameof(network), network);
IndexStore = new IndexStore();
TransactionStore = new AllTransactionStore();
var networkWorkFolderPath = Path.Combine(WorkFolderPath, Network.ToString());
var indexStoreFolderPath = Path.Combine(networkWorkFolderPath, "IndexStore");
HashChain = new HashChain();
MempoolService = new MempoolService();
var initTasks = new[]
{
IndexStore.InitializeAsync(indexStoreFolderPath, Network, HashChain),
TransactionStore.InitializeAsync(networkWorkFolderPath, Network)
};
await Task.WhenAll(initTasks).ConfigureAwait(false);
await IndexStore.InitializeAsync(indexStoreFolderPath, Network, HashChain).ConfigureAwait(false);
IsInitialized = true;
}
}
}
}
| mit | C# |
4159d88826012245d6cb6db32a76e596f88222fe | Add size property to HorizontalRule | kswoll/WootzJs,x335/WootzJs,x335/WootzJs,kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs | WootzJs.Mvc/Views/HorizontalRule.cs | WootzJs.Mvc/Views/HorizontalRule.cs | namespace WootzJs.Mvc.Views
{
public class HorizontalRule : Control
{
public HorizontalRule() : base("hr")
{
}
public int Size
{
get { return Node.HasAttribute("size") ? int.Parse(Node.GetAttribute("size")) : 1; }
set { Node.SetAttribute("size", value.ToString()); }
}
}
} | namespace WootzJs.Mvc.Views
{
public class HorizontalRule : Control
{
public HorizontalRule() : base("hr")
{
}
}
} | mit | C# |
95e4e64acfeb12a37d6ca7001ad5d278c602c3c8 | Add future project key parameter | duncanpMS/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,jango2015/sonar-msbuild-runner,LunicLynx/sonar-msbuild-runner,HSAR/sonar-msbuild-runner,jessehouwing/sonar-msbuild-runner,LunicLynx/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-msbuild-runner,SonarSource-DotNet/sonar-msbuild-runner,SonarSource/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,jessehouwing/sonar-msbuild-runner,jabbera/sonar-msbuild-runner,dbolkensteyn/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-VisualStudio/sonar-msbuild-runner | src/Sonar.FxCopRuleset/Program.cs | src/Sonar.FxCopRuleset/Program.cs | //-----------------------------------------------------------------------
// <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation">
// (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace Sonar.FxCopRuleset
{
class Program
{
public static int Main(string[] args)
{
if (args.Length != 5)
{
Console.WriteLine("Expected to be called with exactly 4 arguments:");
Console.WriteLine(" 1) SonarQube Server URL");
Console.WriteLine(" 2) SonarQube Project Key");
Console.WriteLine(" 3) SonarQube Username");
Console.WriteLine(" 4) SonarQube Password");
Console.WriteLine(" 5) Dump path");
return 1;
}
var server = args[0];
var project = args[1];
var username = args[2];
var password = args[3];
var dumpPath = args[4];
using (WebClient client = new WebClient())
{
// TODO What if username/password contains ':' or accents?
var credentials = string.Format("{0}:{1}", username, password);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
// TODO Custom rules
var url = string.Format("{0}/api/rules/search?activation=true&f=internalKey&ps=500&repositories=fxcop", server);
var jsonContents = client.DownloadString(url);
var json = JObject.Parse(jsonContents);
var ids = json["rules"].Select(r => r["internalKey"].ToString()).ToList();
File.WriteAllText(dumpPath, RulesetWriter.ToString(ids));
}
return 0;
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="Program.cs" company="SonarSource SA and Microsoft Corporation">
// (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace Sonar.FxCopRuleset
{
class Program
{
public static int Main(string[] args)
{
if (args.Length != 4)
{
Console.WriteLine("Expected to be called with exactly 4 arguments:");
Console.WriteLine(" 1) SonarQube Server URL");
Console.WriteLine(" 2) SonarQube Username");
Console.WriteLine(" 3) SonarQube Password");
Console.WriteLine(" 4) Dump path");
return 1;
}
var server = args[0];
var username = args[1];
var password = args[2];
var dumpPath = args[3];
using (WebClient client = new WebClient())
{
// TODO What if username/password contains ':' or accents?
var credentials = string.Format("{0}:{1}", username, password);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
// TODO Custom rules
var url = string.Format("{0}/api/rules/search?activation=true&f=internalKey&ps=500&repositories=fxcop", server);
var jsonContents = client.DownloadString(url);
var json = JObject.Parse(jsonContents);
var ids = json["rules"].Select(r => r["internalKey"].ToString()).ToList();
File.WriteAllText(dumpPath, RulesetWriter.ToString(ids));
}
return 0;
}
}
}
| mit | C# |
5496e7204acb157c400b15282cbeefa135aef48c | Write some more tests for secret splitting | 0culus/ElectronicCash | ElectronicCash.Tests/SecretSplittingTests.cs | ElectronicCash.Tests/SecretSplittingTests.cs | using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
[Test]
public void OnSecretSplit_FlagsShouldBeTrue()
{
var splitter = new SecretSplittingProvider(Message, RandBytes);
splitter.SplitSecretBetweenTwoPeople();
Assert.IsTrue(splitter.IsRProtected);
Assert.IsTrue(splitter.IsSProtected);
Assert.IsTrue(splitter.IsSecretMessageProtected);
}
}
}
| using NUnit.Framework;
using SecretSplitting;
namespace ElectronicCash.Tests
{
[TestFixture]
class SecretSplittingTests
{
private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);
[Test]
public void OnSplit_OriginalMessageShouldBeRecoverable()
{
_splitter.SplitSecretBetweenTwoPeople();
var r = _splitter.R;
var s = _splitter.S;
var m = Helpers.ExclusiveOr(r, s);
Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
}
}
}
| mit | C# |
8562183f0590e23cedbdaed939dce1e90e0bb4ef | Fix incorrect inheritance relationship | terrajobst/nquery-vnext | NQuery.Language/Syntax/SelectClauseSyntax.cs | NQuery.Language/Syntax/SelectClauseSyntax.cs | using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace NQuery.Language
{
public sealed class SelectClauseSyntax : SyntaxNode
{
private readonly SyntaxToken _selectKeyword;
private readonly SyntaxToken? _distinctAllKeyword;
private readonly TopClauseSyntax _topClause;
private readonly ReadOnlyCollection<SelectColumnSyntax> _columns;
public SelectClauseSyntax(SyntaxToken selectKeyword, SyntaxToken? distinctAllKeyword, TopClauseSyntax topClause, IList<SelectColumnSyntax> selectColumns)
{
_selectKeyword = selectKeyword;
_distinctAllKeyword = distinctAllKeyword;
_topClause = topClause;
_columns = new ReadOnlyCollection<SelectColumnSyntax>(selectColumns);
}
public override SyntaxKind Kind
{
get { return SyntaxKind.SelectClause; }
}
public override IEnumerable<SyntaxNodeOrToken> GetChildren()
{
yield return _selectKeyword;
if (_distinctAllKeyword != null)
yield return _distinctAllKeyword.Value;
if (_topClause != null)
yield return _topClause;
foreach (var selectColumn in _columns)
yield return selectColumn;
}
public SyntaxToken SelectKeyword
{
get { return _selectKeyword; }
}
public SyntaxToken? DistinctAllKeyword
{
get { return _distinctAllKeyword; }
}
public TopClauseSyntax TopClause
{
get { return _topClause; }
}
public ReadOnlyCollection<SelectColumnSyntax> Columns
{
get { return _columns; }
}
}
} | using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace NQuery.Language
{
public sealed class SelectClauseSyntax : QuerySyntax
{
private readonly SyntaxToken _selectKeyword;
private readonly SyntaxToken? _distinctAllKeyword;
private readonly TopClauseSyntax _topClause;
private readonly ReadOnlyCollection<SelectColumnSyntax> _columns;
public SelectClauseSyntax(SyntaxToken selectKeyword, SyntaxToken? distinctAllKeyword, TopClauseSyntax topClause, IList<SelectColumnSyntax> selectColumns)
{
_selectKeyword = selectKeyword;
_distinctAllKeyword = distinctAllKeyword;
_topClause = topClause;
_columns = new ReadOnlyCollection<SelectColumnSyntax>(selectColumns);
}
public override SyntaxKind Kind
{
get { return SyntaxKind.SelectClause; }
}
public override IEnumerable<SyntaxNodeOrToken> GetChildren()
{
yield return _selectKeyword;
if (_distinctAllKeyword != null)
yield return _distinctAllKeyword.Value;
if (_topClause != null)
yield return _topClause;
foreach (var selectColumn in _columns)
yield return selectColumn;
}
public SyntaxToken SelectKeyword
{
get { return _selectKeyword; }
}
public SyntaxToken? DistinctAllKeyword
{
get { return _distinctAllKeyword; }
}
public TopClauseSyntax TopClause
{
get { return _topClause; }
}
public ReadOnlyCollection<SelectColumnSyntax> Columns
{
get { return _columns; }
}
}
} | mit | C# |
44af2f94d7bc5d07dc43e7d0f5e63eae8ca47c7e | Use specified font for RTF exporting | GetTabster/Tabster | Plugins/FileTypes/RtfFile/RtfFileExporter.cs | Plugins/FileTypes/RtfFile/RtfFileExporter.cs | #region
using System;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Data;
using Tabster.Data.Processing;
#endregion
namespace RtfFile
{
internal class RtfFileExporter : ITablatureFileExporter
{
private RichTextBox _rtb;
#region Implementation of ITablatureFileExporter
public FileType FileType { get; private set; }
public Version Version
{
get { return new Version("1.0"); }
}
public void Export(ITablatureFile file, string fileName, TablatureFileExportArguments args)
{
if (_rtb == null)
_rtb = new RichTextBox {Font = args.Font, Text = file.Contents};
_rtb.SaveFile(fileName);
_rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created
}
#endregion
public RtfFileExporter()
{
FileType = new FileType("Rich Text Format File", ".rtf");
}
~RtfFileExporter()
{
if (_rtb != null && !_rtb.IsDisposed)
_rtb.Dispose();
}
}
} | #region
using System;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Data;
using Tabster.Data.Processing;
#endregion
namespace RtfFile
{
internal class RtfFileExporter : ITablatureFileExporter
{
private Font _font;
private RichTextBox _rtb;
#region Implementation of ITablatureFileExporter
public FileType FileType { get; private set; }
public Version Version
{
get { return new Version("1.0"); }
}
public void Export(ITablatureFile file, string fileName)
{
if (_font == null)
_font = new Font("Courier New", 9F);
if (_rtb == null)
_rtb = new RichTextBox {Font = new Font("Courier New", 9F), Text = file.Contents};
_rtb.SaveFile(fileName);
_rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created
}
#endregion
public RtfFileExporter()
{
FileType = new FileType("Rich Text Format File", ".rtf");
}
~RtfFileExporter()
{
if (_font != null)
_font.Dispose();
if (_rtb != null && !_rtb.IsDisposed)
_rtb.Dispose();
}
}
} | apache-2.0 | C# |
671d5a8e4acf43cb469ca8644d70af0c6b34e7b7 | Bump version. | andreassjoberg/Tfs2015SetPicture | Tfs2015SetPicture/Properties/AssemblyInfo.cs | Tfs2015SetPicture/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("Tfs2015SetPicture")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tfs2015SetPicture")]
[assembly: AssemblyCopyright("")]
[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("1b8e987a-858f-4469-aa72-c966465b780f")]
// 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.1.*")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tfs2015SetPicture")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tfs2015SetPicture")]
[assembly: AssemblyCopyright("")]
[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("1b8e987a-858f-4469-aa72-c966465b780f")]
// 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.*")]
| mit | C# |
c084fb800a659f41ac7e86dc49d14122c43bd082 | Disable adding redundant arguments for getting machine id | ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks | src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs | src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs | using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
return ComputerId.Value.ToFingerPrintMd5Hash();
}
}
} | using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location;
var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value;
return value.ToFingerPrintMd5Hash();
}
}
} | apache-2.0 | C# |
1e6d745cac04c93f0bc303b14835df2f63f375a3 | Update grammar in StaticConstructorExceptionAnalyzer.cs #839 | giggio/code-cracker,jwooley/code-cracker,carloscds/code-cracker,eriawan/code-cracker,code-cracker/code-cracker,code-cracker/code-cracker,carloscds/code-cracker | src/CSharp/CodeCracker/Design/StaticConstructorExceptionAnalyzer.cs | src/CSharp/CodeCracker/Design/StaticConstructorExceptionAnalyzer.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Design
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class StaticConstructorExceptionAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "Don't throw exceptions inside static constructors.";
internal const string MessageFormat = "Don't throw exceptions inside static constructors.";
internal const string Category = SupportedCategories.Design;
const string Description = "Static constructors are called before a class is used for the first time. Exceptions thrown "
+ "in static constructors force the use of a try block and should be avoided.";
internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.StaticConstructorException.ToDiagnosticId(),
Title,
MessageFormat,
Category,
DiagnosticSeverity.Warning,
true,
description: Description,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.StaticConstructorException));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ConstructorDeclaration);
private static void Analyzer(SyntaxNodeAnalysisContext context)
{
if (context.IsGenerated()) return;
var ctor = (ConstructorDeclarationSyntax)context.Node;
if (!ctor.Modifiers.Any(SyntaxKind.StaticKeyword)) return;
if (ctor.Body == null) return;
var @throw = ctor.Body.ChildNodes().OfType<ThrowStatementSyntax>().FirstOrDefault();
if (@throw == null) return;
context.ReportDiagnostic(Diagnostic.Create(Rule, @throw.GetLocation(), ctor.Identifier.Text));
}
}
}
| using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Design
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class StaticConstructorExceptionAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "Don't throw exception inside static constructors.";
internal const string MessageFormat = "Don't throw exception inside static constructors.";
internal const string Category = SupportedCategories.Design;
const string Description = "Static constructor are called before the first time a class is used but the "
+ "caller doesn't control when exactly.\r\n"
+ "Exception thrown in this context force callers to use 'try' block around any useage of the class "
+ "and should be avoided.";
internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.StaticConstructorException.ToDiagnosticId(),
Title,
MessageFormat,
Category,
DiagnosticSeverity.Warning,
true,
description: Description,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.StaticConstructorException));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ConstructorDeclaration);
private static void Analyzer(SyntaxNodeAnalysisContext context)
{
if (context.IsGenerated()) return;
var ctor = (ConstructorDeclarationSyntax)context.Node;
if (!ctor.Modifiers.Any(SyntaxKind.StaticKeyword)) return;
if (ctor.Body == null) return;
var @throw = ctor.Body.ChildNodes().OfType<ThrowStatementSyntax>().FirstOrDefault();
if (@throw == null) return;
context.ReportDiagnostic(Diagnostic.Create(Rule, @throw.GetLocation(), ctor.Identifier.Text));
}
}
} | apache-2.0 | C# |
8b5b331f4f56b8203a1fbe1a6b845dc712565ecd | Change the tags on the report | ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector | KenticoInspector.Reports/PageTypeNotAssignedToSite/Report.cs | KenticoInspector.Reports/PageTypeNotAssignedToSite/Report.cs | using KenticoInspector.Core;
using KenticoInspector.Core.Constants;
using KenticoInspector.Core.Helpers;
using KenticoInspector.Core.Models;
using KenticoInspector.Core.Services.Interfaces;
using KenticoInspector.Reports.PageTypeNotAssignedToSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace KenticoInspector.Reports.PageTypeNotAssignedToSite
{
public class Report : AbstractReport<Terms>
{
private readonly IDatabaseService databaseService;
public Report(IDatabaseService databaseService, IReportMetadataService reportMetadataService) : base(reportMetadataService)
{
this.databaseService = databaseService;
}
public override IList<Version> CompatibleVersions => VersionHelper.GetVersionList("10", "11", "12");
public override IList<string> Tags => new List<string>
{
ReportTags.Health,
ReportTags.Consistency
};
public override ReportResults GetResults()
{
var pageTypesNotAssigned = databaseService.ExecuteSqlFromFile<UnassignedPageTypes>(Scripts.PageTypeNotAssigned);
return CompileResults(pageTypesNotAssigned);
}
private ReportResults CompileResults(IEnumerable<UnassignedPageTypes> unassignedPageTypes)
{
var countUnassignedPageTypes = unassignedPageTypes.Count();
var results = new ReportResults
{
Status = ReportResultsStatus.Information,
Type = ReportResultsType.Table,
Data = new TableResult<dynamic>()
{
Name = Metadata.Terms.PageTypesNotAssigned,
Rows = unassignedPageTypes
}
};
if (countUnassignedPageTypes == 0)
{
results.Summary = Metadata.Terms.AllpageTypesAssigned;
}
else
{
results.Summary = Metadata.Terms.CountPageTypeNotAssigned.With(new { count = countUnassignedPageTypes });
}
return results;
}
}
} | using KenticoInspector.Core;
using KenticoInspector.Core.Constants;
using KenticoInspector.Core.Helpers;
using KenticoInspector.Core.Models;
using KenticoInspector.Core.Services.Interfaces;
using KenticoInspector.Reports.PageTypeNotAssignedToSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace KenticoInspector.Reports.PageTypeNotAssignedToSite
{
public class Report : AbstractReport<Terms>
{
private readonly IDatabaseService databaseService;
public Report(IDatabaseService databaseService, IReportMetadataService reportMetadataService) : base(reportMetadataService)
{
this.databaseService = databaseService;
}
public override IList<Version> CompatibleVersions => VersionHelper.GetVersionList("10", "11", "12");
public override IList<string> Tags => new List<string>
{
ReportTags.Information
};
public override ReportResults GetResults()
{
var pageTypesNotAssigned = databaseService.ExecuteSqlFromFile<UnassignedPageTypes>(Scripts.PageTypeNotAssigned);
return CompileResults(pageTypesNotAssigned);
}
private ReportResults CompileResults(IEnumerable<UnassignedPageTypes> unassignedPageTypes)
{
var countUnassignedPageTypes = unassignedPageTypes.Count();
var results = new ReportResults
{
Status = ReportResultsStatus.Information,
Type = ReportResultsType.Table,
Data = new TableResult<dynamic>()
{
Name = Metadata.Terms.PageTypesNotAssigned,
Rows = unassignedPageTypes
}
};
if (countUnassignedPageTypes == 0)
{
results.Summary = Metadata.Terms.AllpageTypesAssigned;
}
else
{
results.Summary = Metadata.Terms.CountPageTypeNotAssigned.With(new { count = countUnassignedPageTypes });
}
return results;
}
}
} | mit | C# |
abcf1d54b710f990c55a7e30a7f3bb7e1bd2803c | Fix build error | jotschgl/helix-toolkit,Iluvatar82/helix-toolkit,helix-toolkit/helix-toolkit,smischke/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit,JeremyAnsel/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs | Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CanvasMock.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using SharpDX;
using SharpDX.Direct3D11;
namespace HelixToolkit.Wpf.SharpDX.Tests.Controls
{
class CanvasMock : IRenderHost
{
public CanvasMock()
{
RenderTechniquesManager = new DefaultRenderTechniquesManager();
RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Phong];
EffectsManager = new DefaultEffectsManager(RenderTechniquesManager);
Device = EffectsManager.Device;
}
private int renderCycles = 1;
public int RenderCycles
{
set { renderCycles = value; }
get { return renderCycles; }
}
public Device Device { get; private set; }
public Color4 ClearColor { get; private set; }
public bool IsShadowMapEnabled { get; private set; }
public MSAALevel MSAA { get; set; }
public IRenderer Renderable { get; set; }
public RenderTechnique RenderTechnique { get; private set; }
public double ActualHeight { get; private set; }
public double ActualWidth { get; private set; }
public IEffectsManager EffectsManager { get; set; }
public IRenderTechniquesManager RenderTechniquesManager { get; set; }
public bool IsBusy
{
get;private set;
}
public void SetDefaultRenderTargets()
{
}
public void SetDefaultColorTargets(DepthStencilView dsv)
{
}
public event EventHandler<SharpDX.Utilities.RelayExceptionEventArgs> ExceptionOccurred;
public void InvalidateRender()
{
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CanvasMock.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using SharpDX;
using SharpDX.Direct3D11;
namespace HelixToolkit.Wpf.SharpDX.Tests.Controls
{
class CanvasMock : IRenderHost
{
public CanvasMock()
{
RenderTechniquesManager = new DefaultRenderTechniquesManager();
RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Phong];
EffectsManager = new DefaultEffectsManager(RenderTechniquesManager);
Device = EffectsManager.Device;
}
public Device Device { get; private set; }
public Color4 ClearColor { get; private set; }
public bool IsShadowMapEnabled { get; private set; }
public MSAALevel MSAA { get; set; }
public IRenderer Renderable { get; set; }
public RenderTechnique RenderTechnique { get; private set; }
public double ActualHeight { get; private set; }
public double ActualWidth { get; private set; }
public IEffectsManager EffectsManager { get; set; }
public IRenderTechniquesManager RenderTechniquesManager { get; set; }
public bool IsBusy
{
get;private set;
}
public void SetDefaultRenderTargets()
{
}
public void SetDefaultColorTargets(DepthStencilView dsv)
{
}
public event EventHandler<SharpDX.Utilities.RelayExceptionEventArgs> ExceptionOccurred;
public void InvalidateRender()
{
}
}
}
| mit | C# |
a5e22c052e0f0ad7bdf6c8fd4a0756b6c5079927 | Fix incorrect namespace | bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather | api/test/BellRichM.Exceptions.Test/BusinessExceptionSpecs.cs | api/test/BellRichM.Exceptions.Test/BusinessExceptionSpecs.cs | using BellRichM.Exceptions;
using FluentAssertions;
using Machine.Specifications;
using Moq;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using It = Machine.Specifications.It;
#pragma warning disable SA1649 // File name should match first type name
namespace BellRichM.Exceptions.Test
{
internal class When_info_argument_is_null
{
protected static RoleExceptionTestClass businessException;
protected static Exception thrownException;
Establish context = () =>
businessException = new RoleExceptionTestClass("code");
Because of = () =>
thrownException = Catch.Exception(() => businessException.GetObjectData(null, default(StreamingContext)));
It should_throw_expected_exception = () =>
thrownException.ShouldBeOfExactType<ArgumentNullException>();
}
internal class When_serializing_deserializing_RoleException
{
protected static BusinessException originalException;
protected static BusinessException deserializedException;
protected static MemoryStream serializedStream;
protected static BinaryFormatter formatter;
Establish context = () =>
{
var innerEx = new Exception("foo");
originalException = new RoleExceptionTestClass("code", "message", innerEx);
serializedStream = new MemoryStream(new byte[4096]);
formatter = new BinaryFormatter();
};
Cleanup after = () =>
serializedStream.Dispose();
Because of = () =>
{
formatter.Serialize(serializedStream, originalException);
serializedStream.Position = 0;
deserializedException = (RoleExceptionTestClass)formatter.Deserialize(serializedStream);
};
It should_have_correct_Code = () =>
originalException.Code.ShouldEqual(deserializedException.Code);
It should_have_correct_Message = () =>
originalException.Message.ShouldEqual(deserializedException.Message);
It should_have_correct_innerException_Message = () =>
originalException.InnerException.Message.ShouldEqual(deserializedException.InnerException.Message);
}
[Serializable]
#pragma warning disable S3376 // Class name should end with exception
internal class RoleExceptionTestClass : BusinessException
#pragma warning restore S3376 // Class name should end with exception
{
public RoleExceptionTestClass(string code)
: base(code)
{
}
public RoleExceptionTestClass(string code, string message)
: base(code, message)
{
}
public RoleExceptionTestClass(string code, string message, Exception innerException)
: base(code, message, innerException)
{
}
protected RoleExceptionTestClass(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
#pragma warning restore SA1649 // File name should match first type name
| using BellRichM.Exceptions;
using FluentAssertions;
using Machine.Specifications;
using Moq;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using It = Machine.Specifications.It;
#pragma warning disable SA1649 // File name should match first type name
namespace BellRichM.Api.Exceptions.Test
{
internal class When_info_argument_is_null
{
protected static RoleExceptionTestClass businessException;
protected static Exception thrownException;
Establish context = () =>
businessException = new RoleExceptionTestClass("code");
Because of = () =>
thrownException = Catch.Exception(() => businessException.GetObjectData(null, default(StreamingContext)));
It should_throw_expected_exception = () =>
thrownException.ShouldBeOfExactType<ArgumentNullException>();
}
internal class When_serializing_deserializing_RoleException
{
protected static BusinessException originalException;
protected static BusinessException deserializedException;
protected static MemoryStream serializedStream;
protected static BinaryFormatter formatter;
Establish context = () =>
{
var innerEx = new Exception("foo");
originalException = new RoleExceptionTestClass("code", "message", innerEx);
serializedStream = new MemoryStream(new byte[4096]);
formatter = new BinaryFormatter();
};
Cleanup after = () =>
serializedStream.Dispose();
Because of = () =>
{
formatter.Serialize(serializedStream, originalException);
serializedStream.Position = 0;
deserializedException = (RoleExceptionTestClass)formatter.Deserialize(serializedStream);
};
It should_have_correct_Code = () =>
originalException.Code.ShouldEqual(deserializedException.Code);
It should_have_correct_Message = () =>
originalException.Message.ShouldEqual(deserializedException.Message);
It should_have_correct_innerException_Message = () =>
originalException.InnerException.Message.ShouldEqual(deserializedException.InnerException.Message);
}
[Serializable]
#pragma warning disable S3376 // Class name should end with exception
internal class RoleExceptionTestClass : BusinessException
#pragma warning restore S3376 // Class name should end with exception
{
public RoleExceptionTestClass(string code)
: base(code)
{
}
public RoleExceptionTestClass(string code, string message)
: base(code, message)
{
}
public RoleExceptionTestClass(string code, string message, Exception innerException)
: base(code, message, innerException)
{
}
protected RoleExceptionTestClass(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
#pragma warning restore SA1649 // File name should match first type name
| mit | C# |
cff0b90cd5bda66abbaa26e53a0ab6cda3fc7cf3 | Update AssemblyInfo.cs | lust4life/WebApiProxy,faniereynders/WebApiProxy | WebApiProxy.Tasks/Properties/AssemblyInfo.cs | WebApiProxy.Tasks/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("WebApiProxy C# Proxy Client Generator")]
[assembly: AssemblyDescription("Generates a C# proxy for communicating to a RESTful Web Api that implements the WebApiProxy provider")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("WebApiProxy")]
[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("45d385f6-c964-4aa9-9fd9-9abcbc84a07b")]
// 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: AssemblyInformationalVersion("1.0.6.*")]
[assembly: AssemblyVersion("1.0.6.*")]
[assembly: AssemblyFileVersion("1.0.6.*")]
| 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("WebApiProxy C# Proxy Client Generator")]
[assembly: AssemblyDescription("Generates a C# proxy for communicating to a RESTful Web Api that implements the WebApiProxy provider")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("WebApiProxy")]
[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("45d385f6-c964-4aa9-9fd9-9abcbc84a07b")]
// 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: AssemblyInformationalVersion("1.0.4.*")]
[assembly: AssemblyVersion("1.0.5.*")]
[assembly: AssemblyFileVersion("1.0.5.*")]
| mit | C# |
60efbed8bff3079493d57f7fe38002690532b3cc | update version | strotz/pustota,strotz/pustota,strotz/pustota | src/Pustota.Maven.Cmd/Properties/AssemblyInfo.cs | src/Pustota.Maven.Cmd/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("Pustota.Maven.Cmd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pustota.Maven.Cmd")]
[assembly: AssemblyCopyright("Copyright © Novo Development Group 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7c64bc0-05d1-4fac-a441-b7484a37dc4c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.*")]
[assembly: AssemblyFileVersion("1.0.0.10")]
| 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("Pustota.Maven.Cmd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pustota.Maven.Cmd")]
[assembly: AssemblyCopyright("Copyright © Novo Development Group 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7c64bc0-05d1-4fac-a441-b7484a37dc4c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
673d0f3e879159bd3b6bd4c74bc2a66e71f7ec96 | Create vol_01.cs | webjug/vol | vol_01.cs | vol_01.cs | using System;
namespace vol
{
public class MyClass()
{
}
}
| unlicense | C# | |
338e30974d4870a0eb23f396e6b8af757e5ff049 | Remove Hyena.Timer usage from last commit | mono-soc-2011/banshee,babycaseny/banshee,stsundermann/banshee,petejohanson/banshee,GNOME/banshee,dufoli/banshee,petejohanson/banshee,Carbenium/banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,babycaseny/banshee,arfbtwn/banshee,lamalex/Banshee,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,ixfalia/banshee,GNOME/banshee,lamalex/Banshee,ixfalia/banshee,lamalex/Banshee,petejohanson/banshee,allquixotic/banshee-gst-sharp-work,Dynalon/banshee-osx,dufoli/banshee,babycaseny/banshee,mono-soc-2011/banshee,GNOME/banshee,directhex/banshee-hacks,GNOME/banshee,babycaseny/banshee,Dynalon/banshee-osx,lamalex/Banshee,babycaseny/banshee,Carbenium/banshee,Dynalon/banshee-osx,stsundermann/banshee,ixfalia/banshee,Carbenium/banshee,arfbtwn/banshee,dufoli/banshee,babycaseny/banshee,babycaseny/banshee,petejohanson/banshee,allquixotic/banshee-gst-sharp-work,allquixotic/banshee-gst-sharp-work,mono-soc-2011/banshee,stsundermann/banshee,GNOME/banshee,mono-soc-2011/banshee,mono-soc-2011/banshee,directhex/banshee-hacks,directhex/banshee-hacks,GNOME/banshee,stsundermann/banshee,directhex/banshee-hacks,dufoli/banshee,Carbenium/banshee,arfbtwn/banshee,directhex/banshee-hacks,ixfalia/banshee,Dynalon/banshee-osx,GNOME/banshee,petejohanson/banshee,Carbenium/banshee,dufoli/banshee,babycaseny/banshee,directhex/banshee-hacks,GNOME/banshee,stsundermann/banshee,dufoli/banshee,Dynalon/banshee-osx,ixfalia/banshee,arfbtwn/banshee,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,lamalex/Banshee,Carbenium/banshee,arfbtwn/banshee,petejohanson/banshee,ixfalia/banshee,ixfalia/banshee,arfbtwn/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,dufoli/banshee,lamalex/Banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,dufoli/banshee,Dynalon/banshee-osx,ixfalia/banshee,arfbtwn/banshee,arfbtwn/banshee | src/Core/Banshee.ThickClient/Banshee.Sources.Gui/LazyLoadSourceContents.cs | src/Core/Banshee.ThickClient/Banshee.Sources.Gui/LazyLoadSourceContents.cs | //
// LazyLoadSourceContents.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Banshee.Sources;
namespace Banshee.Sources.Gui
{
public class LazyLoadSourceContents<T> : ISourceContents where T : ISourceContents
{
private object [] args;
private ISourceContents actual_contents;
private ISourceContents ActualContents {
get {
if (actual_contents == null) {
lock (this) {
if (actual_contents == null) {
actual_contents = (T) Activator.CreateInstance (typeof(T), args);
}
}
}
return actual_contents;
}
}
public LazyLoadSourceContents (params object [] args)
{
this.args = args;
}
public bool SetSource (ISource source)
{
return ActualContents.SetSource (source);
}
public void ResetSource ()
{
ActualContents.ResetSource ();
}
public ISource Source {
get { return ActualContents.Source; }
}
public Widget Widget {
get { return ActualContents.Widget; }
}
}
}
| //
// LazyLoadSourceContents.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Banshee.Sources;
namespace Banshee.Sources.Gui
{
public class LazyLoadSourceContents<T> : ISourceContents where T : ISourceContents
{
private object [] args;
private ISourceContents actual_contents;
private ISourceContents ActualContents {
get {
if (actual_contents == null) {
lock (this) {
if (actual_contents == null) {
using (new Hyena.Timer (String.Format ("Creating new {0}", typeof(T).Name))) {
actual_contents = (T) Activator.CreateInstance (typeof(T), args);
}
}
}
}
return actual_contents;
}
}
public LazyLoadSourceContents (params object [] args)
{
this.args = args;
}
public bool SetSource (ISource source)
{
return ActualContents.SetSource (source);
}
public void ResetSource ()
{
ActualContents.ResetSource ();
}
public ISource Source {
get { return ActualContents.Source; }
}
public Widget Widget {
get { return ActualContents.Widget; }
}
}
}
| mit | C# |
e32fb5ad2f880414b2aae8b8cf2c7f4eeb3bf197 | fix new line delimiter | LykkeCity/MT,LykkeCity/MT,LykkeCity/MT | src/MarginTrading.Backend.Core/OvernightSwaps/OvernightSwapNotification.cs | src/MarginTrading.Backend.Core/OvernightSwaps/OvernightSwapNotification.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace MarginTrading.Backend.Core
{
public class OvernightSwapNotification
{
public string CliendId { get; set; }
public IReadOnlyList<AccountCalculations> CalculationsByAccount { get; set; }
public string CurrentDate => DateTime.UtcNow.ToString("dd MMMM yyyy");
public class AccountCalculations
{
public string AccountId { get; set; }
public string AccountCurrency { get; set; }
public IReadOnlyList<SingleCalculation> Calculations { get; set; }
public decimal TotalCost => Calculations.Sum(x => x.Cost);
}
public class SingleCalculation
{
public string Instrument { get; set; }
public string Direction { get; set; }
public decimal Volume { get; set; }
public decimal SwapRate { get; set; }
public decimal Cost { get; set; }
public List<string> PositionIds { get; set; }
public string PositionIdsString => string.Join("\r\n", PositionIds);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace MarginTrading.Backend.Core
{
public class OvernightSwapNotification
{
public string CliendId { get; set; }
public IReadOnlyList<AccountCalculations> CalculationsByAccount { get; set; }
public string CurrentDate => DateTime.UtcNow.ToString("dd MMMM yyyy");
public class AccountCalculations
{
public string AccountId { get; set; }
public string AccountCurrency { get; set; }
public IReadOnlyList<SingleCalculation> Calculations { get; set; }
public decimal TotalCost => Calculations.Sum(x => x.Cost);
}
public class SingleCalculation
{
public string Instrument { get; set; }
public string Direction { get; set; }
public decimal Volume { get; set; }
public decimal SwapRate { get; set; }
public decimal Cost { get; set; }
public List<string> PositionIds { get; set; }
public string PositionIdsString => string.Join("<br />", PositionIds);
}
}
} | mit | C# |
38fcc693c01f0fde2c164e5cca616dd4fc88db38 | Set the right shader type. | izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib | ChamberLib.OpenTK/GlslShaderImporter.cs | ChamberLib.OpenTK/GlslShaderImporter.cs | using System;
using ChamberLib.Content;
using System.IO;
namespace ChamberLib.OpenTK
{
public class GlslShaderImporter
{
public GlslShaderImporter(ShaderStageImporter next=null)
{
this.next = next;
}
readonly ShaderStageImporter next;
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (File.Exists(filename))
{
}
else if (type == ShaderType.Vertex && File.Exists(filename + ".vert"))
{
filename += ".vert";
}
else if (type == ShaderType.Fragment && File.Exists(filename + ".frag"))
{
filename += ".frag";
}
else if (next != null)
{
return next(filename, type, importer);
}
else
{
throw new FileNotFoundException(
string.Format(
"The {0} shader file could not be found: {1}",
type,
filename),
filename);
}
var source = File.ReadAllText(filename);
return new ShaderContent(
vs: (type == ShaderType.Vertex ? source : null),
fs: (type == ShaderType.Fragment ? source : null),
name: filename,
type: type);
}
}
}
| using System;
using ChamberLib.Content;
using System.IO;
namespace ChamberLib.OpenTK
{
public class GlslShaderImporter
{
public GlslShaderImporter(ShaderStageImporter next=null)
{
this.next = next;
}
readonly ShaderStageImporter next;
public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
{
if (File.Exists(filename))
{
}
else if (type == ShaderType.Vertex && File.Exists(filename + ".vert"))
{
filename += ".vert";
}
else if (type == ShaderType.Fragment && File.Exists(filename + ".frag"))
{
filename += ".frag";
}
else if (next != null)
{
return next(filename, type, importer);
}
else
{
throw new FileNotFoundException(
string.Format(
"The {0} shader file could not be found: {1}",
type,
filename),
filename);
}
var source = File.ReadAllText(filename);
return new ShaderContent(
vs: (type == ShaderType.Vertex ? source : null),
fs: (type == ShaderType.Fragment ? source : null),
name: filename,
type: ShaderType.Vertex);
}
}
}
| lgpl-2.1 | C# |
a40dcd3dc222ec7029f0155b619efc263242fcfe | Update base link. | ForNeVeR/EvilPlanner,ForNeVeR/EvilPlanner,ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/EvilPlanner | EvilPlanner/Views/Shared/_Layout.cshtml | EvilPlanner/Views/Shared/_Layout.cshtml | @using System.Web.Configuration
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>F. von Never — @ViewBag.Title</title>
<base href="@WebConfigurationManager.AppSettings["BaseUrl"]"/>
<link rel="stylesheet" type="text/css" href="Content/css"/>
</head>
<body>
<div id="header">
<div id="logo">
<a href="https://fornever.me/">Инженер, программист, джентльмен</a>
</div>
<div id="navigation">
<a href="https://fornever.me/archive.html">Посты</a>
<a href="https://fornever.me/contact.html">Контакты</a>
<a href=".">Планы</a>
</div>
</div>
<div id="content">
<h1>@ViewBag.Title</h1>
@RenderBody()
</div>
<footer>
<div>
<a class="tag" href="https://fornever.me/rss.xml">RSS</a>
<a class="tag" href="https://github.com/ForNeVeR/fornever.me">GitHub</a>
</div>
<div>
Сайт сгенерирован при помощи
<a href="http://jaspervdj.be/hakyll">Hakyll</a>
</div>
</footer>
</body>
</html>
| @using System.Web.Configuration
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>F. von Never — @ViewBag.Title</title>
<base href="@WebConfigurationManager.AppSettings["BaseUrl"]"/>
<link rel="stylesheet" type="text/css" href="Content/css"/>
</head>
<body>
<div id="header">
<div id="logo">
<a href="https://fornever.me/">Инженер, программист, джентльмен</a>
</div>
<div id="navigation">
<a href="https://fornever.me/archive.html">Посты</a>
<a href="https://fornever.me/contact.html">Контакты</a>
<a href="~/">Планы</a>
</div>
</div>
<div id="content">
<h1>@ViewBag.Title</h1>
@RenderBody()
</div>
<footer>
<div>
<a class="tag" href="https://fornever.me/rss.xml">RSS</a>
<a class="tag" href="https://github.com/ForNeVeR/fornever.me">GitHub</a>
</div>
<div>
Сайт сгенерирован при помощи
<a href="http://jaspervdj.be/hakyll">Hakyll</a>
</div>
</footer>
</body>
</html>
| mit | C# |
2b8eaecd993b1112b38da019d7664215b8ad8e49 | Revert TeamFoundationIdentity because it changes the identity received | pmiossec/git-tfs,adbre/git-tfs,modulexcite/git-tfs,bleissem/git-tfs,WolfVR/git-tfs,PKRoma/git-tfs,guyboltonking/git-tfs,WolfVR/git-tfs,modulexcite/git-tfs,adbre/git-tfs,modulexcite/git-tfs,guyboltonking/git-tfs,NathanLBCooper/git-tfs,guyboltonking/git-tfs,jeremy-sylvis-tmg/git-tfs,kgybels/git-tfs,kgybels/git-tfs,WolfVR/git-tfs,steveandpeggyb/Public,git-tfs/git-tfs,jeremy-sylvis-tmg/git-tfs,codemerlin/git-tfs,codemerlin/git-tfs,vzabavnov/git-tfs,steveandpeggyb/Public,NathanLBCooper/git-tfs,kgybels/git-tfs,NathanLBCooper/git-tfs,andyrooger/git-tfs,adbre/git-tfs,codemerlin/git-tfs,steveandpeggyb/Public,jeremy-sylvis-tmg/git-tfs,bleissem/git-tfs,bleissem/git-tfs | GitTfs.VsCommon/TfsHelper.Vs2012Base.cs | GitTfs.VsCommon/TfsHelper.Vs2012Base.cs | using System;
using System.IO;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using StructureMap;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.VsCommon
{
public abstract class TfsHelperVs2012Base : TfsHelperBase
{
protected abstract string TfsVersionString { get; }
protected TfsHelperVs2012Base(TextWriter stdout, TfsApiBridge bridge, IContainer container)
: base(stdout, bridge, container) { }
protected override bool HasWorkItems(Changeset changeset)
{
return Retry.Do(() => changeset.AssociatedWorkItems.Length > 0);
}
private string vsInstallDir;
protected override string GetVsInstallDir()
{
if (vsInstallDir == null)
{
vsInstallDir = TryGetRegString(@"Software\WOW6432Node\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetRegString(@"Software\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetUserRegString(@"Software\WOW6432Node\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir")
?? TryGetUserRegString(@"Software\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir");
}
return vsInstallDir;
}
#pragma warning disable 618
private IGroupSecurityService GroupSecurityService
{
get { return GetService<IGroupSecurityService>(); }
}
public override IIdentity GetIdentity(string username)
{
return _bridge.Wrap<WrapperForIdentity, Identity>(Retry.Do(() => GroupSecurityService.ReadIdentity(SearchFactor.AccountName, username, QueryMembership.None)));
}
protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
{
return HasCredentials ?
new TfsTeamProjectCollection(uri, GetCredential(), new UICredentialsProvider()) :
new TfsTeamProjectCollection(uri, new UICredentialsProvider());
#pragma warning restore 618
}
}
}
| using System;
using System.IO;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.VersionControl.Client;
using StructureMap;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.VsCommon
{
public abstract class TfsHelperVs2012Base : TfsHelperBase
{
protected abstract string TfsVersionString { get; }
protected TfsHelperVs2012Base(TextWriter stdout, TfsApiBridge bridge, IContainer container)
: base(stdout, bridge, container) { }
protected override bool HasWorkItems(Changeset changeset)
{
return Retry.Do(() => changeset.AssociatedWorkItems.Length > 0);
}
private string vsInstallDir;
protected override string GetVsInstallDir()
{
if (vsInstallDir == null)
{
vsInstallDir = TryGetRegString(@"Software\WOW6432Node\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetRegString(@"Software\Microsoft\VisualStudio\" + TfsVersionString, "InstallDir")
?? TryGetUserRegString(@"Software\WOW6432Node\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir")
?? TryGetUserRegString(@"Software\Microsoft\WDExpress\" + TfsVersionString + "_Config", "InstallDir");
}
return vsInstallDir;
}
private IIdentityManagementService GroupSecurityService
{
get { return GetService<IIdentityManagementService>(); }
}
public override IIdentity GetIdentity(string username)
{
return _bridge.Wrap<WrapperForIdentity, TeamFoundationIdentity>(Retry.Do(() => GroupSecurityService.ReadIdentity(IdentitySearchFactor.AccountName, username, MembershipQuery.None, ReadIdentityOptions.None)));
}
protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
{
#pragma warning disable 618
return HasCredentials ?
new TfsTeamProjectCollection(uri, GetCredential(), new UICredentialsProvider()) :
new TfsTeamProjectCollection(uri, new UICredentialsProvider());
#pragma warning restore 618
}
}
}
| apache-2.0 | C# |
81aee807a003c53ccdf8f06604b5e5b94114f550 | Document type indexes - new options like isRequired, close #198 | kotorihq/kotori-core | KotoriCore/Domains/DocumentTypeIndex.cs | KotoriCore/Domains/DocumentTypeIndex.cs | namespace KotoriCore.Domains
{
/// <summary>
/// Document type index.
/// </summary>
public class DocumentTypeIndex : IDomain
{
/// <summary>
/// Gets or sets "from" property.
/// </summary>
/// <value>"From" property.</value>
public string From { get; set; }
// TODO
public bool IsRequired { get; set; } = false;
/// <summary>
/// Gets or sets "to" index.
/// </summary>
/// <value>"To" index.</value>
public Shushu.Enums.IndexField To { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Domains.DocumentTypeIndex"/> class.
/// </summary>
public DocumentTypeIndex()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Domains.DocumentTypeIndex"/> class.
/// </summary>
/// <param name="from">"From" property.</param>
/// <param name="to">"To" index.</param>
public DocumentTypeIndex(string from, Shushu.Enums.IndexField to)
{
From = from;
To = to;
}
}
}
| namespace KotoriCore.Domains
{
/// <summary>
/// Document type index.
/// </summary>
public class DocumentTypeIndex : IDomain
{
/// <summary>
/// Gets or sets "from" property.
/// </summary>
/// <value>"From" property.</value>
public string From { get; set; }
/// <summary>
/// Gets or sets "to" index.
/// </summary>
/// <value>"To" index.</value>
public Shushu.Enums.IndexField To { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Domains.DocumentTypeIndex"/> class.
/// </summary>
public DocumentTypeIndex()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:KotoriCore.Domains.DocumentTypeIndex"/> class.
/// </summary>
/// <param name="from">"From" property.</param>
/// <param name="to">"To" index.</param>
public DocumentTypeIndex(string from, Shushu.Enums.IndexField to)
{
From = from;
To = to;
}
}
}
| mit | C# |
9203bb2f4830e82cdc2465713c9d6c95721b6b21 | Fix settings test. | jlennox/HeartRate | Lennox.HeartRate.Tests/SettingsTests.cs | Lennox.HeartRate.Tests/SettingsTests.cs | using System.IO;
using HeartRate;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lennox.HeartRate.Tests
{
[TestClass]
public class SettingsTests
{
[TestMethod]
public void SettingsSaveToFileAsExpected()
{
const string expected = @"<?xml version=""1.0""?>
<HeartRateSettingsProtocol xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Version>1</Version>
<FontName>Arial</FontName>
<UIFontName>Arial</UIFontName>
<UIFontStyle>Regular</UIFontStyle>
<UIFontUseSize>false</UIFontUseSize>
<UIFontSize>20</UIFontSize>
<UIWindowSizeX>350</UIWindowSizeX>
<UIWindowSizeY>250</UIWindowSizeY>
<UITextAlignment>MiddleCenter</UITextAlignment>
<AlertLevel>70</AlertLevel>
<WarnLevel>65</WarnLevel>
<AlertTimeout>120000</AlertTimeout>
<DisconnectedTimeout>10000</DisconnectedTimeout>
<Color>FFADD8E6</Color>
<WarnColor>FFFF0000</WarnColor>
<UIColor>FF00008B</UIColor>
<UIWarnColor>FFFF0000</UIWarnColor>
<UIBackgroundColor>00FFFFFF</UIBackgroundColor>
<UIBackgroundLayout>Stretch</UIBackgroundLayout>
<Sizable>true</Sizable>
<LogFormat>csv</LogFormat>
<LogDateFormat>OA</LogDateFormat>
<LogFile> </LogFile>
<IBIFile> </IBIFile>
</HeartRateSettingsProtocol>";
using (var tempFile = new TempFile())
{
var def = HeartRateSettings.CreateDefault(tempFile);
def.Save();
var actual = File.ReadAllText(tempFile);
AssertStringEqualsNormalizeEndings(expected, actual);
}
}
private static void AssertStringEqualsNormalizeEndings(
string expected, string actual)
{
expected = (expected ?? "").Replace("\r", "").Trim();
actual = (actual ?? "").Replace("\r", "").Trim();
Assert.AreEqual(expected, actual);
}
}
}
| using System.IO;
using HeartRate;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lennox.HeartRate.Tests
{
[TestClass]
public class SettingsTests
{
[TestMethod]
public void SettingsSaveToFileAsExpected()
{
const string expected = @"<?xml version=""1.0""?>
<HeartRateSettingsProtocol xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<Version>1</Version>
<FontName>Arial</FontName>
<UIFontName>Arial</UIFontName>
<AlertLevel>70</AlertLevel>
<WarnLevel>65</WarnLevel>
<AlertTimeout>120000</AlertTimeout>
<DisconnectedTimeout>10000</DisconnectedTimeout>
<Color>FFADD8E6</Color>
<WarnColor>FFFF0000</WarnColor>
<UIColor>FF00008B</UIColor>
<UIWarnColor>FFFF0000</UIWarnColor>
<UIBackgroundColor>00FFFFFF</UIBackgroundColor>
<Sizable>true</Sizable>
<LogFormat>csv</LogFormat>
<LogDateFormat>OA</LogDateFormat>
<LogFile> </LogFile>
</HeartRateSettingsProtocol>";
using (var tempFile = new TempFile())
{
var def = HeartRateSettings.CreateDefault(tempFile);
def.Save();
var actual = File.ReadAllText(tempFile);
AssertStringEqualsNormalizeEndings(expected, actual);
}
}
private static void AssertStringEqualsNormalizeEndings(
string expected, string actual)
{
expected = (expected ?? "").Replace("\r", "").Trim();
actual = (actual ?? "").Replace("\r", "").Trim();
Assert.AreEqual(expected, actual);
}
}
}
| mit | C# |
2475ccb0df87152929e440d081f3399cf76a9051 | Update AssemblyInfo.cs | RytisLT/LiteDB,falahati/LiteDB,RytisLT/LiteDB,mbdavid/LiteDB,falahati/LiteDB,89sos98/LiteDB,89sos98/LiteDB | LiteDB.Shell/Properties/AssemblyInfo.cs | LiteDB.Shell/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("LiteDB.Shell")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LiteDB.Shell")]
[assembly: AssemblyCopyright("MIT © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("01ce385b-31a7-4b1a-9487-23fe8acb3888")]
[assembly: AssemblyVersion("3.1.2.0")]
[assembly: AssemblyFileVersion("3.1.2.0")]
[assembly: NeutralResourcesLanguage("en")]
| using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("LiteDB.Shell")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LiteDB.Shell")]
[assembly: AssemblyCopyright("MIT © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("01ce385b-31a7-4b1a-9487-23fe8acb3888")]
[assembly: AssemblyVersion("3.1.1.0")]
[assembly: AssemblyFileVersion("3.1.1.0")]
[assembly: NeutralResourcesLanguage("en")]
| mit | C# |
899942611fcb085fc09226c84a7bbbd47500450f | Add tests for time display | ppy/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu | osu.Game.Tournament.Tests/Screens/TestSceneScheduleScreen.cs | osu.Game.Tournament.Tests/Screens/TestSceneScheduleScreen.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Schedule;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneScheduleScreen : TournamentTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both });
Add(new ScheduleScreen());
}
[Test]
public void TestCurrentMatchTime()
{
setMatchDate(TimeSpan.FromDays(-1));
setMatchDate(TimeSpan.FromSeconds(5));
setMatchDate(TimeSpan.FromMinutes(4));
setMatchDate(TimeSpan.FromHours(3));
}
private void setMatchDate(TimeSpan relativeTime)
// Humanizer cannot handle negative timespans.
=> AddStep($"start time is {relativeTime}", () =>
{
var match = CreateSampleMatch();
match.Date.Value = DateTimeOffset.Now + relativeTime;
Ladder.CurrentMatch.Value = match;
});
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Schedule;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneScheduleScreen : TournamentTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both });
Add(new ScheduleScreen());
}
}
}
| mit | C# |
4517b4c38b678ee02a03993a893f3ad799f4d743 | clean up | CityofSantaMonica/Orchard.ParkingData,RaghavAbboy/Orchard.ParkingData | Migrations.cs | Migrations.cs | using System;
using CSM.ParkingData.Models;
using Orchard.Data.Migration;
namespace CSM.ParkingData
{
public class Migrations : DataMigrationImpl
{
public int Create()
{
SchemaBuilder.CreateTable(
typeof(SensorEvent).Name,
table => table
.Column<long>("Id", col => col.PrimaryKey().Identity())
.Column<long>("TransmissionId", col => col.NotNull().Unique())
.Column<string>("ClientId", col => col.WithLength(512).NotNull())
.Column<long>("SessionId", col => col.NotNull())
.Column<string>("EventType", col => col.WithLength(2).NotNull())
.Column<DateTime>("TransmissionTime", col => col.NotNull())
.Column<DateTime>("EventTime", col => col.NotNull())
.Column<string>("MeteredSpace_Id", col => col.NotNull())
);
SchemaBuilder.CreateTable(
typeof(MeteredSpace).Name,
table => table
.Column<long>("Id", col => col.PrimaryKey().Identity())
.Column<string>("MeterId", col => col.NotNull().Unique())
.Column<string>("Area", col => col.WithLength(512))
.Column<string>("SubArea", col => col.WithLength(512))
.Column<string>("Zone", col => col.WithLength(512))
.Column<double>("Latitude")
.Column<double>("Longitude")
.Column<bool>("Active", col => col.NotNull())
);
return 1;
}
}
} | using System;
using CSM.ParkingData.Models;
using Orchard.Data;
using Orchard.Data.Migration;
namespace CSM.ParkingData.Data
{
public class Migrations : DataMigrationImpl
{
private readonly IRepository<SensorEvent> _sensorEventsRepository;
private readonly IRepository<MeteredSpace> _meteredSpacesRepository;
public Migrations(
IRepository<SensorEvent> sensorEventsRepository,
IRepository<MeteredSpace> meteredSpacesRepository)
{
_sensorEventsRepository = sensorEventsRepository;
_meteredSpacesRepository = meteredSpacesRepository;
}
public int Create()
{
SchemaBuilder.CreateTable(
typeof(SensorEvent).Name,
table => table
.Column<long>("Id", col => col.PrimaryKey().Identity())
.Column<long>("TransmissionId", col => col.NotNull().Unique())
.Column<string>("ClientId", col => col.WithLength(512).NotNull())
.Column<long>("SessionId", col => col.NotNull())
.Column<string>("EventType", col => col.WithLength(2).NotNull())
.Column<DateTime>("TransmissionTime", col => col.NotNull())
.Column<DateTime>("EventTime", col => col.NotNull())
.Column<string>("MeteredSpace_Id", col => col.NotNull())
);
SchemaBuilder.CreateTable(
typeof(MeteredSpace).Name,
table => table
.Column<long>("Id", col => col.PrimaryKey().Identity())
.Column<string>("MeterId", col => col.NotNull().Unique())
.Column<string>("Area", col => col.WithLength(512))
.Column<string>("SubArea", col => col.WithLength(512))
.Column<string>("Zone", col => col.WithLength(512))
.Column<double>("Latitude")
.Column<double>("Longitude")
.Column<bool>("Active", col => col.NotNull())
);
return 1;
}
}
} | mit | C# |
4f79d6d63cf6cdabd50f8ebf4e9b6acc709d08f2 | Update compatibility checks for user language permissions | KevinJump/uSync,KevinJump/uSync,KevinJump/uSync | uSync.Core/uSyncCapabilityChecker.cs | uSync.Core/uSyncCapabilityChecker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Configuration;
namespace uSync.Core
{
/// <summary>
/// a centralized way of telling if the current version of umbraco has
/// certain features or not.
/// </summary>
public class uSyncCapabilityChecker
{
private readonly IUmbracoVersion _version;
public uSyncCapabilityChecker(IUmbracoVersion version)
{
_version = version;
}
/// <summary>
/// History cleanup was introduced in Umbraco 9.1
/// </summary>
/// <remarks>
/// anything above v9.1 has history cleanup.
/// </remarks>
public bool HasHistoryCleanup
=> _version.Version.Major != 9 || _version.Version.Minor >= 1;
/// <summary>
/// Has a runtime mode introduced in v10.1
/// </summary>
/// <remarks>
/// Runtime mode of Production means you can't update views etc.
/// </remarks>
public bool HasRuntimeMode
=> _version.Version.Major > 10 ||
_version.Version.Major == 10 && _version.Version.Minor > 1;
/// <summary>
/// User groups has Language Permissions - introduced in Umbraco 10.2.0
/// </summary>
public bool HasGroupLanguagePermissions => _version.Version >= new Version(10, 2, 0);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Configuration;
namespace uSync.Core
{
/// <summary>
/// a centralized way of telling if the current version of umbraco has
/// certain features or not.
/// </summary>
public class uSyncCapabilityChecker
{
private readonly IUmbracoVersion _version;
public uSyncCapabilityChecker(IUmbracoVersion version)
{
_version = version;
}
/// <summary>
/// History cleanup was introduced in Umbraco 9.1
/// </summary>
/// <remarks>
/// anything above v9.1 has history cleanup.
/// </remarks>
public bool HasHistoryCleanup
=> _version.Version.Major != 9 || _version.Version.Minor >= 1;
/// <summary>
/// Has a runtime mode introduced in v10.1
/// </summary>
/// <remarks>
/// Runtime mode of Production means you can't update views etc.
/// </remarks>
public bool HasRuntimeMode
=> _version.Version.Major > 10 ||
_version.Version.Major == 10 && _version.Version.Minor > 1;
}
}
| mpl-2.0 | C# |
61f4dcbafda336c384f77a0e0efff8209aabcb3a | update to match ThaiBahtText parameter ordering | greatfriends/ThaiBahtText,greatfriends/ThaiBahtText,greatfriends/ThaiBahtText | GFDN.ThaiBahtText/ThaiBahtTextOptions.cs | GFDN.ThaiBahtText/ThaiBahtTextOptions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GreatFriends.ThaiBahtText {
public class ThaiBahtTextOptions {
public UsesEt Mode { get; set; }
public Unit Unit { get; set; }
public bool AppendBahtOnly { get; set; }
public int DecimalPlaces { get; set; }
public ThaiBahtTextOptions()
: this(mode: UsesEt.TensOnly,
unit: ThaiBahtText.Unit.Baht,
decimalPlaces: 2,
appendBahtOnly: true) {
//
}
public ThaiBahtTextOptions(UsesEt mode = UsesEt.TensOnly,
Unit unit = Unit.Baht,
int decimalPlaces = 2,
bool appendBahtOnly = true) {
this.Mode = mode;
this.Unit = unit;
this.AppendBahtOnly = appendBahtOnly;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GreatFriends.ThaiBahtText {
public class ThaiBahtTextOptions {
public UsesEt Mode { get; set; }
public Unit Unit { get; set; }
public bool AppendBahtOnly { get; set; }
public int DecimalPlaces { get; set; }
public ThaiBahtTextOptions()
: this(mode: UsesEt.TensOnly,
unit: ThaiBahtText.Unit.Baht,
appendBahtOnly: true,
decimalPlaces: 2) {
//
}
public ThaiBahtTextOptions(UsesEt mode = UsesEt.TensOnly,
Unit unit = Unit.Baht,
bool appendBahtOnly = true,
int decimalPlaces = 2) {
this.Mode = mode;
this.Unit = unit;
this.AppendBahtOnly = appendBahtOnly;
}
}
}
| mit | C# |
07d9e864506794d93a03bc68efd825d935013e8f | Correct namespace to fix failure | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/IdentitySample.Mvc/Views/Shared/_LoginPartial.cshtml | samples/IdentitySample.Mvc/Views/Shared/_LoginPartial.cshtml | @using System.Security.Claims
@if (User.IsSignedIn())
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
} | @using System.Security.Principal
@if (User.IsSignedIn())
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
} | apache-2.0 | C# |
7a97c257d80b8e77455ec9ed210d6c7a4898c8ad | Make header of header middleware publicly accessible | InfiniteSoul/Azuria | Azuria/Middleware/StaticHeaderMiddleware.cs | Azuria/Middleware/StaticHeaderMiddleware.cs | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azuria.ErrorHandling;
using Azuria.Requests.Builder;
namespace Azuria.Middleware
{
/// <summary>
/// Adds some static headers to the request. They indicate things like application, version and api key used.
/// </summary>
public class StaticHeaderMiddleware : IMiddleware
{
/// <summary>
///
/// </summary>
/// <param name="staticHeaders"></param>
public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders)
{
this.Header = staticHeaders;
}
/// <summary>
///
/// </summary>
/// <value></value>
public IDictionary<string, string> Header { get; }
/// <inheritdoc />
public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next,
CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this.Header), cancellationToken);
}
/// <inheritdoc />
public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request,
MiddlewareAction<T> next, CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this.Header), cancellationToken);
}
}
} | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azuria.ErrorHandling;
using Azuria.Requests.Builder;
namespace Azuria.Middleware
{
/// <summary>
/// Adds some static headers to the request. They indicate things like application, version and api key used.
/// </summary>
public class StaticHeaderMiddleware : IMiddleware
{
private readonly IDictionary<string, string> _staticHeaders;
/// <summary>
///
/// </summary>
/// <param name="staticHeaders"></param>
public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders)
{
this._staticHeaders = staticHeaders;
}
/// <inheritdoc />
public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next,
CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this._staticHeaders), cancellationToken);
}
/// <inheritdoc />
public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request,
MiddlewareAction<T> next, CancellationToken cancellationToken = default)
{
return next(request.WithHeader(this._staticHeaders), cancellationToken);
}
}
} | mit | C# |
fe302676f71b297942fb1687afe9befffb8567df | fix - updated namespace in route mapping of EmbeddedResourceController | uComponents/nuPickers,uComponents/nuPickers,uComponents/nuPickers | source/nuPickers/EmbeddedResource/EmbeddedResourceStartup.cs | source/nuPickers/EmbeddedResource/EmbeddedResourceStartup.cs | namespace nuPickers.EmbeddedResource
{
using ClientDependency.Core;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core;
public class EmbeddedResourceStartup : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
base.ApplicationStarted(umbracoApplication, applicationContext);
RouteTable
.Routes
.MapRoute(
name: "nuPickersShared",
url: EmbeddedResource.ROOT_URL.TrimStart("~/") + "{folder}/{file}",
defaults: new
{
controller = "EmbeddedResource",
action = "GetSharedResource"
},
namespaces: new[] { "nuPickers.EmbeddedResource" });
FileWriters.AddWriterForExtension(EmbeddedResource.FILE_EXTENSION, new EmbeddedResourceWriter());
}
protected override bool ExecuteWhenApplicationNotConfigured
{
get { return true; }
}
}
}
| namespace nuPickers.EmbeddedResource
{
using ClientDependency.Core;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core;
public class EmbeddedResourceStartup : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
base.ApplicationStarted(umbracoApplication, applicationContext);
RouteTable
.Routes
.MapRoute(
name: "nuPickersShared",
url: EmbeddedResource.ROOT_URL.TrimStart("~/") + "{folder}/{file}",
defaults: new
{
controller = "EmbeddedResource",
action = "GetSharedResource"
},
namespaces: new[] { "nuPickers" });
FileWriters.AddWriterForExtension(EmbeddedResource.FILE_EXTENSION, new EmbeddedResourceWriter());
}
protected override bool ExecuteWhenApplicationNotConfigured
{
get { return true; }
}
}
}
| mit | C# |
fbff56d52482b7739481d7c09118f7f779c60d6a | Simplify parsing string to Topology enum | Sitecore/Sitecore-Instance-Manager | src/SIM.Pipelines/Install/Containers/InstallContainerArgs.cs | src/SIM.Pipelines/Install/Containers/InstallContainerArgs.cs | using System;
using System.Globalization;
using ContainerInstaller;
using SIM.Pipelines.Processors;
namespace SIM.Pipelines.Install.Containers
{
public enum Topology
{
Xm1,
Xp0,
Xp1
}
public class InstallContainerArgs : ProcessorArgs
{
public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology)
{
this.EnvModel = model;
this.FilesRoot = filesRoot;
this.Destination = destination;
this.Topology = (Topology)Enum.Parse(typeof(Topology), topology, true);
}
public EnvModel EnvModel { get; }
public string Destination
{
get; set;
}
public Topology Topology { get; }
public string FilesRoot
{
get;
}
}
}
| using System;
using System.Globalization;
using ContainerInstaller;
using SIM.Pipelines.Processors;
namespace SIM.Pipelines.Install.Containers
{
public enum Topology
{
Xm1,
Xp0,
Xp1
}
public static class StringExtentions
{
public static Topology ToTopology(this string tpl)
{
if (tpl.Equals("xp0", StringComparison.InvariantCultureIgnoreCase))
{
return Topology.Xp0;
}
if (tpl.Equals("xp1", StringComparison.InvariantCultureIgnoreCase))
{
return Topology.Xp1;
}
if (tpl.Equals("xm1", StringComparison.InvariantCultureIgnoreCase))
{
return Topology.Xm1;
}
throw new InvalidOperationException("Topology cannot be resolved from '" + tpl + "'");
}
}
public class InstallContainerArgs : ProcessorArgs
{
public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology)
{
this.EnvModel = model;
this.FilesRoot = filesRoot;
this.Destination = destination;
this.Topology = topology.ToTopology();
}
public EnvModel EnvModel { get; }
public string Destination
{
get; set;
}
public Topology Topology { get; }
public string FilesRoot
{
get;
}
}
}
| mit | C# |
44cd05908a60817a6bbbfed4d57b1550b231ad1e | Use await instead. | danielwertheim/mycouch,danielwertheim/mycouch | src/Tests/MyCouch.Net45.IntegrationTests/ClientExtensions.cs | src/Tests/MyCouch.Net45.IntegrationTests/ClientExtensions.cs | using MyCouch.Extensions;
using MyCouch.Requests;
using MyCouch.Responses;
namespace MyCouch.IntegrationTests
{
internal static class ClientExtensions
{
internal static void ClearAllDocuments(this IClient client)
{
var query = new QuerySystemViewRequest("_all_docs").Configure(q => q.Stale(Stale.UpdateAfter));
var response = client.Views.QueryAsync<dynamic>(query).Result;
BulkDelete(client, response);
response = client.Views.QueryAsync<dynamic>(query).Result;
BulkDelete(client, response);
}
private static async void BulkDelete(IClient client, ViewQueryResponse<dynamic> response)
{
if (response.IsEmpty)
return;
var bulkRequest = new BulkRequest();
foreach (var row in response.Rows)
bulkRequest.Delete(row.Id, row.Value.rev.ToString());
await client.Documents.BulkAsync(bulkRequest).ForAwait();
}
}
} | using MyCouch.Requests;
using MyCouch.Responses;
namespace MyCouch.IntegrationTests
{
internal static class ClientExtensions
{
internal static void ClearAllDocuments(this IClient client)
{
var query = new QuerySystemViewRequest("_all_docs").Configure(q => q.Stale(Stale.UpdateAfter));
var response = client.Views.QueryAsync<dynamic>(query).Result;
BulkDelete(client, response);
response = client.Views.QueryAsync<dynamic>(query).Result;
BulkDelete(client, response);
}
private static void BulkDelete(IClient client, ViewQueryResponse<dynamic> response)
{
if (response.IsEmpty)
return;
var bulkRequest = new BulkRequest();
foreach (var row in response.Rows)
bulkRequest.Delete(row.Id, row.Value.rev.ToString());
client.Documents.BulkAsync(bulkRequest).Wait();
}
}
} | mit | C# |
bbae88e1bbd23098cede29ff01c63aefee1789f6 | change version | vevix/DigitalOcean.API | DigitalOcean.API/Properties/AssemblyInfo.cs | DigitalOcean.API/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DigitalOcean.API")]
[assembly: AssemblyDescription(".NET wrapper of the DigitalOcean API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thomas McNiven")]
[assembly: AssemblyProduct("DigitalOcean.API")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7057d92f-7d8e-4221-a9c3-c13e07799fdb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DigitalOcean.API")]
[assembly: AssemblyDescription(".NET wrapper of the DigitalOcean API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thomas McNiven")]
[assembly: AssemblyProduct("DigitalOcean.API")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7057d92f-7d8e-4221-a9c3-c13e07799fdb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")] | mit | C# |
c2e25edec01ded992b492da77fc584823d0b3780 | Fix StickerOwnerUserId from config | MrRoundRobin/telegram.bot,AndyDingo/telegram.bot,TelegramBots/telegram.bot | test/Telegram.Bot.Tests.Integ/Framework/ConfigurationProvider.cs | test/Telegram.Bot.Tests.Integ/Framework/ConfigurationProvider.cs | using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace Telegram.Bot.Tests.Integ.Framework
{
public static class ConfigurationProvider
{
public static TestConfigurations TestConfigurations;
static ConfigurationProvider()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.Development.json", true)
.AddEnvironmentVariables("TelegramBot_")
.Build();
TestConfigurations = new TestConfigurations
{
ApiToken = configuration[nameof(TestConfigurations.ApiToken)],
AllowedUserNames = configuration[nameof(TestConfigurations.AllowedUserNames)],
SuperGroupChatId = configuration[nameof(TestConfigurations.SuperGroupChatId)],
ChannelChatId = configuration[nameof(TestConfigurations.ChannelChatId)],
PaymentProviderToken = configuration[nameof(TestConfigurations.PaymentProviderToken)],
RegularGroupMemberId = configuration[nameof(TestConfigurations.RegularGroupMemberId)],
};
if (long.TryParse(configuration[nameof(TestConfigurations.TesterPrivateChatId)], out long privateChat))
{
TestConfigurations.TesterPrivateChatId = privateChat;
}
if (int.TryParse(configuration[nameof(TestConfigurations.StickerOwnerUserId)], out int userId))
{
TestConfigurations.StickerOwnerUserId = userId;
}
if (string.IsNullOrWhiteSpace(TestConfigurations.ApiToken))
throw new ArgumentNullException(nameof(TestConfigurations.ApiToken), "API token is not provided or is empty.");
if (TestConfigurations.ApiToken?.Length < 25)
throw new ArgumentException("API token is too short.", nameof(TestConfigurations.ApiToken));
if (!TestConfigurations.AllowedUserNamesArray.Any())
throw new ArgumentException("Allowed user names is not provided", nameof(TestConfigurations.AllowedUserNames));
}
}
}
| using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace Telegram.Bot.Tests.Integ.Framework
{
public static class ConfigurationProvider
{
public static TestConfigurations TestConfigurations;
static ConfigurationProvider()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.Development.json", true)
.AddEnvironmentVariables("TelegramBot_")
.Build();
TestConfigurations = new TestConfigurations
{
ApiToken = configuration[nameof(TestConfigurations.ApiToken)],
AllowedUserNames = configuration[nameof(TestConfigurations.AllowedUserNames)],
SuperGroupChatId = configuration[nameof(TestConfigurations.SuperGroupChatId)],
ChannelChatId = configuration[nameof(TestConfigurations.ChannelChatId)],
PaymentProviderToken = configuration[nameof(TestConfigurations.PaymentProviderToken)],
RegularGroupMemberId = configuration[nameof(TestConfigurations.RegularGroupMemberId)],
};
if (long.TryParse(configuration[nameof(TestConfigurations.TesterPrivateChatId)], out long privateChat))
{
TestConfigurations.TesterPrivateChatId = privateChat;
}
if (int.TryParse(configuration[nameof(TestConfigurations.TesterPrivateChatId)], out int userId))
{
TestConfigurations.StickerOwnerUserId = userId;
}
if (string.IsNullOrWhiteSpace(TestConfigurations.ApiToken))
throw new ArgumentNullException(nameof(TestConfigurations.ApiToken), "API token is not provided or is empty.");
if (TestConfigurations.ApiToken?.Length < 25)
throw new ArgumentException("API token is too short.", nameof(TestConfigurations.ApiToken));
if (!TestConfigurations.AllowedUserNamesArray.Any())
throw new ArgumentException("Allowed user names is not provided", nameof(TestConfigurations.AllowedUserNames));
}
}
}
| mit | C# |
76153fc93cf3580cebd4d9a6dbc9ae32681e4958 | Add [Serializable] attribute | dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute | Source/NSubstitute/Exceptions/NullSubstituteReferenceException.cs | Source/NSubstitute/Exceptions/NullSubstituteReferenceException.cs | using System;
using System.Runtime.Serialization;
namespace NSubstitute.Exceptions
{
[Serializable]
public class NullSubstituteReferenceException : NotASubstituteException
{
public NullSubstituteReferenceException() { }
protected NullSubstituteReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
| using System.Runtime.Serialization;
namespace NSubstitute.Exceptions
{
[Serializable]
public class NullSubstituteReferenceException : NotASubstituteException
{
public NullSubstituteReferenceException() { }
protected NullSubstituteReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
| bsd-3-clause | C# |
f205a86d182af16d5eec1f7703bb5150e92c913e | Duplicate Property | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts/Configuration/EmployerAccountsConfiguration.cs | src/SFA.DAS.EmployerAccounts/Configuration/EmployerAccountsConfiguration.cs | using SFA.DAS.Authentication;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.Hmrc.Configuration;
using SFA.DAS.Messaging.AzureServiceBus.StructureMap;
namespace SFA.DAS.EmployerAccounts.Configuration
{
public class EmployerAccountsConfiguration : ITopicMessagePublisherConfiguration
{
public string AllowedHashstringCharacters { get; set; }
public string CdnBaseUrl { get; set; }
public string DashboardUrl { get; set; }
public string DatabaseConnectionString { get; set; }
public string EmployerAccountsBaseUrl { get; set; }
public string EmployerCommitmentsBaseUrl { get; set; }
public string EmployerFinanceBaseUrl { get; set; }
public string EmployerPortalBaseUrl { get; set; }
public string EmployerProjectionsBaseUrl { get; set; }
public string EmployerRecruitBaseUrl { get; set; }
public string ReservationsBaseUrl { get; set; }
public string EmployerFavouritesBaseUrl { get; set; }
public string ProviderRelationshipsBaseUrl { get; set; }
public EventsApiClientConfiguration EventsApi { get; set; }
public string Hashstring { get; set; }
public HmrcConfiguration Hmrc { get; set; }
public PensionRegulatorConfiguration PensionRegulatorApi { get; set; }
public ProviderRegistrationsConfiguration ProviderRegistrationsApi { get; set; }
public IdentityServerConfiguration Identity { get; set; }
public string LegacyServiceBusConnectionString { get; set; }
public string MessageServiceBusConnectionString => LegacyServiceBusConnectionString;
public string NServiceBusLicense { get; set; }
public PostcodeAnywhereConfiguration PostcodeAnywhere { get; set; }
public string PublicAllowedHashstringCharacters { get; set; }
public string PublicAllowedAccountLegalEntityHashstringCharacters { get; set; }
public string PublicAllowedAccountLegalEntityHashstringSalt { get; set; }
public string PublicHashstring { get; set; }
public string ServiceBusConnectionString { get; set; }
public string RedisConnectionString { get; set; }
public bool CanSkipRegistrationSteps { get; set; }
public AccountApiConfiguration AccountApi { get; set; }
public UserAornPayeLockConfiguration UserAornPayeLock { get; set; }
public string ZenDeskHelpCentreUrl { get; set; }
public string ReportTrainingProviderEmailAddress { get; set; }
}
} | using SFA.DAS.Authentication;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.Hmrc.Configuration;
using SFA.DAS.Messaging.AzureServiceBus.StructureMap;
namespace SFA.DAS.EmployerAccounts.Configuration
{
public class EmployerAccountsConfiguration : ITopicMessagePublisherConfiguration
{
public string AllowedHashstringCharacters { get; set; }
public string CdnBaseUrl { get; set; }
public string DashboardUrl { get; set; }
public string DatabaseConnectionString { get; set; }
public string EmployerAccountsBaseUrl { get; set; }
public string EmployerCommitmentsBaseUrl { get; set; }
public string EmployerFinanceBaseUrl { get; set; }
public string EmployerPortalBaseUrl { get; set; }
public string EmployerProjectionsBaseUrl { get; set; }
public string EmployerRecruitBaseUrl { get; set; }
public string ReservationsBaseUrl { get; set; }
public string EmployerFavouritesBaseUrl { get; set; }
public string ProviderRelationshipsBaseUrl { get; set; }
public EventsApiClientConfiguration EventsApi { get; set; }
public string Hashstring { get; set; }
public HmrcConfiguration Hmrc { get; set; }
public PensionRegulatorConfiguration PensionRegulatorApi { get; set; }
public ProviderRegistrationsConfiguration ProviderRegistrationsApi { get; set; }
public string ReportTrainingProviderEmailAddress { get; set; }
public IdentityServerConfiguration Identity { get; set; }
public string LegacyServiceBusConnectionString { get; set; }
public string MessageServiceBusConnectionString => LegacyServiceBusConnectionString;
public string NServiceBusLicense { get; set; }
public PostcodeAnywhereConfiguration PostcodeAnywhere { get; set; }
public string PublicAllowedHashstringCharacters { get; set; }
public string PublicAllowedAccountLegalEntityHashstringCharacters { get; set; }
public string PublicAllowedAccountLegalEntityHashstringSalt { get; set; }
public string PublicHashstring { get; set; }
public string ServiceBusConnectionString { get; set; }
public string RedisConnectionString { get; set; }
public bool CanSkipRegistrationSteps { get; set; }
public AccountApiConfiguration AccountApi { get; set; }
public UserAornPayeLockConfiguration UserAornPayeLock { get; set; }
public string ZenDeskHelpCentreUrl { get; set; }
public string ReportTrainingProviderEmailAddress { get; set; }
}
} | mit | C# |
e13119ec9b26a946ad1a864de74c795e36da4f10 | bump version | alecgorge/adzerk-dot-net | Adzerk.Api/Properties/AssemblyInfo.cs | Adzerk.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("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// 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.0.0.16")]
[assembly: AssemblyFileVersion("0.0.0.16")]
| 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("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// 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.0.0.15")]
[assembly: AssemblyFileVersion("0.0.0.15")]
| mit | C# |
4d854ee10073b7f91985c35298f1c81a580543f4 | Add Beta property on FleaHeader event | EDDiscovery/EDDiscovery,andreaspada/EDDiscovery,klightspeed/EDDiscovery,EDDiscovery/EDDiscovery,EDDiscovery/EDDiscovery,andreaspada/EDDiscovery,klightspeed/EDDiscovery,klightspeed/EDDiscovery | EDDiscovery/EliteDangerous/JournalEvents/JournalFileHeader.cs | EDDiscovery/EliteDangerous/JournalEvents/JournalFileHeader.cs | using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
public class JournalFileHeader : JournalEntry
{
public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader)
{
GameVersion = Tools.GetStringDef(evt["gameversion"]);
Build = Tools.GetStringDef(evt["build"]);
Language = Tools.GetStringDef(evt["language"]);
}
public string GameVersion { get; set; }
public string Build { get; set; }
public string Language { get; set; }
public bool Beta
{
get
{
if (GameVersion.Contains("Beta"))
return true;
if (GameVersion.Equals("2.2") && Build.Contains("r121645/r0"))
return true;
return false;
}
}
}
}
| using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
public class JournalFileHeader : JournalEntry
{
public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader)
{
GameVersion = Tools.GetStringDef(evt["gameversion"]);
Build = Tools.GetStringDef(evt["build"]);
Language = Tools.GetStringDef(evt["language"]);
}
public string GameVersion { get; set; }
public string Build { get; set; }
public string Language { get; set; }
}
}
| apache-2.0 | C# |
2854b9e8ad075e99f9915493ed99ba078bde5302 | Use ReactiveUI Events for Click Handler | ApplETS/ETSMobile-WindowsPlatforms,ApplETS/ETSMobile-WindowsPlatforms | Ets.Mobile/Ets.Mobile.Shared/Views/Pages/Account/LoginPage.cs | Ets.Mobile/Ets.Mobile.Shared/Views/Pages/Account/LoginPage.cs | using Ets.Mobile.ViewModel.Pages.Account;
using ReactiveUI;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
namespace Ets.Mobile.Pages.Account
{
public partial class LoginPage : IViewFor<LoginViewModel>
{
#region IViewFor<T>
public LoginViewModel ViewModel
{
get { return (LoginViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null));
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (LoginViewModel)value; }
}
#endregion
public LoginPage()
{
InitializeComponent();
// When ViewModel is set
this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Subscribe(x =>
{
Login.Events().Click.Subscribe(arg => ErrorMessage.Visibility = Visibility.Collapsed);
});
// Error Handling
UserError.RegisterHandler(ue =>
{
ErrorMessage.Text = ue.ErrorMessage;
ErrorMessage.Visibility = Visibility.Visible;
return Observable.Return(RecoveryOptionResult.CancelOperation);
});
PartialInitialize();
}
partial void PartialInitialize();
}
} | using Ets.Mobile.ViewModel.Pages.Account;
using ReactiveUI;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
namespace Ets.Mobile.Pages.Account
{
public partial class LoginPage : IViewFor<LoginViewModel>
{
#region IViewFor<T>
public LoginViewModel ViewModel
{
get { return (LoginViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null));
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (LoginViewModel)value; }
}
#endregion
public LoginPage()
{
InitializeComponent();
// When ViewModel is set
this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Subscribe(x =>
{
#if DEBUG
ViewModel.UserName = "";
ViewModel.Password = "";
#endif
Login.Click += (sender, arg) => { ErrorMessage.Visibility = Visibility.Collapsed; };
});
// Error Handling
UserError.RegisterHandler(ue =>
{
ErrorMessage.Text = ue.ErrorMessage;
ErrorMessage.Visibility = Visibility.Visible;
return Observable.Return(RecoveryOptionResult.CancelOperation);
});
this.BindCommand(ViewModel, x => x.Login, x => x.Login);
PartialInitialize();
}
partial void PartialInitialize();
}
} | apache-2.0 | C# |
877136c0f4d3a7c976099fdf77b4089a03264c67 | Fix description of DB2400Driver. | lnu/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core | src/NHibernate/Driver/DB2400Driver.cs | src/NHibernate/Driver/DB2400Driver.cs | using System;
namespace NHibernate.Driver
{
/// <summary>
/// A NHibernate Driver for using the IBM.Data.DB2.iSeries DataProvider.
/// </summary>
public class DB2400Driver : ReflectionBasedDriver
{
/// <summary>
/// Initializes a new instance of the <see cref="DB2400Driver"/> class.
/// </summary>
/// <exception cref="HibernateException">
/// Thrown when the <c>IBM.Data.DB2.iSeries</c> assembly can not be loaded.
/// </exception>
public DB2400Driver() : base(
"IBM.Data.DB2.iSeries",
"IBM.Data.DB2.iSeries.iDB2Connection",
"IBM.Data.DB2.iSeries.iDB2Command")
{
}
public override bool UseNamedPrefixInSql
{
get { return false; }
}
public override bool UseNamedPrefixInParameter
{
get { return false; }
}
public override string NamedPrefix
{
get { return String.Empty; }
}
public override bool SupportsMultipleOpenReaders
{
get { return false; }
}
}
}
| using System;
namespace NHibernate.Driver
{
/// <summary>
/// A NHibernate Driver for using the IBM.Data.DB2.iSeries DataProvider.
/// </summary>
public class DB2400Driver : ReflectionBasedDriver
{
/// <summary>
/// Initializes a new instance of the <see cref="DB2Driver"/> class.
/// </summary>
/// <exception cref="HibernateException">
/// Thrown when the <c>IBM.Data.DB2.iSeries</c> assembly can not be loaded.
/// </exception>
public DB2400Driver() : base(
"IBM.Data.DB2.iSeries",
"IBM.Data.DB2.iSeries.iDB2Connection",
"IBM.Data.DB2.iSeries.iDB2Command")
{
}
public override bool UseNamedPrefixInSql
{
get { return false; }
}
public override bool UseNamedPrefixInParameter
{
get { return false; }
}
public override string NamedPrefix
{
get { return String.Empty; }
}
public override bool SupportsMultipleOpenReaders
{
get { return false; }
}
}
} | lgpl-2.1 | C# |
d5af3177ac0a82410dac85f5ffd25cd250ee6a74 | Fix for EFCore using the same InMemoryDatabase Instance when running tests. | timstarbuck/allReady,GProulx/allReady,binaryjanitor/allReady,jonatwabash/allReady,HamidMosalla/allReady,colhountech/allReady,HamidMosalla/allReady,HTBox/allReady,gitChuckD/allReady,gitChuckD/allReady,forestcheng/allReady,pranap/allReady,chinwobble/allReady,VishalMadhvani/allReady,mheggeseth/allReady,mheggeseth/allReady,GProulx/allReady,MisterJames/allReady,gftrader/allReady,colhountech/allReady,stevejgordon/allReady,c0g1t8/allReady,colhountech/allReady,VishalMadhvani/allReady,timstarbuck/allReady,arst/allReady,forestcheng/allReady,MisterJames/allReady,jonatwabash/allReady,enderdickerson/allReady,forestcheng/allReady,shanecharles/allReady,mgmccarthy/allReady,arst/allReady,JowenMei/allReady,BillWagner/allReady,forestcheng/allReady,anobleperson/allReady,binaryjanitor/allReady,GProulx/allReady,GProulx/allReady,dpaquette/allReady,bcbeatty/allReady,stevejgordon/allReady,HamidMosalla/allReady,dpaquette/allReady,bcbeatty/allReady,mipre100/allReady,gftrader/allReady,pranap/allReady,enderdickerson/allReady,anobleperson/allReady,anobleperson/allReady,shanecharles/allReady,gitChuckD/allReady,timstarbuck/allReady,mheggeseth/allReady,c0g1t8/allReady,chinwobble/allReady,dpaquette/allReady,BillWagner/allReady,VishalMadhvani/allReady,BillWagner/allReady,VishalMadhvani/allReady,jonatwabash/allReady,colhountech/allReady,stevejgordon/allReady,JowenMei/allReady,BillWagner/allReady,binaryjanitor/allReady,binaryjanitor/allReady,MisterJames/allReady,c0g1t8/allReady,pranap/allReady,mgmccarthy/allReady,bcbeatty/allReady,bcbeatty/allReady,mgmccarthy/allReady,gftrader/allReady,arst/allReady,mipre100/allReady,HTBox/allReady,shanecharles/allReady,timstarbuck/allReady,gftrader/allReady,enderdickerson/allReady,mipre100/allReady,pranap/allReady,c0g1t8/allReady,HamidMosalla/allReady,chinwobble/allReady,HTBox/allReady,JowenMei/allReady,jonatwabash/allReady,anobleperson/allReady,chinwobble/allReady,arst/allReady,stevejgordon/allReady,MisterJames/allReady,mipre100/allReady,mgmccarthy/allReady,enderdickerson/allReady,HTBox/allReady,shanecharles/allReady,JowenMei/allReady,dpaquette/allReady,gitChuckD/allReady,mheggeseth/allReady | AllReadyApp/Web-App/AllReady.UnitTest/TestBase.cs | AllReadyApp/Web-App/AllReady.UnitTest/TestBase.cs | using AllReady.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting.Internal;
namespace AllReady.UnitTest
{
/// <summary>
/// Inherit from this type to implement tests that
/// have access to a service provider, empty in-memory
/// database, and basic configuration.
/// </summary>
public abstract class TestBase
{
protected IServiceProvider ServiceProvider { get; private set; }
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
}
}
| using AllReady.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting.Internal;
namespace AllReady.UnitTest
{
/// <summary>
/// Inherit from this type to implement tests that
/// have access to a service provider, empty in-memory
/// database, and basic configuration.
/// </summary>
public abstract class TestBase
{
protected IServiceProvider ServiceProvider { get; private set; }
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services.AddEntityFramework()
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase());
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
}
}
| mit | C# |
d27975bab504b90ebc9e8e4b546cb8e8da7e35ac | fix compiling | MehdyKarimpour/extensions,signumsoftware/framework,MehdyKarimpour/extensions,AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/framework,signumsoftware/extensions,AlejandroCano/extensions | Signum.React.Extensions/Rest/RestLogController.cs | Signum.React.Extensions/Rest/RestLogController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Signum.Engine;
using Signum.Entities;
using Signum.Entities.Rest;
using Signum.Utilities;
namespace Signum.React.Rest
{
public class RestLogController : ApiController
{
[Route("api/restLog/{id}"), HttpGet]
public async Task<RestDiffResult> GetRestDiffLog(string id)
{
var oldRequest = Database.Retrieve<RestLogEntity>(PrimaryKey.Parse(id, typeof(RestLogEntity)));
var result = new RestDiffResult {Current = oldRequest.ResponseBody};
//create the new Request
var restClient = new HttpClient();
restClient.BaseAddress = new Uri(oldRequest.Url);
if (!string.IsNullOrWhiteSpace(oldRequest.RequestBody))
{
var newRequest = restClient.PostAsJsonAsync("", oldRequest.RequestBody);
result.Current = await newRequest.Result.Content.ReadAsStringAsync();
}
else
{
result.Current = restClient.GetStringAsync(oldRequest.Url).Result;
}
return result;
}
}
public class RestDiffResult
{
public string Previous { get; set; }
public string Current { get; set; }
public List<StringDistance.DiffPair<List<StringDistance.DiffPair<string>>>> diff { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Signum.Engine;
using Signum.Entities;
using Signum.Entities.Rest;
using Signum.Utilities;
namespace Signum.React.Rest
{
public class RestLogController : ApiController
{
[Route("api/restLog/{id}"), HttpGet]
public async Task<RestDiffResult> GetRestDiffLog(string id)
{
var oldRequest = Database.Retrieve<RestLogEntity>(PrimaryKey.Parse(id, typeof(RestLogEntity)));
var result = new RestDiffResult {Current = oldRequest.ResponseBody};
//create the new Request
var restClient = new HttpClient();
restClient.BaseAddress = new Uri(oldRequest.Url);
if (!string.IsNullOrWhiteSpace(oldRequest.RequestBody))
{
var newRequest = restClient.PostAsJsonAsync("", oldRequest.RequestBody);
result.Current = await newRequest.Result.Content.ReadAsStringAsync();
}
else
{
result.Current = restClient.GetStringAsync(oldRequest.Url).Result
}
return result;
}
}
public class RestDiffResult
{
public string Previous { get; set; }
public string Current { get; set; }
public List<StringDistance.DiffPair<List<StringDistance.DiffPair<string>>>> diff { get; set; }
}
} | mit | C# |
11d8e12ac75ef6f1079198e192f354d492c40fd2 | add job project test object | mzrimsek/resume-site-api | Test.Integration/TestHelpers/TestObjectCreator.cs | Test.Integration/TestHelpers/TestObjectCreator.cs | using Web.Models.JobModels;
using Web.Models.JobProjectModels;
using Web.Models.SchoolModels;
namespace Test.Integration.TestHelpers
{
public static class TestObjectCreator
{
public static AddUpdateJobViewModel GetAddUpdateJobViewModel(string name)
{
return new AddUpdateJobViewModel()
{
Name = name,
City = "San Francisco",
State = "CA",
Title = "Developer",
StartDate = "1/1/2017",
EndDate = "7/1/2017"
};
}
public static AddUpdateJobViewModel GetAddUpdateJobViewModel()
{
return GetAddUpdateJobViewModel("Some Company");
}
public static AddUpdateSchoolViewModel GetAddUpdateSchoolViewModel(string name)
{
return new AddUpdateSchoolViewModel()
{
Name = name,
City = "Kent",
State = "OH",
Major = "Computer Science",
Degree = "B.S.",
StartDate = "9/1/2015",
EndDate = "5/13/2017"
};
}
public static AddUpdateSchoolViewModel GetAddUpdateSchoolViewModel()
{
return GetAddUpdateSchoolViewModel("Kent State University");
}
public static AddUpdateJobProjectViewModel GetAddUpdateJobProjectViewModel(int jobId, string name)
{
return new AddUpdateJobProjectViewModel()
{
JobId = jobId,
Name = name,
Description = "Some project description"
};
}
public static AddUpdateJobProjectViewModel GetAddUpdateJobProjectViewModel(int jobId)
{
return GetAddUpdateJobProjectViewModel(jobId, "Some project name");
}
}
} | using Web.Models.JobModels;
using Web.Models.SchoolModels;
namespace Test.Integration.TestHelpers
{
public static class TestObjectCreator
{
public static AddUpdateJobViewModel GetAddUpdateJobViewModel(string name)
{
return new AddUpdateJobViewModel()
{
Name = name,
City = "San Francisco",
State = "CA",
Title = "Developer",
StartDate = "1/1/2017",
EndDate = "7/1/2017"
};
}
public static AddUpdateJobViewModel GetAddUpdateJobViewModel()
{
return GetAddUpdateJobViewModel("Some Company");
}
public static AddUpdateSchoolViewModel GetAddUpdateSchoolViewModel(string name)
{
return new AddUpdateSchoolViewModel()
{
Name = name,
City = "Kent",
State = "OH",
Major = "Computer Science",
Degree = "B.S.",
StartDate = "9/1/2015",
EndDate = "5/13/2017"
};
}
public static AddUpdateSchoolViewModel GetAddUpdateSchoolViewModel()
{
return GetAddUpdateSchoolViewModel("Kent State University");
}
}
} | mit | C# |
10e1701ef0457c09d918d63c5c053bf60546cb66 | Make default fallback path factory static | khellang/Middleware,khellang/Middleware | src/SpaFallback/SpaFallbackOptions.cs | src/SpaFallback/SpaFallbackOptions.cs | using System;
using Microsoft.AspNetCore.Http;
namespace Hellang.Middleware.SpaFallback
{
public class SpaFallbackOptions
{
private static readonly Func<HttpContext, PathString> DefaultFallbackPathFactory = _ => "/index.html";
public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = DefaultFallbackPathFactory;
public bool AllowFileExtensions { get; set; } = false;
public bool ThrowIfFallbackFails { get; set; } = true;
}
}
| using System;
using Microsoft.AspNetCore.Http;
namespace Hellang.Middleware.SpaFallback
{
public class SpaFallbackOptions
{
public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = _ => "/index.html";
public bool AllowFileExtensions { get; set; } = false;
public bool ThrowIfFallbackFails { get; set; } = true;
}
}
| mit | C# |
11222cdf13643e67566447487acce01aa804056e | Bump version to 1.3.0 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
private const string GitHubForUnityVersion = "1.3.0";
internal const string VersionForAssembly = GitHubForUnityVersion;
// If this is an alpha, beta or other pre-release, mark it as such as shown below
internal const string Version = GitHubForUnityVersion; // GitHubForUnityVersion + "-beta1"
}
}
| #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
private const string GitHubForUnityVersion = "1.2.2";
internal const string VersionForAssembly = GitHubForUnityVersion;
// If this is an alpha, beta or other pre-release, mark it as such as shown below
internal const string Version = GitHubForUnityVersion; // GitHubForUnityVersion + "-beta1"
}
}
| mit | C# |
6f49bd8a3506d2091523b1585a485e392b327123 | Add comment | whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016,virtuoushub/game-off-2016,virtuoushub/game-off-2016,whoa-algebraic/game-off-2016 | Assets/Scripts/PlayerActionControls.cs | Assets/Scripts/PlayerActionControls.cs | using UnityEngine;
public class PlayerActionControls : MonoBehaviour {
private GameObject[] limbs;
void Start() {
GameObject bearFrontLimbPrefab = Managers.LimbManager.LimbPrefabs[0];
GameObject bearBackLimbPrefab = Managers.LimbManager.LimbPrefabs[1];
limbs = new GameObject[4];
limbs[0] = Instantiate(bearFrontLimbPrefab);
limbs[1] = Instantiate(bearFrontLimbPrefab);
limbs[2] = Instantiate(bearBackLimbPrefab);
limbs[3] = Instantiate(bearBackLimbPrefab);
foreach(GameObject limb in limbs) {
ConfigureLimbInstance(limb);
}
}
void Update () {
// right trigger
if (Input.GetAxis("Action1") > 0 || Input.GetButtonDown("Action1 Alt")) {
Debug.Log("Action1 button pressed");
limbs[0].GetComponent<Limb>().Activate();
}
if (Input.GetAxis("Action2") > 0 || Input.GetButtonDown("Action2 Alt")) {
Debug.Log("Action2 button pressed");
limbs[1].GetComponent<Limb>().Activate();
}
if (Input.GetButtonDown("Action3")) {
Debug.Log("Action3 button pressed");
limbs[2].GetComponent<Limb>().Activate();
}
if (Input.GetButtonDown("Action4")) {
Debug.Log("Action4 button pressed");
limbs[3].GetComponent<Limb>().Activate();
}
}
private void ConfigureLimbInstance(GameObject limb) {
limb.transform.SetParent(this.transform);
limb.transform.localPosition = Vector3.zero;
limb.transform.localScale = Vector3.one;
}
}
| using UnityEngine;
public class PlayerActionControls : MonoBehaviour {
private GameObject[] limbs;
void Start() {
GameObject bearFrontLimbPrefab = Managers.LimbManager.LimbPrefabs[0];
GameObject bearBackLimbPrefab = Managers.LimbManager.LimbPrefabs[1];
limbs = new GameObject[4];
limbs[0] = Instantiate(bearFrontLimbPrefab);
limbs[1] = Instantiate(bearFrontLimbPrefab);
limbs[2] = Instantiate(bearBackLimbPrefab);
limbs[3] = Instantiate(bearBackLimbPrefab);
foreach(GameObject limb in limbs) {
ConfigureLimbInstance(limb);
}
}
void Update () {
if (Input.GetAxis("Action1") > 0 || Input.GetButtonDown("Action1 Alt")) {
Debug.Log("Action1 button pressed");
limbs[0].GetComponent<Limb>().Activate();
}
if (Input.GetAxis("Action2") > 0 || Input.GetButtonDown("Action2 Alt")) {
Debug.Log("Action2 button pressed");
limbs[1].GetComponent<Limb>().Activate();
}
if (Input.GetButtonDown("Action3")) {
Debug.Log("Action3 button pressed");
limbs[2].GetComponent<Limb>().Activate();
}
if (Input.GetButtonDown("Action4")) {
Debug.Log("Action4 button pressed");
limbs[3].GetComponent<Limb>().Activate();
}
}
private void ConfigureLimbInstance(GameObject limb) {
limb.transform.SetParent(this.transform);
limb.transform.localPosition = Vector3.zero;
limb.transform.localScale = Vector3.one;
}
}
| mit | C# |
64d191f29c087e367cf05e66187e6e15f8e1bf2e | Update BuildTool Deploy | WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework | Framework.BuildTool/Command/Deploy.cs | Framework.BuildTool/Command/Deploy.cs | using System.IO;
namespace Framework.BuildTool
{
public class CommandDeploy : Command
{
public CommandDeploy()
: base("deploy", "Deploy to Azure git")
{
this.AzureGitUrl = ArgumentAdd("azureGitUrl", "Azure Git Url");
}
public readonly Argument AzureGitUrl;
public override void Run()
{
string azureGitUrl = AzureGitUrl.Value;
string folderPublish = UtilFramework.FolderName + "Server/bin/Debug/netcoreapp2.0/publish/";
//
UtilBuildTool.DirectoryDelete(folderPublish);
UtilFramework.Assert(!Directory.Exists(folderPublish), "Delete folder failed!");
UtilBuildTool.DotNetPublish(UtilFramework.FolderName + "Server/");
UtilFramework.Assert(Directory.Exists(folderPublish), "Publish failed!");
UtilBuildTool.Start(folderPublish, "git", "init");
UtilBuildTool.Start(folderPublish, "git", "remote add azure " + azureGitUrl);
UtilBuildTool.Start(folderPublish, "git", "fetch --all");
UtilBuildTool.Start(folderPublish, "git", "add .");
UtilBuildTool.Start(folderPublish, "git", "commit -m Deploy");
UtilBuildTool.Start(folderPublish, "git", "push azure master -f 2>&1 # do not write to stderr");
}
}
}
| using System.IO;
namespace Framework.BuildTool
{
public class CommandDeploy : Command
{
public CommandDeploy()
: base("deploy", "Deploy to Azure git")
{
this.AzureGitUrl = ArgumentAdd("azureGitUrl", "Azure Git Url");
}
public readonly Argument AzureGitUrl;
public override void Run()
{
string azureGitUrl = AzureGitUrl.Value;
string folderPublish = UtilFramework.FolderName + "Server/bin/Debug/netcoreapp2.0/publish/";
//
UtilBuildTool.DirectoryDelete(folderPublish);
UtilFramework.Assert(!Directory.Exists(folderPublish), "Delete folder failed!");
UtilBuildTool.DotNetPublish(UtilFramework.FolderName + "Server/");
UtilFramework.Assert(Directory.Exists(folderPublish), "Publish failed!");
UtilBuildTool.Start(folderPublish, "git", "init");
UtilBuildTool.Start(folderPublish, "git", "remote add azure " + azureGitUrl);
UtilBuildTool.Start(folderPublish, "git", "fetch --all");
UtilBuildTool.Start(folderPublish, "git", "add .");
UtilBuildTool.Start(folderPublish, "git", "commit -m Deploy");
UtilBuildTool.Start(folderPublish, "git", "push azure master -f");
}
}
}
| mit | C# |
4cb2ff87b980506afa7e4dab269029cacd8a505e | Test now restores Environment properties back to their original values. | ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core | src/NHibernate.Test/CfgTest/ConfigurationFixture.cs | src/NHibernate.Test/CfgTest/ConfigurationFixture.cs | using System;
using NHibernate.Cfg;
using NUnit.Framework;
namespace NHibernate.Test.CfgTest
{
/// <summary>
/// Summary description for ConfigurationFixture.
/// </summary>
[TestFixture]
public class ConfigurationFixture
{
[SetUp]
public void SetUp()
{
System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true);
}
[TearDown]
public void TearDown()
{
System.IO.File.Delete("hibernate.cfg.xml");
}
/// <summary>
/// Verify that NHibernate can read the configuration from a hibernate.cfg.xml
/// file and that the values override what is in the app.config.
/// </summary>
[Test]
public void ReadCfgXmlFromDefaultFile()
{
string origQuerySubst = Cfg.Environment.Properties[Cfg.Environment.QuerySubstitutions] as string;
string origConnString = Cfg.Environment.Properties[Cfg.Environment.ConnectionString] as string;
Configuration cfg = new Configuration();
cfg.Configure();
Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]);
Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]);
cfg.Properties[Cfg.Environment.QuerySubstitutions] = origQuerySubst;
cfg.Properties[Cfg.Environment.ConnectionString] = origConnString;
}
}
}
| using System;
using NHibernate.Cfg;
using NUnit.Framework;
namespace NHibernate.Test.CfgTest
{
/// <summary>
/// Summary description for ConfigurationFixture.
/// </summary>
[TestFixture]
public class ConfigurationFixture
{
[SetUp]
public void SetUp()
{
System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true);
}
[TearDown]
public void TearDown()
{
System.IO.File.Delete("hibernate.cfg.xml");
}
/// <summary>
/// Verify that NHibernate can read the configuration from a hibernate.cfg.xml
/// file and that the values override what is in the app.config.
/// </summary>
[Test]
public void ReadCfgXmlFromDefaultFile()
{
Configuration cfg = new Configuration();
cfg.Configure();
Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]);
Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]);
}
}
}
| lgpl-2.1 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.