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 |
|---|---|---|---|---|---|---|---|---|
cd3fe6ad3bfcde360a2b510f68a332671e2e91bc
|
Remove nameof method usage in Identifiers.
|
affecto/dotnet-Testing.SpecFlow
|
Testing.SpecFlow/Identifiers.cs
|
Testing.SpecFlow/Identifiers.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Affecto.Testing.SpecFlow
{
public class Identifiers
{
private readonly IDictionary<Guid, string> identifiedTexts;
public Identifiers()
{
identifiedTexts = new Dictionary<Guid, string>();
}
public void Generate(string textWithId)
{
if (string.IsNullOrWhiteSpace(textWithId))
{
throw new ArgumentException("Empty text cannot be added.", "textWithId");
}
if (IsTextAdded(textWithId))
{
throw new ArgumentException(string.Format("Text '{0}' already added.", textWithId), "textWithId");
}
identifiedTexts.Add(Guid.NewGuid(), textWithId);
}
public Guid Get(string textWithId)
{
if (!IsTextAdded(textWithId))
{
throw new ArgumentException(string.Format("Text '{0}' not added.", textWithId), "textWithId");
}
return identifiedTexts.Single(text => text.Value.Equals(textWithId)).Key;
}
private bool IsTextAdded(string textWithId)
{
return identifiedTexts.Any(text => text.Value.Equals(textWithId));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Affecto.Testing.SpecFlow
{
public class Identifiers
{
private readonly IDictionary<Guid, string> identifiedTexts;
public Identifiers()
{
identifiedTexts = new Dictionary<Guid, string>();
}
public void Generate(string textWithId)
{
if (string.IsNullOrWhiteSpace(textWithId))
{
throw new ArgumentException("Empty text cannot be added.", nameof(textWithId));
}
if (IsTextAdded(textWithId))
{
throw new ArgumentException(string.Format("Text '{0}' already added.", textWithId), nameof(textWithId));
}
identifiedTexts.Add(Guid.NewGuid(), textWithId);
}
public Guid Get(string textWithId)
{
if (!IsTextAdded(textWithId))
{
throw new ArgumentException(string.Format("Text '{0}' not added.", textWithId), nameof(textWithId));
}
return identifiedTexts.Single(text => text.Value.Equals(textWithId)).Key;
}
private bool IsTextAdded(string textWithId)
{
return identifiedTexts.Any(text => text.Value.Equals(textWithId));
}
}
}
|
mit
|
C#
|
3209624048e010515b83d1fa2bf8adaf174614d0
|
Add one more mode for dump checkedout files - by checkout date
|
azarkevich/VssSvnConverter
|
VssSvnConverter/LinksBuilder.cs
|
VssSvnConverter/LinksBuilder.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using SourceSafeTypeLib;
using vcslib;
namespace VssSvnConverter
{
class LinksBuilder
{
public const string DataFileName = "3-state-links.txt";
public const string DataFileUiName = "3-state-links-ui.txt";
public const string DataFileCoName = "3-state-checkouts.txt";
public const string DataFileCoByDateName = "3-state-checkouts-by-date.txt";
public void Build(Options opts, IList<Tuple<string, int>> files)
{
var coDict = new Dictionary<DateTime, List<Tuple<string, string>>>();
var xrefsCo = new XRefMap();
var xrefs = new XRefMap();
foreach (var file in files.Select(t => t.Item1))
{
Console.WriteLine(file);
var item = opts.DB.VSSItem[file];
foreach (IVSSItem vssLink in item.Links)
{
if (!String.Equals(item.Spec, vssLink.Spec, StringComparison.OrdinalIgnoreCase) && !vssLink.Deleted)
xrefs.AddRef(item.Spec, vssLink.Spec);
foreach (IVSSCheckout vssCheckout in vssLink.Checkouts)
{
xrefsCo.AddRef(item.Spec, vssCheckout.Username + " at " + vssCheckout.Date);
var coDate = vssCheckout.Date.Date;
List<Tuple<string, string>> list;
if(!coDict.TryGetValue(coDate, out list))
{
list = new List<Tuple<string, string>>();
coDict[coDate] = list;
}
list.Add(Tuple.Create(vssCheckout.Username, item.Spec));
}
}
}
xrefs.Save(DataFileName);
xrefs.Save(DataFileUiName, true);
xrefsCo.Save(DataFileCoName, true);
// save co dict by dates
using (var tw = File.CreateText(DataFileCoByDateName))
{
foreach (var kvp in coDict.OrderByDescending(kvp => kvp.Key))
{
tw.WriteLine("{0}", kvp.Key);
foreach (var tuple in kvp.Value)
{
tw.WriteLine("{0} at {1}", tuple.Item1, tuple.Item2);
}
tw.WriteLine();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SourceSafeTypeLib;
using vcslib;
namespace VssSvnConverter
{
class LinksBuilder
{
public const string DataFileName = "3-state-links.txt";
public const string DataFileUiName = "3-state-links-ui.txt";
public const string DataFileCoName = "3-state-checkouts.txt";
public void Build(Options opts, IList<Tuple<string, int>> files)
{
var xrefsCo = new XRefMap();
var xrefs = new XRefMap();
foreach (var file in files.Select(t => t.Item1))
{
Console.WriteLine(file);
var item = opts.DB.VSSItem[file];
foreach (IVSSItem vssLink in item.Links)
{
if (!String.Equals(item.Spec, vssLink.Spec, StringComparison.OrdinalIgnoreCase) && !vssLink.Deleted)
xrefs.AddRef(item.Spec, vssLink.Spec);
foreach (IVSSCheckout vssCheckout in vssLink.Checkouts)
{
xrefsCo.AddRef(item.Spec, vssCheckout.Username + " at " + vssCheckout.Date);
}
}
}
xrefs.Save(DataFileName);
xrefs.Save(DataFileUiName, true);
xrefsCo.Save(DataFileCoName, true);
}
}
}
|
mit
|
C#
|
d294b431fa9a8ca5f2d9a7260ecec546e22eb586
|
Enable Inspector property code vision by default
|
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
|
resharper/resharper-unity/src/Settings/UnitySettings.cs
|
resharper/resharper-unity/src/Settings/UnitySettings.cs
|
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Resources.Settings;
namespace JetBrains.ReSharper.Plugins.Unity.Settings
{
[SettingsKey(typeof(CodeEditingSettings), "Unity plugin settings")]
public class UnitySettings
{
[SettingsEntry(true, "If this option is enabled, the Rider Unity editor plugin will be automatically installed and updated.")]
public bool InstallUnity3DRiderPlugin;
[SettingsEntry(true, "If this option is enabled, Rider will automatically notify the Unity editor to refresh assets.")]
public bool AllowAutomaticRefreshInUnity;
[SettingsEntry(true, "Enables syntax error highlighting, brace matching and more of ShaderLab files.")]
public bool EnableShaderLabParsing;
[SettingsEntry(true, "Enables completion based on words found in the current file.")]
public bool EnableShaderLabHippieCompletion;
[SettingsEntry(false, "Enables syntax error highlighting of CG blocks in ShaderLab files.")]
public bool EnableCgErrorHighlighting;
[SettingsEntry(GutterIconMode.CodeInsightDisabled, "Unity highlighter scheme for editor.")]
public GutterIconMode GutterIconMode;
// backward compability
[SettingsEntry(true, "Should yaml heuristic be applied?")]
public bool ShouldApplyYamlHugeFileHeuristic;
[SettingsEntry(true, "Enables syntax error highlighting, brace matching and more of YAML files for Unity")]
public bool IsYamlParsingEnabled;
// Analysis
[SettingsEntry(true, "Enables performance analysis in frequently called code")]
public bool EnablePerformanceCriticalCodeHighlighting;
// UX for performance critical analysis
[SettingsEntry(PerformanceHighlightingMode.CurrentMethod, "Highlighting mode for performance critical code")]
public PerformanceHighlightingMode PerformanceHighlightingMode;
[SettingsEntry(true, "Enables showing hot icon for frequently called code")]
public bool EnableIconsForPerformanceCriticalCode;
[SettingsEntry(true, "Show Inspector properties changes in editor")]
public bool EnableInspectorPropertiesEditor;
}
}
|
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Resources.Settings;
namespace JetBrains.ReSharper.Plugins.Unity.Settings
{
[SettingsKey(typeof(CodeEditingSettings), "Unity plugin settings")]
public class UnitySettings
{
[SettingsEntry(true, "If this option is enabled, the Rider Unity editor plugin will be automatically installed and updated.")]
public bool InstallUnity3DRiderPlugin;
[SettingsEntry(true, "If this option is enabled, Rider will automatically notify the Unity editor to refresh assets.")]
public bool AllowAutomaticRefreshInUnity;
[SettingsEntry(true, "Enables syntax error highlighting, brace matching and more of ShaderLab files.")]
public bool EnableShaderLabParsing;
[SettingsEntry(true, "Enables completion based on words found in the current file.")]
public bool EnableShaderLabHippieCompletion;
[SettingsEntry(false, "Enables syntax error highlighting of CG blocks in ShaderLab files.")]
public bool EnableCgErrorHighlighting;
[SettingsEntry(GutterIconMode.CodeInsightDisabled, "Unity highlighter scheme for editor.")]
public GutterIconMode GutterIconMode;
// backward compability
[SettingsEntry(true, "Should yaml heuristic be applied?")]
public bool ShouldApplyYamlHugeFileHeuristic;
[SettingsEntry(true, "Enables syntax error highlighting, brace matching and more of YAML files for Unity")]
public bool IsYamlParsingEnabled;
// Analysis
[SettingsEntry(true, "Enables performance analysis in frequently called code")]
public bool EnablePerformanceCriticalCodeHighlighting;
// UX for performance critical analysis
[SettingsEntry(PerformanceHighlightingMode.CurrentMethod, "Highlighting mode for performance critical code")]
public PerformanceHighlightingMode PerformanceHighlightingMode;
[SettingsEntry(true, "Enables showing hot icon for frequently called code")]
public bool EnableIconsForPerformanceCriticalCode;
[SettingsEntry(false, "Show Inspector properties changes in editor")]
public bool EnableInspectorPropertiesEditor;
}
}
|
apache-2.0
|
C#
|
20315077bff953fa40bb9a7fb21d4c094607dc50
|
Fix regression due to starting in Part view without printer selection
|
unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl
|
Tests/MatterControl.AutomationTests/OptionsTabTests.cs
|
Tests/MatterControl.AutomationTests/OptionsTabTests.cs
|
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg.UI;
using NUnit.Framework;
namespace MatterHackers.MatterControl.Tests.Automation
{
[TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain]
public class ShowTerminalButtonClickedOpensTerminal
{
[Test, Apartment(ApartmentState.STA)]
public async Task ClickingShowTerminalButtonOpensTerminal()
{
await MatterControlUtilities.RunTest((testRunner) =>
{
testRunner.AddAndSelectPrinter("Airwolf 3D", "HD");
Assert.IsFalse(testRunner.WaitForName("TerminalWidget", 0.5), "Terminal Window should not exist");
testRunner.ClickByName("Terminal Sidebar");
testRunner.Delay(1);
Assert.IsTrue(testRunner.WaitForName("TerminalWidget"), "Terminal Window should exists after Show Terminal button is clicked");
return Task.CompletedTask;
});
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg.UI;
using NUnit.Framework;
namespace MatterHackers.MatterControl.Tests.Automation
{
[TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain]
public class ShowTerminalButtonClickedOpensTerminal
{
[Test, Apartment(ApartmentState.STA)]
public async Task ClickingShowTerminalButtonOpensTerminal()
{
await MatterControlUtilities.RunTest((testRunner) =>
{
testRunner.CloseSignInAndPrinterSelect();
Assert.IsFalse(testRunner.WaitForName("TerminalWidget", 0.5), "Terminal Window should not exist");
testRunner.ClickByName("Terminal Sidebar");
testRunner.Delay(1);
Assert.IsTrue(testRunner.WaitForName("TerminalWidget"), "Terminal Window should exists after Show Terminal button is clicked");
return Task.CompletedTask;
});
}
}
}
|
bsd-2-clause
|
C#
|
5b868368cd614260fd86176a2445c55ef0a77c34
|
Mark IViewFactory as deprecated
|
ramonesteban78/RockMvvmForms
|
RockMvvmForms/IViewFactory.cs
|
RockMvvmForms/IViewFactory.cs
|
using System;
using Xamarin.Forms;
namespace RockMvvmForms
{
[Obsolete("Use the static class ViewFactory. This interface is no longer available",true)]
public interface IViewFactory
{
void Register<TViewModel, TView>()
where TViewModel : class, IViewModel
where TView : Page;
Page Resolve<TViewModel>(TViewModel viewModel)
where TViewModel : class, IViewModel;
}
}
|
using System;
using Xamarin.Forms;
namespace RockMvvmForms
{
public interface IViewFactory
{
void Register<TViewModel, TView>()
where TViewModel : class, IViewModel
where TView : Page;
Page Resolve<TViewModel>(TViewModel viewModel)
where TViewModel : class, IViewModel;
}
}
|
mit
|
C#
|
38d9a1f0dd3db50e555b269b20b32fc9c48604c0
|
Fix bug where factory name hadn't been udpated
|
pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
|
src/Glimpse.Agent.Connection.Stream/Broker/WebSocketChannelSender.cs
|
src/Glimpse.Agent.Connection.Stream/Broker/WebSocketChannelSender.cs
|
using Glimpse.Agent.Connection.Stream.Connection;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public class WebSocketChannelSender : IChannelSender
{
private readonly IMessageConverter _messageConverter;
private readonly IStreamHubProxyFactory _streamHubProxyFactory;
private IStreamHubProxy _streamHubProxy;
public WebSocketChannelSender(IMessageConverter messageConverter, IStreamHubProxyFactory streamHubProxyFactory)
{
_messageConverter = messageConverter;
_streamHubProxyFactory = streamHubProxyFactory;
_streamHubProxyFactory.Register("WebSocketChannelReceiver", x => _streamHubProxy = x);
}
public async Task PublishMessage(IMessage message)
{
// TODO: Probably not the best place to put this
await _streamHubProxyFactory.Start();
var newMessage = _messageConverter.ConvertMessage(message);
await _streamHubProxy.Invoke("HandleMessage", newMessage);
}
}
}
|
using Glimpse.Agent.Connection.Stream.Connection;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public class WebSocketChannelSender : IChannelSender
{
private readonly IMessageConverter _messageConverter;
private readonly IStreamHubProxyFactory _streamHubProxyFactory;
private IStreamHubProxy _streamHubProxy;
public WebSocketChannelSender(IMessageConverter messageConverter, IStreamHubProxyFactory streamHubProxyFactory)
{
_messageConverter = messageConverter;
_streamHubProxyFactory = streamHubProxyFactory;
_streamHubProxyFactory.Register("RemoteStreamMessagePublisherResource", x => _streamHubProxy = x);
}
public async Task PublishMessage(IMessage message)
{
// TODO: Probably not the best place to put this
await _streamHubProxyFactory.Start();
var newMessage = _messageConverter.ConvertMessage(message);
await _streamHubProxy.Invoke("HandleMessage", newMessage);
}
}
}
|
mit
|
C#
|
2c14310619eba5e09baf7878bc7dbefddd25b400
|
Change the 'Request' object in the Dispatch system to no longer alter the passed in message.
|
ariugwu/sharpbox,ariugwu/sharpbox,ariugwu/sharpbox,ariugwu/sharpbox
|
sharpbox.Dispatch/Model/Request.cs
|
sharpbox.Dispatch/Model/Request.cs
|
using System;
namespace sharpbox.Dispatch.Model
{
[Serializable]
public class Request : BasePackage
{
public Request()
{
CreatedDate = DateTime.Now;
}
public int RequestId { get; set; } // @SEE http://stackoverflow.com/questions/11938044/what-are-the-best-practices-for-using-a-guid-as-a-primary-key-specifically-rega
public Guid RequestUniqueKey { get; set; }
public string Message { get; set; }
public int CommandNameId { get; set; }
public CommandNames CommandName { get; set; }
public Delegate Action { get; set; }
public DateTime CreatedDate { get; set; }
public Guid? ApplicationId { get; set; }
public static Request Create<T>(CommandNames commandName, string message, T entity)
{
return new Request()
{
RequestUniqueKey = Guid.NewGuid(),
CommandName = commandName,
Message = message,
Entity = entity,
Type = entity != null? entity.GetType() : null,
CreatedDate = DateTime.Now
};
}
}
}
|
using System;
namespace sharpbox.Dispatch.Model
{
[Serializable]
public class Request : BasePackage
{
public Request()
{
CreatedDate = DateTime.Now;
}
public int RequestId { get; set; } // @SEE http://stackoverflow.com/questions/11938044/what-are-the-best-practices-for-using-a-guid-as-a-primary-key-specifically-rega
public Guid RequestUniqueKey { get; set; }
public string Message { get; set; }
public int CommandNameId { get; set; }
public CommandNames CommandName { get; set; }
public Delegate Action { get; set; }
public DateTime CreatedDate { get; set; }
public Guid? ApplicationId { get; set; }
public static Request Create<T>(CommandNames commandName, string message, T entity)
{
return new Request()
{
RequestUniqueKey = Guid.NewGuid(),
CommandName = commandName,
Message = String.Format("[Invoke Command: {0}] [Message: {1}]",commandName, message),
Entity = entity,
Type = entity != null? entity.GetType() : null,
CreatedDate = DateTime.Now
};
}
}
}
|
mit
|
C#
|
d9194a864a3011cdbd6f42f56cb0c834e2b6a0fd
|
Fix name of help file
|
gmartin7/myBloomFork,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork
|
src/BloomExe/HelpLauncher.cs
|
src/BloomExe/HelpLauncher.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Palaso.IO;
namespace Bloom
{
public class HelpLauncher
{
public static void Show(Control parent)
{
Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication("Bloom.chm"));
}
public static void Show(Control parent, string topic)
{
Show(parent, "Bloom.chm", topic);
}
public static void Show(Control parent, string helpFileName, string topic)
{
Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication(helpFileName), topic);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Palaso.IO;
namespace Bloom
{
public class HelpLauncher
{
public static void Show(Control parent)
{
Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication("Bloom.CHM"));
}
public static void Show(Control parent, string topic)
{
Show(parent, "Bloom.CHM", topic);
}
public static void Show(Control parent, string helpFileName, string topic)
{
Help.ShowHelp(parent, FileLocator.GetFileDistributedWithApplication(helpFileName), topic);
}
}
}
|
mit
|
C#
|
8444821ac3320b0685c506cda0567c648735d815
|
use tag to find target panels, instead of panel name
|
yasokada/unity-150905-dynamicDisplay
|
Assets/PanelDisplayControl.cs
|
Assets/PanelDisplayControl.cs
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.3 2015/09/06
* - use Tag for Panel to find target panels, instead of panel name
* v0.2 2015/09/06
* - add sample UI components in each panel
* v0.1 2015/09/05
* - show/hide panels
*/
public class PanelDisplayControl : MonoBehaviour {
public GameObject PageSelect;
public GameObject PanelGroup;
private Vector2[] orgSize;
void Start() {
orgSize = new Vector2[4];
int idx=0;
foreach (Transform child in PanelGroup.transform) {
orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width;
orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height;
bool isOn = getIsOn (idx + 1);
DisplayPanel (idx + 1, isOn);
idx++;
}
}
bool getIsOn(int idx_st1) {
Toggle selected = null;
string name;
foreach (Transform child in PageSelect.transform) {
name = child.gameObject.name;
if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"...
selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle;
break;
}
}
return selected.isOn;
}
void DisplayPanel(int idx_st1, bool doShow)
{
GameObject [] panels = GameObject.FindGameObjectsWithTag ("TagP" + idx_st1.ToString ());
if (panels == null) {
return;
}
foreach (GameObject panel in panels) {
RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform;
Vector2 size = rect.sizeDelta;
if (doShow) {
size.x = orgSize [idx_st1 - 1].x;
size.y = orgSize [idx_st1 - 1].y;
} else {
size.x = 0;
size.y = 0;
}
rect.sizeDelta = size;
}
}
public void ToggleValueChanged(int idx_st1) {
bool isOn = getIsOn (idx_st1);
DisplayPanel (idx_st1, isOn);
Debug.Log (isOn.ToString ());
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.2 2015/09/06
* - add sample UI components in each panel
* v0.1 2015/09/05
* - show/hide panels
*/
public class PanelDisplayControl : MonoBehaviour {
public GameObject PageSelect;
public GameObject PanelGroup;
private Vector2[] orgSize;
void Start() {
orgSize = new Vector2[4];
int idx=0;
foreach (Transform child in PanelGroup.transform) {
orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width;
orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height;
bool isOn = getIsOn (idx + 1);
DisplayPanel (idx + 1, isOn);
idx++;
}
}
bool getIsOn(int idx_st1) {
Toggle selected = null;
string name;
foreach (Transform child in PageSelect.transform) {
name = child.gameObject.name;
if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"...
selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle;
break;
}
}
return selected.isOn;
}
void DisplayPanel(int idx_st1, bool doShow)
{
GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ());
if (panel == null) {
return;
}
RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform;
Vector2 size = rect.sizeDelta;
if (doShow) {
size.x = orgSize[idx_st1 - 1].x;
size.y = orgSize[idx_st1 - 1].y;
} else {
size.x = 0;
size.y = 0;
}
rect.sizeDelta = size;
}
public void ToggleValueChanged(int idx_st1) {
bool isOn = getIsOn (idx_st1);
DisplayPanel (idx_st1, isOn);
Debug.Log (isOn.ToString ());
}
}
|
mit
|
C#
|
35cd6674f62453170861d6dab2f738fbb66932ba
|
Fix tiny droplet scale factor
|
smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu
|
osu.Game.Rulesets.Catch/Objects/Drawables/DrawableTinyDroplet.cs
|
osu.Game.Rulesets.Catch/Objects/Drawables/DrawableTinyDroplet.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.
namespace osu.Game.Rulesets.Catch.Objects.Drawables
{
public class DrawableTinyDroplet : DrawableDroplet
{
protected override float ScaleFactor => base.ScaleFactor / 2;
public DrawableTinyDroplet(TinyDroplet h)
: base(h)
{
}
}
}
|
// 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;
namespace osu.Game.Rulesets.Catch.Objects.Drawables
{
public class DrawableTinyDroplet : DrawableDroplet
{
public DrawableTinyDroplet(TinyDroplet h)
: base(h)
{
}
[BackgroundDependencyLoader]
private void load()
{
ScaleContainer.Scale /= 2;
}
}
}
|
mit
|
C#
|
b73651c6b6ffcef16981fe35e31a9c052414a2c5
|
support whitespace
|
BarryThePenguin/Squirrel.Windows,markwal/Squirrel.Windows,JonMartinTx/AS400Report,flagbug/Squirrel.Windows,1gurucoder/Squirrel.Windows,sickboy/Squirrel.Windows,sickboy/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,cguedel/Squirrel.Windows,flagbug/Squirrel.Windows,ChaseFlorell/Squirrel.Windows,vaginessa/Squirrel.Windows,aneeff/Squirrel.Windows,jochenvangasse/Squirrel.Windows,EdZava/Squirrel.Windows,1gurucoder/Squirrel.Windows,awseward/Squirrel.Windows,markuscarlen/Squirrel.Windows,Katieleeb84/Squirrel.Windows,awseward/Squirrel.Windows,markwal/Squirrel.Windows,cguedel/Squirrel.Windows,willdean/Squirrel.Windows,ChaseFlorell/Squirrel.Windows,jochenvangasse/Squirrel.Windows,JonMartinTx/AS400Report,Katieleeb84/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,ruisebastiao/Squirrel.Windows,hammerandchisel/Squirrel.Windows,yovannyr/Squirrel.Windows,flagbug/Squirrel.Windows,willdean/Squirrel.Windows,awseward/Squirrel.Windows,kenbailey/Squirrel.Windows,kenbailey/Squirrel.Windows,punker76/Squirrel.Windows,punker76/Squirrel.Windows,ChaseFlorell/Squirrel.Windows,Squirrel/Squirrel.Windows,hammerandchisel/Squirrel.Windows,bowencode/Squirrel.Windows,Suninus/Squirrel.Windows,aneeff/Squirrel.Windows,BarryThePenguin/Squirrel.Windows,jbeshir/Squirrel.Windows,jbeshir/Squirrel.Windows,ruisebastiao/Squirrel.Windows,Katieleeb84/Squirrel.Windows,hammerandchisel/Squirrel.Windows,josenbo/Squirrel.Windows,yovannyr/Squirrel.Windows,BloomBooks/Squirrel.Windows,BloomBooks/Squirrel.Windows,vaginessa/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,BloomBooks/Squirrel.Windows,Suninus/Squirrel.Windows,airtimemedia/Squirrel.Windows,Squirrel/Squirrel.Windows,josenbo/Squirrel.Windows,jbeshir/Squirrel.Windows,airtimemedia/Squirrel.Windows,1gurucoder/Squirrel.Windows,EdZava/Squirrel.Windows,allanrsmith/Squirrel.Windows,willdean/Squirrel.Windows,NeilSorensen/Squirrel.Windows,markwal/Squirrel.Windows,JonMartinTx/AS400Report,NeilSorensen/Squirrel.Windows,yovannyr/Squirrel.Windows,airtimemedia/Squirrel.Windows,punker76/Squirrel.Windows,BarryThePenguin/Squirrel.Windows,cguedel/Squirrel.Windows,josenbo/Squirrel.Windows,markuscarlen/Squirrel.Windows,jochenvangasse/Squirrel.Windows,allanrsmith/Squirrel.Windows,kenbailey/Squirrel.Windows,bowencode/Squirrel.Windows,NeilSorensen/Squirrel.Windows,vaginessa/Squirrel.Windows,aneeff/Squirrel.Windows,allanrsmith/Squirrel.Windows,akrisiun/Squirrel.Windows,markuscarlen/Squirrel.Windows,EdZava/Squirrel.Windows,Suninus/Squirrel.Windows,bowencode/Squirrel.Windows,Squirrel/Squirrel.Windows,sickboy/Squirrel.Windows,ruisebastiao/Squirrel.Windows
|
src/Squirrel/AssemblyExtensions.cs
|
src/Squirrel/AssemblyExtensions.cs
|
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Squirrel
{
public static class AssemblyExtensions
{
public static void Restart(this Assembly assembly, string[] arguments = null)
{
ProcessStart(assembly, assembly.Location, arguments);
}
public static void ProcessStart(this Assembly assembly, string exeName, string[] arguments = null)
{
Process.Start(getProcessStartInfo(assembly, exeName, arguments));
}
public static ProcessStartInfo ProcessStartGetInfo(this Assembly assembly, string exeName, string[] arguments = null)
{
return getProcessStartInfo(assembly, exeName, arguments);
}
static ProcessStartInfo getProcessStartInfo(Assembly assembly, string exeName, string[] arguments)
{
arguments = arguments ?? new string[] { };
object[] psi =
{
string.Format("--process-start=\"{0}\"", exeName),
string.Format("--process-start-args=\"{0}\"", string.Join(" ", arguments))
};
return new ProcessStartInfo(getUpdateExe(assembly), string.Format(" ", psi));
}
static string getUpdateExe(Assembly assembly)
{
var rootAppDir = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe");
return rootAppDir;
}
}
}
|
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Squirrel
{
public static class AssemblyExtensions
{
public static void Restart(this Assembly assembly, string[] arguments = null)
{
ProcessStart(assembly, assembly.Location, arguments);
}
public static void ProcessStart(this Assembly assembly, string exeName, string[] arguments = null)
{
Process.Start(getProcessStartInfo(assembly, exeName, arguments));
}
public static ProcessStartInfo ProcessStartGetInfo(this Assembly assembly, string exeName, string[] arguments = null)
{
return getProcessStartInfo(assembly, exeName, arguments);
}
static ProcessStartInfo getProcessStartInfo(Assembly assembly, string exeName, string[] arguments)
{
arguments = arguments ?? new string[] { };
object[] psi =
{
string.Format("--process-start={0}", exeName),
string.Format("--process-start-args={0}", string.Join(" ", arguments))
};
return new ProcessStartInfo(getUpdateExe(assembly), string.Format(" ", psi));
}
static string getUpdateExe(Assembly assembly)
{
var rootAppDir = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe");
return rootAppDir;
}
}
}
|
mit
|
C#
|
f73f822d1076765b396ed4804f4785efaf51b2e1
|
Backup name fixed.
|
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
|
src/Squidex/Areas/Api/Controllers/Backups/BackupContentController.cs
|
src/Squidex/Areas/Api/Controllers/Backups/BackupContentController.cs
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Orleans;
using Squidex.Domain.Apps.Entities.Backup;
using Squidex.Infrastructure.Assets;
using Squidex.Infrastructure.Commands;
using Squidex.Web;
namespace Squidex.Areas.Api.Controllers.Backups
{
/// <summary>
/// Manages backups for app.
/// </summary>
[ApiExplorerSettings(GroupName = nameof(Backups))]
public class BackupContentController : ApiController
{
private readonly IAssetStore assetStore;
private readonly IGrainFactory grainFactory;
public BackupContentController(ICommandBus commandBus, IAssetStore assetStore, IGrainFactory grainFactory)
: base(commandBus)
{
this.assetStore = assetStore;
this.grainFactory = grainFactory;
}
/// <summary>
/// Get the backup content.
/// </summary>
/// <param name="app">The name of the app.</param>
/// <param name="id">The id of the asset.</param>
/// <returns>
/// 200 => Backup found and content returned.
/// 404 => Backup or app not found.
/// </returns>
[HttpGet]
[Route("apps/{app}/backups/{id}")]
[ResponseCache(Duration = 3600 * 24 * 30)]
[ProducesResponseType(typeof(FileResult), 200)]
[ApiCosts(0)]
[AllowAnonymous]
public async Task<IActionResult> GetBackupContent(string app, Guid id)
{
var backupGrain = grainFactory.GetGrain<IBackupGrain>(AppId);
var backups = await backupGrain.GetStateAsync();
var backup = backups.Value.Find(x => x.Id == id);
if (backup == null || backup.Status != JobStatus.Completed)
{
return NotFound();
}
var fileName = $"backup-{app}-{backup.Started:yyyy-MM-dd_HH-mm-ss}.zip";
return new FileCallbackResult("application/zip", fileName, false, bodyStream =>
{
return assetStore.DownloadAsync(id.ToString(), 0, null, bodyStream);
});
}
}
}
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Orleans;
using Squidex.Domain.Apps.Entities.Backup;
using Squidex.Infrastructure.Assets;
using Squidex.Infrastructure.Commands;
using Squidex.Web;
namespace Squidex.Areas.Api.Controllers.Backups
{
/// <summary>
/// Manages backups for app.
/// </summary>
[ApiExplorerSettings(GroupName = nameof(Backups))]
public class BackupContentController : ApiController
{
private readonly IAssetStore assetStore;
private readonly IGrainFactory grainFactory;
public BackupContentController(ICommandBus commandBus, IAssetStore assetStore, IGrainFactory grainFactory)
: base(commandBus)
{
this.assetStore = assetStore;
this.grainFactory = grainFactory;
}
/// <summary>
/// Get the backup content.
/// </summary>
/// <param name="app">The name of the app.</param>
/// <param name="id">The id of the asset.</param>
/// <returns>
/// 200 => Backup found and content returned.
/// 404 => Backup or app not found.
/// </returns>
[HttpGet]
[Route("apps/{app}/backups/{id}")]
[ResponseCache(Duration = 3600 * 24 * 30)]
[ProducesResponseType(typeof(FileResult), 200)]
[ApiCosts(0)]
[AllowAnonymous]
public async Task<IActionResult> GetBackupContent(string app, Guid id)
{
var backupGrain = grainFactory.GetGrain<IBackupGrain>(AppId);
var backups = await backupGrain.GetStateAsync();
var backup = backups.Value.Find(x => x.Id == id);
if (backup == null || backup.Status != JobStatus.Completed)
{
return NotFound();
}
var fileName = $"backup-{app}-{backup.Started:yyyy-MM-dd_HH-mm-ss}";
return new FileCallbackResult("application/zip", fileName, false, bodyStream =>
{
return assetStore.DownloadAsync(id.ToString(), 0, null, bodyStream);
});
}
}
}
|
mit
|
C#
|
0d2faef1f966185bb76be8bd0ce9eb360fe0624d
|
Fix ordering of fluent API in SC-daemon so mempool loads on startup (#1902)
|
fassadlr/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode
|
src/Stratis.StratisSmartContractsD/Program.cs
|
src/Stratis.StratisSmartContractsD/Program.cs
|
using System;
using System.Threading.Tasks;
using NBitcoin;
using NBitcoin.Networks;
using NBitcoin.Protocol;
using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Features.Api;
using Stratis.Bitcoin.Features.BlockStore;
using Stratis.Bitcoin.Features.MemoryPool;
using Stratis.Bitcoin.Features.RPC;
using Stratis.Bitcoin.Features.SmartContracts;
using Stratis.Bitcoin.Features.SmartContracts.Networks;
using Stratis.Bitcoin.Features.SmartContracts.Wallet;
using Stratis.Bitcoin.Utilities;
namespace Stratis.StratisSmartContractsD
{
class Program
{
public static void Main(string[] args)
{
MainAsync(args).Wait();
}
public static async Task MainAsync(string[] args)
{
try
{
Network network = NetworkRegistration.Register(new SmartContractPosTest());
NodeSettings nodeSettings = new NodeSettings(network, ProtocolVersion.ALT_PROTOCOL_VERSION, "StratisSC", args: args);
Bitcoin.IFullNode node = new FullNodeBuilder()
.UseNodeSettings(nodeSettings)
.UseBlockStore()
.AddRPC()
.AddSmartContracts()
.UseSmartContractPosConsensus()
.UseSmartContractPosPowMining()
.UseSmartContractWallet()
.UseReflectionExecutor()
.UseApi()
.UseMempool()
.Build();
await node.RunAsync();
}
catch (Exception ex)
{
Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
}
}
}
}
|
using System;
using System.Threading.Tasks;
using NBitcoin;
using NBitcoin.Networks;
using NBitcoin.Protocol;
using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Features.Api;
using Stratis.Bitcoin.Features.BlockStore;
using Stratis.Bitcoin.Features.MemoryPool;
using Stratis.Bitcoin.Features.RPC;
using Stratis.Bitcoin.Features.SmartContracts;
using Stratis.Bitcoin.Features.SmartContracts.Networks;
using Stratis.Bitcoin.Features.SmartContracts.Wallet;
using Stratis.Bitcoin.Utilities;
namespace Stratis.StratisSmartContractsD
{
class Program
{
public static void Main(string[] args)
{
MainAsync(args).Wait();
}
public static async Task MainAsync(string[] args)
{
try
{
Network network = NetworkRegistration.Register(new SmartContractPosTest());
NodeSettings nodeSettings = new NodeSettings(network, ProtocolVersion.ALT_PROTOCOL_VERSION, "StratisSC", args: args);
Bitcoin.IFullNode node = new FullNodeBuilder()
.UseNodeSettings(nodeSettings)
.UseBlockStore()
.UseMempool()
.AddRPC()
.AddSmartContracts()
.UseSmartContractPosConsensus()
.UseSmartContractPosPowMining()
.UseSmartContractWallet()
.UseReflectionExecutor()
.UseApi()
.Build();
await node.RunAsync();
}
catch (Exception ex)
{
Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
}
}
}
}
|
mit
|
C#
|
081b8ba7342654d7d7459a74030c9aadd1ec2ec1
|
fix important bug
|
dethi/troma
|
src/Game/Arrow/Arrow/Game.cs
|
src/Game/Arrow/Arrow/Game.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Arrow
{
public partial class Game : Microsoft.Xna.Framework.Game
{
#region Fields
internal GraphicsDeviceManager graphics { get; private set; }
ScreenManager screenManager;
// Prelaod any assets using by UI rendering
static readonly string[] preloadAssets =
{
};
#endregion
#region Initialization
/// <summary>
/// The main game constructor
/// </summary>
public Game()
{
this.graphics = new GraphicsDeviceManager(this);
//ActivateFullScreen();
//DisableVsync();
Content.RootDirectory = "Content";
screenManager = new ScreenManager(this);
Components.Add(screenManager);
//screenManager.AddScreen(new GameplayScreen(this))
screenManager.AddScreen(new MainMenuScreen(this));
#if !BUILD
screenManager.AddScreen(new DebugScreen(this));
#endif
}
protected override void Initialize()
{
base.Initialize();
screenManager.Initialize();
}
/// <summary>
/// Load graphics content
/// </summary>
protected override void LoadContent()
{
foreach (string asset in preloadAssets)
Content.Load<object>(asset);
}
#endregion
#region Draw
protected override void Draw(GameTime gameTime)
{
//graphics.GraphicsDevice.Clear(Color.DarkOliveGreen);
graphics.GraphicsDevice.Clear(Color.Black);
base.Draw(gameTime);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Arrow
{
public partial class Game : Microsoft.Xna.Framework.Game
{
#region Fields
internal GraphicsDeviceManager graphics { get; private set; }
ScreenManager screenManager;
// Prelaod any assets using by UI rendering
static readonly string[] preloadAssets =
{
};
#endregion
#region Initialization
/// <summary>
/// The main game constructor
/// </summary>
public Game()
{
this.graphics = new GraphicsDeviceManager(this);
//ActivateFullScreen();
//DisableVsync();
Content.RootDirectory = "Content";
screenManager = new ScreenManager(this);
Components.Add(screenManager);
//screenManager.AddScreen(new GameplayScreen(this))
screenManager.AddScreen(new MainMenuScreen(this));
#if !BUILD
screenManager.AddScreen(new DebugScreen(this));
#endif
}
/// <summary>
/// Load graphics content
/// </summary>
protected override void LoadContent()
{
foreach (string asset in preloadAssets)
Content.Load<object>(asset);
}
#endregion
#region Draw
protected override void Draw(GameTime gameTime)
{
//graphics.GraphicsDevice.Clear(Color.DarkOliveGreen);
graphics.GraphicsDevice.Clear(Color.Black);
base.Draw(gameTime);
}
#endregion
}
}
|
mit
|
C#
|
a859a7b1441cd64b4fd6fe831877f1612943e50b
|
fix added class
|
StrubT/StrubTUtilities
|
StrubTUtilities/SimpleTree.cs
|
StrubTUtilities/SimpleTree.cs
|
using System;
using System.Collections.Generic;
namespace StrubT {
public interface IReadOnlyTree<out T> {
string Name { get; }
IReadOnlyCollection<IReadOnlyTreeNode<T>> RootNodes { get; }
}
public interface IReadOnlyTreeNode<out T> {
string Label { get; }
T Value { get; }
IReadOnlyCollection<IReadOnlyTreeNode<T>> Children { get; }
}
class Tree<T> : IReadOnlyTree<T>, IReadOnlyTreeNode<T> {
string IReadOnlyTreeNode<T>.Label => Name;
public string Name { get; }
T IReadOnlyTreeNode<T>.Value => throw new NotImplementedException();
List<Node> _rootNodes { get; } = new List<Node>();
IReadOnlyCollection<IReadOnlyTreeNode<T>> IReadOnlyTreeNode<T>.Children => _rootNodes;
public IReadOnlyCollection<IReadOnlyTreeNode<T>> RootNodes => _rootNodes;
public Tree(string name) => Name = name;
public INodeReference AddNode(string label, T value) {
var node = new Node(this, label, value);
_rootNodes.Add(node);
return new NodeReference(node);
}
INodeReference AddNode(IReadOnlyTreeNode<T> parentNode, string label, T value) {
var node = new Node(this, label, value);
((Node)parentNode).AddChild(node);
return new NodeReference(node);
}
public override string ToString() => $"[Tree<{typeof(T).Name}>] '{Name}'";
class Node : IReadOnlyTreeNode<T> {
internal Tree<T> Tree { get; }
public string Label { get; }
public T Value { get; }
List<Node> _children { get; }
public IReadOnlyCollection<IReadOnlyTreeNode<T>> Children => _children;
public Node(Tree<T> tree, string label, T value, params Node[] children) : this(tree, label, value, (IReadOnlyCollection<Node>)children) { }
public Node(Tree<T> tree, string label, T value, IReadOnlyCollection<Node> children) {
Tree = tree;
Label = label;
Value = value;
_children = children as List<Node> ?? new List<Node>(children);
}
public void AddChild(Node node) => _children.Add(node);
public override string ToString() => $"{Label} ({Value}), {Children.Count} child(ren)";
}
public interface INodeReference {
INodeReference AddNode(string label, T value);
}
class NodeReference : INodeReference {
internal Node Node { get; }
public NodeReference(Node node) => Node = node;
public INodeReference AddNode(string label, T value) => Node.Tree.AddNode(Node, label, value);
}
}
}
|
using System;
using System.Collections.Generic;
namespace StrubT {
public interface IReadOnlyTree<out T> {
string Name { get; }
IReadOnlyCollection<IReadOnlyTreeNode<T>> RootNodes { get; }
}
public interface IReadOnlyTreeNode<out T> {
string Label { get; }
T Value { get; }
IReadOnlyCollection<IReadOnlyTreeNode<T>> Children { get; }
}
public class Tree<T> : IReadOnlyTree<T>, IReadOnlyTreeNode<T> {
string IReadOnlyTreeNode<T>.Label => Name;
public string Name { get; }
T IReadOnlyTreeNode<T>.Value => throw new NotImplementedException();
List<Node> _rootNodes { get; } = new List<Node>();
IReadOnlyCollection<IReadOnlyTreeNode<T>> IReadOnlyTreeNode<T>.Children => _rootNodes;
public IReadOnlyCollection<IReadOnlyTreeNode<T>> RootNodes => _rootNodes;
public Tree(string name) => Name = name;
public INodeReference AddNode(string label, T value) {
var node = new Node(this, label, value);
_rootNodes.Add(node);
return new NodeReference(node);
}
INodeReference AddNode(IReadOnlyTreeNode<T> parentNode, string label, T value) {
var node = new Node(this, label, value);
((Node)parentNode).AddChild(node);
return new NodeReference(node);
}
public override string ToString() => $"[Tree<{typeof(T).Name}>] '{Name}'";
class Node : IReadOnlyTreeNode<T> {
internal Tree<T> Tree { get; }
public string Label { get; }
public T Value { get; }
List<Node> _children { get; }
public IReadOnlyCollection<IReadOnlyTreeNode<T>> Children => _children;
public Node(Tree<T> tree, string label, T value, params Node[] children) : this(tree, label, value, (IReadOnlyCollection<Node>)children) { }
public Node(Tree<T> tree, string label, T value, IReadOnlyCollection<Node> children) {
Tree = tree;
Label = label;
Value = value;
_children = children as List<Node> ?? new List<Node>(children);
}
public void AddChild(Node node) => _children.Add(node);
public override string ToString() => $"{Label} ({Value}), {Children.Count} child(ren)";
}
public interface INodeReference {
INodeReference AddNode(string label, T value);
}
class NodeReference : INodeReference {
internal Node Node { get; }
public NodeReference(Node node) => Node = node;
public INodeReference AddNode(string label, T value) => Node.Tree.AddNode(Node, label, value);
}
}
}
|
mit
|
C#
|
9435f1255e42f62eb6c904b74521d204dc3559e3
|
Tidy up Start() function comment
|
Nilihum/fungus,lealeelu/Fungus,snozbot/fungus,kdoore/Fungus,FungusGames/Fungus,RonanPearce/Fungus,tapiralec/Fungus,inarizushi/Fungus
|
Assets/Fungus/Scripts/View.cs
|
Assets/Fungus/Scripts/View.cs
|
using UnityEngine;
using System.Collections;
namespace Fungus
{
// Defines a camera view point.
// The position and rotation are specified using the game object's transform, so this class
// only specifies the ortographic view size.
[ExecuteInEditMode]
public class View : MonoBehaviour
{
public float viewSize = 0.5f;
// An empty Start() method is needed to display enable checkbox in editor
void Start()
{}
}
}
|
using UnityEngine;
using System.Collections;
namespace Fungus
{
// Defines a camera view point.
// The position and rotation are specified using the game object's transform, so this class
// only specifies the ortographic view size.
[ExecuteInEditMode]
public class View : MonoBehaviour
{
public float viewSize = 0.5f;
void Start()
{
// An empty Start() method is needed to display enable checkbox in editor
}
}
}
|
mit
|
C#
|
242be37073ede3ebbd522d0f353b443af5f6fa0f
|
remove unused using
|
LiberisLabs/CompaniesHouse.NET,kevbite/CompaniesHouse.NET
|
src/LiberisLabs.CompaniesHouse/CompaniesHouseCompanyFilingHistoryClient.cs
|
src/LiberisLabs.CompaniesHouse/CompaniesHouseCompanyFilingHistoryClient.cs
|
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using LiberisLabs.CompaniesHouse.Response.CompanyFiling;
using LiberisLabs.CompaniesHouse.UriBuilders;
namespace LiberisLabs.CompaniesHouse
{
public class CompaniesHouseCompanyFilingHistoryClient : ICompaniesHouseCompanyFilingHistoryClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ICompanyFilingHistoryUriBuilder _companyFilingHistoryUriBuilder;
public CompaniesHouseCompanyFilingHistoryClient(IHttpClientFactory httpClientFactory, ICompanyFilingHistoryUriBuilder companyFilingHistoryUriBuilder)
{
_httpClientFactory = httpClientFactory;
_companyFilingHistoryUriBuilder = companyFilingHistoryUriBuilder;
}
public async Task<CompaniesHouseClientResponse<CompanyFilingHistory>> GetCompanyProfileAsync(string companyNumber, int startIndex = 0, int pageSize = 25, CancellationToken cancellationToken = default(CancellationToken))
{
using (var httpClient = _httpClientFactory.CreateHttpClient())
{
var requestUri = _companyFilingHistoryUriBuilder.Build(companyNumber, startIndex, pageSize);
var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
// Return a null profile on 404s, but raise exception for all other error codes
if (response.StatusCode != System.Net.HttpStatusCode.NotFound)
response.EnsureSuccessStatusCode();
CompanyFilingHistory result = response.IsSuccessStatusCode
? await response.Content.ReadAsAsync<CompanyFilingHistory>(cancellationToken).ConfigureAwait(false)
: null;
return new CompaniesHouseClientResponse<CompanyFilingHistory>(result);
}
}
}
}
|
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using LiberisLabs.CompaniesHouse.Response.CompanyFiling;
using LiberisLabs.CompaniesHouse.Response.CompanyProfile;
using LiberisLabs.CompaniesHouse.UriBuilders;
namespace LiberisLabs.CompaniesHouse
{
public class CompaniesHouseCompanyFilingHistoryClient : ICompaniesHouseCompanyFilingHistoryClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ICompanyFilingHistoryUriBuilder _companyFilingHistoryUriBuilder;
public CompaniesHouseCompanyFilingHistoryClient(IHttpClientFactory httpClientFactory, ICompanyFilingHistoryUriBuilder companyFilingHistoryUriBuilder)
{
_httpClientFactory = httpClientFactory;
_companyFilingHistoryUriBuilder = companyFilingHistoryUriBuilder;
}
public async Task<CompaniesHouseClientResponse<CompanyFilingHistory>> GetCompanyProfileAsync(string companyNumber, int startIndex = 0, int pageSize = 25, CancellationToken cancellationToken = default(CancellationToken))
{
using (var httpClient = _httpClientFactory.CreateHttpClient())
{
var requestUri = _companyFilingHistoryUriBuilder.Build(companyNumber, startIndex, pageSize);
var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
// Return a null profile on 404s, but raise exception for all other error codes
if (response.StatusCode != System.Net.HttpStatusCode.NotFound)
response.EnsureSuccessStatusCode();
CompanyFilingHistory result = response.IsSuccessStatusCode
? await response.Content.ReadAsAsync<CompanyFilingHistory>(cancellationToken).ConfigureAwait(false)
: null;
return new CompaniesHouseClientResponse<CompanyFilingHistory>(result);
}
}
}
}
|
mit
|
C#
|
7ae19dc6634b01ea654b156e006bd246219bcd16
|
set width/height to 0
|
yasokada/unity-150905-dynamicDisplay
|
Assets/PanelDisplayControl.cs
|
Assets/PanelDisplayControl.cs
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.1 2015/09/05
* - show/hide panels
*/
public class PanelDisplayControl : MonoBehaviour {
public GameObject PageSelect;
public GameObject PanelGroup;
private Vector2[] orgSize;
void Start() {
orgSize = new Vector2[4];
int idx=0;
foreach (Transform child in PanelGroup.transform) {
orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width;
orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height;
bool isOn = getIsOn (idx + 1);
DisplayPanel (idx + 1, isOn);
idx++;
}
}
bool getIsOn(int idx_st1) {
Toggle selected = null;
string name;
foreach (Transform child in PageSelect.transform) {
name = child.gameObject.name;
if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"...
selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle;
break;
}
}
return selected.isOn;
}
void DisplayPanel(int idx_st1, bool doShow)
{
GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ());
if (panel == null) {
return;
}
RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform;
Vector2 size = rect.sizeDelta;
if (doShow) {
size.x = orgSize[idx_st1 - 1].x;
size.y = orgSize[idx_st1 - 1].y;
} else {
size.x = 0;
size.y = 0;
}
rect.sizeDelta = size;
}
public void ToggleValueChanged(int idx_st1) {
bool isOn = getIsOn (idx_st1);
DisplayPanel (idx_st1, isOn);
Debug.Log (isOn.ToString ());
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.1 2015/09/05
* - show/hide panels
*/
public class PanelDisplayControl : MonoBehaviour {
public GameObject PageSelect;
public GameObject PanelGroup;
private Vector2[] orgSize;
void Start() {
orgSize = new Vector2[4];
int idx=0;
foreach (Transform child in PanelGroup.transform) {
orgSize[idx].x = child.gameObject.GetComponent<RectTransform>().rect.width;
orgSize[idx].y = child.gameObject.GetComponent<RectTransform>().rect.height;
bool isOn = getIsOn (idx + 1);
DisplayPanel (idx + 1, isOn);
idx++;
}
}
bool getIsOn(int idx_st1) {
Toggle selected = null;
string name;
foreach (Transform child in PageSelect.transform) {
name = child.gameObject.name;
if (name.Contains(idx_st1.ToString())) { // e.g. "SelP1", "SelP2"...
selected = child.gameObject.GetComponent(typeof(Toggle)) as Toggle;
break;
}
}
return selected.isOn;
}
void DisplayPanel(int idx_st1, bool doShow)
{
GameObject panel = GameObject.Find ("Panel" + idx_st1.ToString ());
if (panel == null) {
return;
}
RectTransform rect = panel.GetComponent (typeof(RectTransform)) as RectTransform;
Vector2 size = rect.sizeDelta;
if (doShow) {
size.x = orgSize[idx_st1 - 1].x;
size.y = orgSize[idx_st1 - 1].y;
} else {
size.x = 1;
size.y = 1;
}
rect.sizeDelta = size;
}
public void ToggleValueChanged(int idx_st1) {
bool isOn = getIsOn (idx_st1);
DisplayPanel (idx_st1, isOn);
Debug.Log (isOn.ToString ());
}
}
|
mit
|
C#
|
fa0830b44fb8ddfa3d712e3381f04bf6490469e2
|
Update player XP
|
jamioflan/LD38
|
Assets/Scripts/HUD_Manager.cs
|
Assets/Scripts/HUD_Manager.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD_Manager : MonoBehaviour
{
// The names of the GUI objects we're editing
public string amountXPElementName;
public string playerHealthElementName;
public string equippedWeaponIconElementName;
// Equipped weapon icons to use
public Sprite equippedMeleeSprite;
public Sprite equippedRangedSprite;
public Sprite equippedMagicSprite;
// The GUI objects we're editing
GUIText amountXPText;
Slider playerHealthSlider;
Image equippedWeaponIcon;
// Use this for initialization
void Start ()
{
// Find and store the things we'll be modifying
amountXPText = GameObject.Find(amountXPElementName).GetComponent<GUIText>();
playerHealthSlider = GameObject.Find(playerHealthElementName).GetComponent<Slider>();
equippedWeaponIcon = GameObject.Find(equippedWeaponIconElementName).GetComponent<Image>();
}
// Update is called once per frame
void Update ()
{
// Update player XP, health and equipped weapon icon
amountXPText.text = Game.thePlayer.XP.ToString();
playerHealthSlider.value = Game.thePlayer.health / Game.thePlayer.maxHealth;
// TODO: equipped weapon
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD_Manager : MonoBehaviour
{
// The names of the GUI objects we're editing
public string amountXPElementName;
public string playerHealthElementName;
public string equippedWeaponIconElementName;
// Equipped weapon icons to use
public Sprite equippedMeleeSprite;
public Sprite equippedRangedSprite;
public Sprite equippedMagicSprite;
// The GUI objects we're editing
GUIText amountXPText;
Slider playerHealthSlider;
Image equippedWeaponIcon;
// Use this for initialization
void Start ()
{
// Find and store the things we'll be modifying
amountXPText = GameObject.Find(amountXPElementName).GetComponent<GUIText>();
playerHealthSlider = GameObject.Find(playerHealthElementName).GetComponent<Slider>();
equippedWeaponIcon = GameObject.Find(equippedWeaponIconElementName).GetComponent<Image>();
}
// Update is called once per frame
void Update ()
{
// Update player health, XP and equipped weapon icon
// TODO
playerHealthSlider.value = Game.thePlayer.health / Game.thePlayer.maxHealth;
}
}
|
mit
|
C#
|
c6d4e0dac5fb2607b1d06d8ae5a4529398f79d41
|
use the right root.
|
KirillOsenkov/roslyn,eriawan/roslyn,srivatsn/roslyn,wvdd007/roslyn,physhi/roslyn,orthoxerox/roslyn,agocke/roslyn,wvdd007/roslyn,orthoxerox/roslyn,tvand7093/roslyn,nguerrera/roslyn,weltkante/roslyn,kelltrick/roslyn,stephentoub/roslyn,jmarolf/roslyn,MattWindsor91/roslyn,amcasey/roslyn,TyOverby/roslyn,dotnet/roslyn,jcouv/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,gafter/roslyn,a-ctor/roslyn,kelltrick/roslyn,DustinCampbell/roslyn,xoofx/roslyn,heejaechang/roslyn,AnthonyDGreen/roslyn,reaction1989/roslyn,mavasani/roslyn,robinsedlaczek/roslyn,jeffanders/roslyn,brettfo/roslyn,bkoelman/roslyn,KevinRansom/roslyn,Hosch250/roslyn,bartdesmet/roslyn,CaptainHayashi/roslyn,Hosch250/roslyn,bbarry/roslyn,mgoertz-msft/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,jkotas/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,weltkante/roslyn,abock/roslyn,jeffanders/roslyn,tmeschter/roslyn,mattscheffer/roslyn,amcasey/roslyn,KirillOsenkov/roslyn,yeaicc/roslyn,heejaechang/roslyn,jamesqo/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,bkoelman/roslyn,panopticoncentral/roslyn,Giftednewt/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,diryboy/roslyn,bbarry/roslyn,dpoeschl/roslyn,KirillOsenkov/roslyn,paulvanbrenk/roslyn,ErikSchierboom/roslyn,jeffanders/roslyn,akrisiun/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,sharwell/roslyn,panopticoncentral/roslyn,Hosch250/roslyn,DustinCampbell/roslyn,jcouv/roslyn,tannergooding/roslyn,jcouv/roslyn,gafter/roslyn,bkoelman/roslyn,a-ctor/roslyn,stephentoub/roslyn,xasx/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,mmitche/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,cston/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,a-ctor/roslyn,diryboy/roslyn,eriawan/roslyn,abock/roslyn,srivatsn/roslyn,amcasey/roslyn,mattscheffer/roslyn,xasx/roslyn,CaptainHayashi/roslyn,MichalStrehovsky/roslyn,MattWindsor91/roslyn,jamesqo/roslyn,paulvanbrenk/roslyn,sharwell/roslyn,physhi/roslyn,khyperia/roslyn,swaroop-sridhar/roslyn,drognanar/roslyn,heejaechang/roslyn,bartdesmet/roslyn,MichalStrehovsky/roslyn,mmitche/roslyn,paulvanbrenk/roslyn,zooba/roslyn,tannergooding/roslyn,akrisiun/roslyn,orthoxerox/roslyn,yeaicc/roslyn,TyOverby/roslyn,genlu/roslyn,Giftednewt/roslyn,pdelvo/roslyn,jmarolf/roslyn,mmitche/roslyn,AlekseyTs/roslyn,OmarTawfik/roslyn,pdelvo/roslyn,ErikSchierboom/roslyn,xoofx/roslyn,drognanar/roslyn,wvdd007/roslyn,AnthonyDGreen/roslyn,eriawan/roslyn,genlu/roslyn,dotnet/roslyn,tmat/roslyn,AArnott/roslyn,robinsedlaczek/roslyn,jkotas/roslyn,VSadov/roslyn,abock/roslyn,tvand7093/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tmeschter/roslyn,mattscheffer/roslyn,CyrusNajmabadi/roslyn,Giftednewt/roslyn,davkean/roslyn,davkean/roslyn,VSadov/roslyn,khyperia/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,mattwar/roslyn,nguerrera/roslyn,cston/roslyn,mavasani/roslyn,AnthonyDGreen/roslyn,AlekseyTs/roslyn,jkotas/roslyn,brettfo/roslyn,aelij/roslyn,jamesqo/roslyn,khyperia/roslyn,reaction1989/roslyn,agocke/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,jasonmalinowski/roslyn,tvand7093/roslyn,zooba/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,mattwar/roslyn,VSadov/roslyn,lorcanmooney/roslyn,robinsedlaczek/roslyn,mattwar/roslyn,agocke/roslyn,reaction1989/roslyn,AmadeusW/roslyn,AArnott/roslyn,TyOverby/roslyn,bbarry/roslyn,stephentoub/roslyn,xoofx/roslyn,zooba/roslyn,AmadeusW/roslyn,MattWindsor91/roslyn,aelij/roslyn,nguerrera/roslyn,lorcanmooney/roslyn,weltkante/roslyn,AlekseyTs/roslyn,dpoeschl/roslyn,OmarTawfik/roslyn,tmat/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,AArnott/roslyn,AmadeusW/roslyn,gafter/roslyn,yeaicc/roslyn,drognanar/roslyn,MichalStrehovsky/roslyn,tannergooding/roslyn,CaptainHayashi/roslyn,OmarTawfik/roslyn,akrisiun/roslyn,dotnet/roslyn,kelltrick/roslyn,xasx/roslyn,diryboy/roslyn,bartdesmet/roslyn,cston/roslyn,aelij/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tmat/roslyn
|
src/Workspaces/Core/Portable/CodeFixes/SyntaxEditorBasedCodeFixProvider.cs
|
src/Workspaces/Core/Portable/CodeFixes/SyntaxEditorBasedCodeFixProvider.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal abstract partial class SyntaxEditorBasedCodeFixProvider : CodeFixProvider
{
public sealed override FixAllProvider GetFixAllProvider()
=> new SyntaxEditorBasedFixAllProvider(this);
protected Task<Document> FixAsync(
Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
return FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken);
}
private async Task<Document> FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
await FixAllAsync(document, diagnostics, editor, cancellationToken).ConfigureAwait(false);
var newRoot = editor.GetChangedRoot();
return document.WithSyntaxRoot(newRoot);
}
protected abstract Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken);
/// <summary>
/// Whether or not this diagnostic should be included when performing a FixAll. This is useful
/// for providers that create multiple diagnostics for the same issue (For example, one main
/// diagnostic and multiple 'faded out code' diagnostics). FixAll can be invoked from any of
/// those, but we'll only want perform an edit for only one diagnostic for each of those sets
/// of diagnostics.
/// </summary>
protected virtual bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => true;
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal abstract partial class SyntaxEditorBasedCodeFixProvider : CodeFixProvider
{
public sealed override FixAllProvider GetFixAllProvider()
=> new SyntaxEditorBasedFixAllProvider(this);
protected Task<Document> FixAsync(
Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
return FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken);
}
private async Task<Document> FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
await FixAllAsync(document, diagnostics, editor, cancellationToken).ConfigureAwait(false);
var newRoot = editor.GetChangedRoot();
return document.WithSyntaxRoot(root);
}
protected abstract Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken);
/// <summary>
/// Whether or not this diagnostic should be included when performing a FixAll. This is useful
/// for providers that create multiple diagnostics for the same issue (For example, one main
/// diagnostic and multiple 'faded out code' diagnostics). FixAll can be invoked from any of
/// those, but we'll only want perform an edit for only one diagnostic for each of those sets
/// of diagnostics.
/// </summary>
protected virtual bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => true;
}
}
|
mit
|
C#
|
cc5b9a85275a283e450c787192f8a286415842e3
|
增强对取值的处理。 :fu:
|
Zongsoft/Zongsoft.CoreLibrary
|
src/Data/ConditionalRange.cs
|
src/Data/ConditionalRange.cs
|
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections;
namespace Zongsoft.Data
{
public class ConditionalRange
{
#region 成员字段
private object _from;
private object _to;
#endregion
#region 构造函数
public ConditionalRange()
{
}
public ConditionalRange(object from, object to)
{
this.From = from;
this.To = to;
}
#endregion
#region 公共属性
public object From
{
get
{
return _from;
}
set
{
_from = GetValue(value);
}
}
public object To
{
get
{
return _to;
}
set
{
_to = GetValue(value);
}
}
#endregion
#region 公共方法
public Condition ToCondition(string name)
{
if(_from == null)
return _to == null ? null : new Condition(name, _to, ConditionOperator.LessThanEqual);
else
return _to == null ? new Condition(name, _from, ConditionOperator.GreaterThanEqual) : new Condition(name, new object[] { _from, _to }, ConditionOperator.Between);
}
#endregion
#region 静态方法
public static bool IsEmpty(ConditionalRange value)
{
return value == null || (value.From == null && value.To == null);
}
#endregion
#region 私有方法
private static object GetValue(object value)
{
if(value == null || System.Convert.IsDBNull(value))
return null;
if(value is string)
{
if(string.IsNullOrWhiteSpace((string)value))
return null;
return value;
}
var items = value as IEnumerable;
if(items != null)
{
var enumerator = items.GetEnumerator();
if(enumerator != null && enumerator.MoveNext())
{
var current = enumerator.Current;
enumerator.Reset();
return GetValue(current);
}
return null;
}
return value;
}
#endregion
}
}
|
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2016 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
namespace Zongsoft.Data
{
public class ConditionalRange
{
#region 成员字段
private object _from;
private object _to;
#endregion
#region 构造函数
public ConditionalRange(object from, object to)
{
_from = from;
_to = to;
}
#endregion
#region 公共属性
public object From
{
get
{
return _from;
}
set
{
_from = value;
}
}
public object To
{
get
{
return _to;
}
set
{
_to = value;
}
}
#endregion
#region 公共方法
public Condition ToCondition(string name)
{
if(_from == null)
return _to == null ? null : new Condition(name, _to, ConditionOperator.LessThanEqual);
else
return _to == null ? new Condition(name, _from, ConditionOperator.GreaterThanEqual) : new Condition(name, new object[] { _from, _to }, ConditionOperator.Between);
}
#endregion
#region 静态方法
public static bool IsEmpty(ConditionalRange value)
{
return value == null || (value.From == null && value.To == null);
}
#endregion
}
}
|
lgpl-2.1
|
C#
|
c1ec20a1e08bc528aa60a5c6207bb59cdf53f59a
|
Check if argument in projection provider attribute is a valid type
|
ircnelson/enjoy.cqrs,ircnelson/enjoy.cqrs
|
src/EnjoyCQRS/Attributes/ProjectionProviderAttribute.cs
|
src/EnjoyCQRS/Attributes/ProjectionProviderAttribute.cs
|
using System;
using System.Reflection;
using EnjoyCQRS.EventSource.Projections;
namespace EnjoyCQRS.Attributes
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ProjectionProviderAttribute : Attribute
{
public Type Provider { get; }
public ProjectionProviderAttribute(Type provider)
{
if (provider == null) throw new ArgumentNullException(nameof(provider));
if (provider.IsAssignableFrom(typeof(IProjectionProvider))) throw new ArgumentException($"Provider should be inherited of {nameof(IProjectionProvider)}.");
Provider = provider;
}
}
}
|
using System;
namespace EnjoyCQRS.Attributes
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ProjectionProviderAttribute : Attribute
{
public Type Provider { get; }
public ProjectionProviderAttribute(Type provider)
{
Provider = provider;
}
}
}
|
mit
|
C#
|
d8a5dc86774929a9db383ad77a51de038e008b01
|
Fix bug。
|
tangxuehua/equeue,geffzhang/equeue,geffzhang/equeue,tangxuehua/equeue,Aaron-Liu/equeue,Aaron-Liu/equeue,tangxuehua/equeue
|
src/Samples/QuickStart/QuickStart.BrokerServer/Program.cs
|
src/Samples/QuickStart/QuickStart.BrokerServer/Program.cs
|
using System;
using System.Configuration;
using ECommon.Configurations;
using EQueue.Broker;
using EQueue.Configurations;
using ECommonConfiguration = ECommon.Configurations.Configuration;
namespace QuickStart.BrokerServer
{
class Program
{
static void Main(string[] args)
{
InitializeEQueue();
var setting = new BrokerSetting(
false,
ConfigurationManager.AppSettings["fileStoreRootPath"],
chunkCacheMaxPercent: 95,
chunkFlushInterval: int.Parse(ConfigurationManager.AppSettings["flushInterval"]),
messageChunkDataSize: int.Parse(ConfigurationManager.AppSettings["chunkSize"]) * 1024 * 1024,
chunkWriteBuffer: int.Parse(ConfigurationManager.AppSettings["chunkWriteBuffer"]) * 1024,
enableCache: bool.Parse(ConfigurationManager.AppSettings["enableCache"]),
chunkCacheMinPercent: int.Parse(ConfigurationManager.AppSettings["chunkCacheMinPercent"]),
messageChunkLocalCacheSize: 30 * 10000,
queueChunkLocalCacheSize: 10000)
{
NotifyWhenMessageArrived = false
};
BrokerController.Create(setting).Start();
Console.ReadLine();
}
static void InitializeEQueue()
{
var configuration = ECommonConfiguration
.Create()
.UseAutofac()
.RegisterCommonComponents()
.UseLog4Net()
.UseJsonNet()
.RegisterUnhandledExceptionHandler()
.RegisterEQueueComponents()
.UseDeleteMessageByCountStrategy(10);
}
}
}
|
using System;
using System.Configuration;
using ECommon.Configurations;
using EQueue.Broker;
using EQueue.Configurations;
using ECommonConfiguration = ECommon.Configurations.Configuration;
namespace QuickStart.BrokerServer
{
class Program
{
static void Main(string[] args)
{
InitializeEQueue();
var setting = new BrokerSetting(
ConfigurationManager.AppSettings["fileStoreRootPath"],
chunkCacheMaxPercent: 95,
chunkFlushInterval: int.Parse(ConfigurationManager.AppSettings["flushInterval"]),
messageChunkDataSize: int.Parse(ConfigurationManager.AppSettings["chunkSize"]) * 1024 * 1024,
chunkWriteBuffer: int.Parse(ConfigurationManager.AppSettings["chunkWriteBuffer"]) * 1024,
enableCache: bool.Parse(ConfigurationManager.AppSettings["enableCache"]),
chunkCacheMinPercent: int.Parse(ConfigurationManager.AppSettings["chunkCacheMinPercent"]),
messageChunkLocalCacheSize: 30 * 10000,
queueChunkLocalCacheSize: 10000)
{
NotifyWhenMessageArrived = false
};
BrokerController.Create(setting).Start();
Console.ReadLine();
}
static void InitializeEQueue()
{
var configuration = ECommonConfiguration
.Create()
.UseAutofac()
.RegisterCommonComponents()
.UseLog4Net()
.UseJsonNet()
.RegisterUnhandledExceptionHandler()
.RegisterEQueueComponents()
.UseDeleteMessageByCountStrategy(10);
}
}
}
|
mit
|
C#
|
1158e7051d7a28edd15040aa50d4a097bec52b2e
|
fix type compile bug
|
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
|
src/Core/Models/Api/Response/ProfileOrganizationResponseModel.cs
|
src/Core/Models/Api/Response/ProfileOrganizationResponseModel.cs
|
using Bit.Core.Enums;
using Bit.Core.Models.Data;
namespace Bit.Core.Models.Api
{
public class ProfileOrganizationResponseModel : ResponseModel
{
public ProfileOrganizationResponseModel(OrganizationUserOrganizationDetails organization)
: base("profileOrganization")
{
Id = organization.OrganizationId.ToString();
Name = organization.Name;
Key = organization.Key;
Status = organization.Status;
Type = organization.Type;
}
public string Id { get; set; }
public string Name { get; set; }
public string Key { get; set; }
public OrganizationUserStatusType Status { get; set; }
public OrganizationUserType Type { get; set; }
}
}
|
using Bit.Core.Enums;
using Bit.Core.Models.Data;
namespace Bit.Core.Models.Api
{
public class ProfileOrganizationResponseModel : ResponseModel
{
public ProfileOrganizationResponseModel(OrganizationUserOrganizationDetails organization)
: base("profileOrganization")
{
Id = organization.OrganizationId.ToString();
Name = organization.Name;
Key = organization.Key;
Status = organization.Status;
Type = organization;
}
public string Id { get; set; }
public string Name { get; set; }
public string Key { get; set; }
public OrganizationUserStatusType Status { get; set; }
public OrganizationUserType Type { get; set; }
}
}
|
agpl-3.0
|
C#
|
a4927637feda932bc6e26b9a613645cda628bf17
|
Remove changes done to unrelated unit test
|
mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,JasperFx/Marten,mysticmind/marten,mysticmind/marten,mdissel/Marten,mdissel/Marten,ericgreenmix/marten,mysticmind/marten,JasperFx/Marten,JasperFx/Marten,ericgreenmix/marten
|
src/Marten.Testing/duplicate_fields_in_table_and_upsert_Tests.cs
|
src/Marten.Testing/duplicate_fields_in_table_and_upsert_Tests.cs
|
using Baseline;
using Marten.Schema;
using Marten.Services;
using Marten.Testing.Documents;
using Shouldly;
using Xunit;
namespace Marten.Testing
{
public class duplicate_fields_in_table_and_upsert_Tests : IntegratedFixture
{
[Fact]
public void end_to_end()
{
theStore.Storage.MappingFor(typeof(User)).As<DocumentMapping>().DuplicateField("FirstName");
var user1 = new User { FirstName = "Byron", LastName = "Scott" };
using (var session = theStore.OpenSession())
{
session.Store(user1);
session.SaveChanges();
}
var runner = theStore.Tenancy.Default.OpenConnection();
runner.QueryScalar<string>($"select first_name from mt_doc_user where id = '{user1.Id}'")
.ShouldBe("Byron");
}
}
}
|
using Baseline;
using Marten.Schema;
using Marten.Services;
using Marten.Testing.Documents;
using Shouldly;
using Xunit;
namespace Marten.Testing
{
public class duplicate_fields_in_table_and_upsert_Tests : IntegratedFixture
{
[Fact]
public void end_to_end()
{
theStore.Storage.MappingFor(typeof(User)).As<DocumentMapping>().DuplicateField("FirstName");
var store = DocumentStore.For(_ =>
{
_.Connection("host=localhost;database=test;password=password1;username=postgres");
_.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate;
_.Schema.For<User>()
.Duplicate(u => u.FirstName);
});
var user1 = new User { FirstName = "Byron", LastName = "Scott" };
using (var session = theStore.OpenSession())
{
session.Store(user1);
session.SaveChanges();
}
var runner = theStore.Tenancy.Default.OpenConnection();
runner.QueryScalar<string>($"select first_name from mt_doc_user where id = '{user1.Id}'")
.ShouldBe("Byron");
}
}
}
|
mit
|
C#
|
e58a648bd01cf71dc3304bb4a0713252a0ed9dd3
|
Add Microsoft.Win32.Registry serialization
|
twsouthwick/corefx,ravimeda/corefx,billwert/corefx,Petermarcu/corefx,nbarbettini/corefx,rjxby/corefx,the-dwyer/corefx,krk/corefx,rahku/corefx,BrennanConroy/corefx,jlin177/corefx,ravimeda/corefx,dotnet-bot/corefx,nbarbettini/corefx,axelheer/corefx,weltkante/corefx,parjong/corefx,Ermiar/corefx,seanshpark/corefx,jlin177/corefx,parjong/corefx,ptoonen/corefx,tijoytom/corefx,cydhaselton/corefx,ViktorHofer/corefx,ravimeda/corefx,zhenlan/corefx,krk/corefx,alexperovich/corefx,cydhaselton/corefx,axelheer/corefx,tijoytom/corefx,Ermiar/corefx,shimingsg/corefx,Jiayili1/corefx,richlander/corefx,richlander/corefx,lggomez/corefx,ViktorHofer/corefx,gkhanna79/corefx,shimingsg/corefx,nbarbettini/corefx,marksmeltzer/corefx,krytarowski/corefx,dhoehna/corefx,gkhanna79/corefx,JosephTremoulet/corefx,krk/corefx,rahku/corefx,shimingsg/corefx,zhenlan/corefx,tijoytom/corefx,parjong/corefx,mazong1123/corefx,seanshpark/corefx,gkhanna79/corefx,twsouthwick/corefx,rahku/corefx,Jiayili1/corefx,yizhang82/corefx,mmitche/corefx,dotnet-bot/corefx,elijah6/corefx,MaggieTsang/corefx,alexperovich/corefx,DnlHarvey/corefx,rahku/corefx,alexperovich/corefx,JosephTremoulet/corefx,nchikanov/corefx,JosephTremoulet/corefx,parjong/corefx,jlin177/corefx,wtgodbe/corefx,mazong1123/corefx,dhoehna/corefx,krytarowski/corefx,lggomez/corefx,mmitche/corefx,ViktorHofer/corefx,stone-li/corefx,DnlHarvey/corefx,ravimeda/corefx,krk/corefx,rubo/corefx,mazong1123/corefx,ericstj/corefx,richlander/corefx,dhoehna/corefx,nbarbettini/corefx,twsouthwick/corefx,zhenlan/corefx,billwert/corefx,krytarowski/corefx,YoupHulsebos/corefx,stone-li/corefx,nchikanov/corefx,ViktorHofer/corefx,ericstj/corefx,MaggieTsang/corefx,gkhanna79/corefx,weltkante/corefx,MaggieTsang/corefx,dhoehna/corefx,Petermarcu/corefx,ViktorHofer/corefx,elijah6/corefx,rjxby/corefx,Ermiar/corefx,DnlHarvey/corefx,krytarowski/corefx,marksmeltzer/corefx,shimingsg/corefx,ravimeda/corefx,rjxby/corefx,krytarowski/corefx,wtgodbe/corefx,lggomez/corefx,mmitche/corefx,rahku/corefx,ericstj/corefx,parjong/corefx,Petermarcu/corefx,richlander/corefx,ericstj/corefx,nchikanov/corefx,stephenmichaelf/corefx,elijah6/corefx,rubo/corefx,marksmeltzer/corefx,krk/corefx,Petermarcu/corefx,JosephTremoulet/corefx,richlander/corefx,fgreinacher/corefx,ptoonen/corefx,Jiayili1/corefx,YoupHulsebos/corefx,dotnet-bot/corefx,Petermarcu/corefx,ericstj/corefx,dotnet-bot/corefx,Ermiar/corefx,Ermiar/corefx,BrennanConroy/corefx,nbarbettini/corefx,rjxby/corefx,jlin177/corefx,wtgodbe/corefx,DnlHarvey/corefx,ViktorHofer/corefx,rubo/corefx,rahku/corefx,mmitche/corefx,JosephTremoulet/corefx,twsouthwick/corefx,lggomez/corefx,cydhaselton/corefx,jlin177/corefx,DnlHarvey/corefx,zhenlan/corefx,tijoytom/corefx,cydhaselton/corefx,stephenmichaelf/corefx,shimingsg/corefx,marksmeltzer/corefx,elijah6/corefx,ptoonen/corefx,stephenmichaelf/corefx,weltkante/corefx,weltkante/corefx,stone-li/corefx,seanshpark/corefx,twsouthwick/corefx,fgreinacher/corefx,stephenmichaelf/corefx,Ermiar/corefx,stone-li/corefx,tijoytom/corefx,yizhang82/corefx,Jiayili1/corefx,elijah6/corefx,the-dwyer/corefx,lggomez/corefx,dotnet-bot/corefx,ptoonen/corefx,alexperovich/corefx,the-dwyer/corefx,nchikanov/corefx,marksmeltzer/corefx,nchikanov/corefx,stephenmichaelf/corefx,the-dwyer/corefx,ericstj/corefx,seanshpark/corefx,nbarbettini/corefx,YoupHulsebos/corefx,axelheer/corefx,jlin177/corefx,nchikanov/corefx,billwert/corefx,yizhang82/corefx,seanshpark/corefx,stone-li/corefx,shimingsg/corefx,ptoonen/corefx,the-dwyer/corefx,stone-li/corefx,marksmeltzer/corefx,yizhang82/corefx,weltkante/corefx,ptoonen/corefx,zhenlan/corefx,Petermarcu/corefx,rahku/corefx,rubo/corefx,wtgodbe/corefx,nbarbettini/corefx,wtgodbe/corefx,lggomez/corefx,axelheer/corefx,cydhaselton/corefx,shimingsg/corefx,YoupHulsebos/corefx,zhenlan/corefx,weltkante/corefx,krk/corefx,weltkante/corefx,yizhang82/corefx,cydhaselton/corefx,the-dwyer/corefx,ravimeda/corefx,dotnet-bot/corefx,krk/corefx,fgreinacher/corefx,Jiayili1/corefx,stone-li/corefx,mazong1123/corefx,billwert/corefx,wtgodbe/corefx,mmitche/corefx,mazong1123/corefx,krytarowski/corefx,zhenlan/corefx,YoupHulsebos/corefx,BrennanConroy/corefx,richlander/corefx,billwert/corefx,alexperovich/corefx,mazong1123/corefx,fgreinacher/corefx,twsouthwick/corefx,elijah6/corefx,lggomez/corefx,DnlHarvey/corefx,tijoytom/corefx,ptoonen/corefx,stephenmichaelf/corefx,Ermiar/corefx,stephenmichaelf/corefx,YoupHulsebos/corefx,mmitche/corefx,axelheer/corefx,billwert/corefx,tijoytom/corefx,cydhaselton/corefx,yizhang82/corefx,alexperovich/corefx,yizhang82/corefx,alexperovich/corefx,JosephTremoulet/corefx,the-dwyer/corefx,MaggieTsang/corefx,dhoehna/corefx,rjxby/corefx,billwert/corefx,Jiayili1/corefx,Jiayili1/corefx,gkhanna79/corefx,rubo/corefx,dhoehna/corefx,dotnet-bot/corefx,mazong1123/corefx,nchikanov/corefx,MaggieTsang/corefx,MaggieTsang/corefx,seanshpark/corefx,mmitche/corefx,ericstj/corefx,Petermarcu/corefx,axelheer/corefx,ravimeda/corefx,parjong/corefx,jlin177/corefx,twsouthwick/corefx,gkhanna79/corefx,gkhanna79/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,marksmeltzer/corefx,parjong/corefx,wtgodbe/corefx,richlander/corefx,DnlHarvey/corefx,dhoehna/corefx,YoupHulsebos/corefx,rjxby/corefx,rjxby/corefx,elijah6/corefx,krytarowski/corefx,ViktorHofer/corefx,seanshpark/corefx
|
src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryHive.cs
|
src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryHive.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.Win32
{
/**
* Registry hive values. Useful only for GetRemoteBaseKey
*/
[Serializable]
#if REGISTRY_ASSEMBLY
public
#else
internal
#endif
enum RegistryHive
{
ClassesRoot = unchecked((int)0x80000000),
CurrentUser = unchecked((int)0x80000001),
LocalMachine = unchecked((int)0x80000002),
Users = unchecked((int)0x80000003),
PerformanceData = unchecked((int)0x80000004),
CurrentConfig = unchecked((int)0x80000005),
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32
{
/**
* Registry hive values. Useful only for GetRemoteBaseKey
*/
#if REGISTRY_ASSEMBLY
public
#else
internal
#endif
enum RegistryHive
{
ClassesRoot = unchecked((int)0x80000000),
CurrentUser = unchecked((int)0x80000001),
LocalMachine = unchecked((int)0x80000002),
Users = unchecked((int)0x80000003),
PerformanceData = unchecked((int)0x80000004),
CurrentConfig = unchecked((int)0x80000005),
}
}
|
mit
|
C#
|
d8dc79b78bc6848695d95b948ed6d946a34a7f8d
|
Fix polly sync/async policy Get issue
|
BrighterCommand/Darker
|
src/Paramore.Darker.Policies/RetryableQueryDecorator.cs
|
src/Paramore.Darker.Policies/RetryableQueryDecorator.cs
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Paramore.Darker.Exceptions;
using Paramore.Darker.Policies.Logging;
using Polly;
using Polly.Registry;
namespace Paramore.Darker.Policies
{
public class RetryableQueryDecorator<TQuery, TResult> : IQueryHandlerDecorator<TQuery, TResult>
where TQuery : IQuery<TResult>
{
private static readonly ILog _logger = LogProvider.GetLogger(typeof(RetryableQueryDecorator<,>));
private string _policyName;
public IQueryContext Context { get; set; }
public void InitializeFromAttributeParams(object[] attributeParams)
{
_policyName = (string)attributeParams[0];
if (!GetPolicyRegistry().ContainsKey(_policyName))
throw new ConfigurationException($"Policy does not exist in policy registry: {_policyName}");
}
public TResult Execute(TQuery query, Func<TQuery, TResult> next, Func<TQuery, TResult> fallback)
{
_logger.InfoFormat("Executing query with policy: {PolicyName}", _policyName);
return GetPolicyRegistry().Get<ISyncPolicy>(_policyName).Execute(() => next(query));
}
public async Task<TResult> ExecuteAsync(TQuery query,
Func<TQuery, CancellationToken, Task<TResult>> next,
Func<TQuery, CancellationToken, Task<TResult>> fallback,
CancellationToken cancellationToken = default(CancellationToken))
{
_logger.InfoFormat("Executing async query with policy: {PolicyName}", _policyName);
return await GetPolicyRegistry().Get<IAsyncPolicy>(_policyName)
.ExecuteAsync(ct => next(query, ct), cancellationToken, false)
.ConfigureAwait(false);
}
private IPolicyRegistry<string> GetPolicyRegistry()
{
if (!Context.Bag.ContainsKey(Constants.ContextBagKey))
throw new ConfigurationException($"Policy registry does not exist in context bag with key {Constants.ContextBagKey}.");
var policyRegistry = Context.Bag[Constants.ContextBagKey] as IPolicyRegistry<string>;
if (policyRegistry == null)
throw new ConfigurationException($"The policy registry in the context bag (with key {Constants.ContextBagKey}) must be of type {nameof(IPolicyRegistry<string>)}, but is {Context.Bag[Constants.ContextBagKey].GetType()}.");
return policyRegistry;
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Paramore.Darker.Exceptions;
using Paramore.Darker.Policies.Logging;
using Polly;
using Polly.Registry;
namespace Paramore.Darker.Policies
{
public class RetryableQueryDecorator<TQuery, TResult> : IQueryHandlerDecorator<TQuery, TResult>
where TQuery : IQuery<TResult>
{
private static readonly ILog _logger = LogProvider.GetLogger(typeof(RetryableQueryDecorator<,>));
private string _policyName;
public IQueryContext Context { get; set; }
public void InitializeFromAttributeParams(object[] attributeParams)
{
_policyName = (string)attributeParams[0];
if (!GetPolicyRegistry().ContainsKey(_policyName))
throw new ConfigurationException($"Policy does not exist in policy registry: {_policyName}");
}
public TResult Execute(TQuery query, Func<TQuery, TResult> next, Func<TQuery, TResult> fallback)
{
_logger.InfoFormat("Executing query with policy: {PolicyName}", _policyName);
return GetPolicyRegistry().Get<ISyncPolicy<TResult>>(_policyName).Execute(() => next(query));
}
public async Task<TResult> ExecuteAsync(TQuery query,
Func<TQuery, CancellationToken, Task<TResult>> next,
Func<TQuery, CancellationToken, Task<TResult>> fallback,
CancellationToken cancellationToken = default(CancellationToken))
{
_logger.InfoFormat("Executing async query with policy: {PolicyName}", _policyName);
return await GetPolicyRegistry().Get<IAsyncPolicy<TResult>>(_policyName)
.ExecuteAsync(ct => next(query, ct), cancellationToken, false)
.ConfigureAwait(false);
}
private IReadOnlyPolicyRegistry<string> GetPolicyRegistry()
{
if (!Context.Bag.ContainsKey(Constants.ContextBagKey))
throw new ConfigurationException($"Policy registry does not exist in context bag with key {Constants.ContextBagKey}.");
var policyRegistry = Context.Bag[Constants.ContextBagKey] as IPolicyRegistry<string>;
if (policyRegistry == null)
throw new ConfigurationException($"The policy registry in the context bag (with key {Constants.ContextBagKey}) must be of type {nameof(IPolicyRegistry<string>)}, but is {Context.Bag[Constants.ContextBagKey].GetType()}.");
return policyRegistry;
}
}
}
|
mit
|
C#
|
1417790bfbe5dcf43e0738ecae34ee421c68cd1e
|
Clean code
|
aloisdg/Doccou,aloisdg/CountPages,saidmarouf/Doccou
|
CountPages/MainWindow.xaml.cs
|
CountPages/MainWindow.xaml.cs
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using iTextSharp.text.pdf;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Window = System.Windows.Window;
namespace CountPages
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void DropList_Drop(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
try
{
var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
var count = paths.Select(path => new FileInfo(path))
//.Where(file => file.Extension.Equals(".pdf"))
.Sum(file => CountPages(file));
CountBlock.Text = count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static int CountPages(FileSystemInfo file)
{
if (file.Extension.Equals(".doc") || file.Extension.Equals(".docx"))
return CountWordPages(file);
if (file.Extension.Equals(".pdf"))
return CountPdfPages(file);
return 0;
}
public static int CountPdfPages(FileSystemInfo file)
{
try
{
var pdfReader = new PdfReader(file.FullName);
return pdfReader.NumberOfPages;
}
catch (Exception ex)
{
// we could skip and return 0.
throw new Exception(String.Format("There is a problem with {0}", file.FullName), ex);
}
}
public static int CountWordPages(FileSystemInfo file)
{
const WdStatistic stat = WdStatistic.wdStatisticPages;
_Application wordApp = new Application();
object fileName = file.FullName;
object readOnly = false;
object isVisible = true;
// the way to handle parameters you don't care about in .NET
object missing = Missing.Value;
// Make word visible, so you can see what's happening
//wordApp.Visible = true;
// Open the document that was chosen by the dialog
var aDoc = wordApp.Documents.Open(ref fileName,
ref missing, ref readOnly, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref isVisible);
return aDoc.ComputeStatistics(stat, ref missing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using iTextSharp.text.pdf;
using Microsoft.Office.Interop.Word;
using Window = System.Windows.Window;
namespace CountPages
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void DropList_Drop(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
try
{
var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
var count = paths.Select(path => new FileInfo(path))
//.Where(file => file.Extension.Equals(".pdf"))
.Sum(file => CountPages(file));
CountBlock.Text = count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static int CountPages(FileSystemInfo file)
{
if (file.Extension.Equals(".doc") || file.Extension.Equals(".docx"))
return CountWordPages(file);
if (file.Extension.Equals(".pdf"))
return CountPdfPages(file);
return 0;
}
public static int CountPdfPages(FileSystemInfo file)
{
try
{
var pdfReader = new PdfReader(file.FullName);
return pdfReader.NumberOfPages;
}
catch (Exception ex)
{
// we could skip and return 0.
throw new Exception(String.Format("There is a problem with {0}", file.FullName), ex);
}
}
public static int CountWordPages(FileSystemInfo file)
{
const WdStatistic stat = WdStatistic.wdStatisticPages;
_Application wordApp = new Microsoft.Office.Interop.Word.Application();
object fileName = file.FullName;
object readOnly = false;
object isVisible = true;
// the way to handle parameters you don't care about in .NET
object missing = System.Reflection.Missing.Value;
// Make word visible, so you can see what's happening
//wordApp.Visible = true;
// Open the document that was chosen by the dialog
var aDoc = wordApp.Documents.Open(ref fileName,
ref missing, ref readOnly, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref isVisible);
return aDoc.ComputeStatistics(stat, ref missing);
}
}
}
|
mit
|
C#
|
09dd21c598e54ce7ae3c8d4fe1452aecaa148bb0
|
Work around 0.11 beta breaking the Version and LocalVersion fields
|
canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor
|
src/SyncTrayzor/SyncThing/ApiClient/ItemStartedEvent.cs
|
src/SyncTrayzor/SyncThing/ApiClient/ItemStartedEvent.cs
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.ApiClient
{
public class ItemStartedEventDetails
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Flags")]
public long Flags { get; set; }
[JsonProperty("Modified")]
public long Modified { get; set; } // Is this supposed to be a DateTime?
// This changed in 0.11 beta, but it's not yet clear what do
// Since we don't use it anyway currently...
//[JsonProperty("Version")]
//public List<long> Version { get; set; }
// This changed in 0.11 beta, but it's not yet clear what do
// Since we don't use it anyway currently...
//[JsonProperty("LocalVersion")]
//public List<long> LocalVersion { get; set; }
[JsonProperty("NumBlocks")]
public long NumBlocks { get; set; }
}
public class ItemStartedEventData
{
[JsonProperty("item")]
public string Item { get; set; }
[JsonProperty("folder")]
public string Folder { get; set; }
[JsonProperty("details")]
public ItemStartedEventDetails Details { get; set; }
}
public class ItemStartedEvent : Event
{
[JsonProperty("data")]
public ItemStartedEventData Data { get; set; }
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return String.Format("<ItemStarted ID={0} Time={1} Item={2} Folder={3} Name={4} Flags={5} Modified={6} NumBlocks={7}>",
this.Id, this.Time, this.Data.Item, this.Data.Folder, this.Data.Details.Name, this.Data.Details.Flags, this.Data.Details.Modified, this.Data.Details.NumBlocks);
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SyncTrayzor.SyncThing.ApiClient
{
public class ItemStartedEventDetails
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Flags")]
public long Flags { get; set; }
[JsonProperty("Modified")]
public long Modified { get; set; } // Is this supposed to be a DateTime?
[JsonProperty("Version")]
public long Version { get; set; }
[JsonProperty("LocalVersion")]
public long LocalVersion { get; set; }
[JsonProperty("NumBlocks")]
public long NumBlocks { get; set; }
}
public class ItemStartedEventData
{
[JsonProperty("item")]
public string Item { get; set; }
[JsonProperty("folder")]
public string Folder { get; set; }
[JsonProperty("details")]
public ItemStartedEventDetails Details { get; set; }
}
public class ItemStartedEvent : Event
{
[JsonProperty("data")]
public ItemStartedEventData Data { get; set; }
public override void Visit(IEventVisitor visitor)
{
visitor.Accept(this);
}
public override string ToString()
{
return String.Format("<ItemStarted ID={0} Time={1} Item={2} Folder={3} Name={4} Flags={5} Modified={6} Version={7} LocalVersion={8} NumBlocks={9}>",
this.Id, this.Time, this.Data.Item, this.Data.Folder, this.Data.Details.Name, this.Data.Details.Flags, this.Data.Details.Modified,
this.Data.Details.Version, this.Data.Details.LocalVersion, this.Data.Details.NumBlocks);
}
}
}
|
mit
|
C#
|
a038fc6a6134e6c0c971fd165d82213acb98f5aa
|
Change to 3 digit version
|
travelrepublic/TravelRepublic.DnsClient
|
src/TravelRepublic.DnsClient/Properties/AssemblyInfo.cs
|
src/TravelRepublic.DnsClient/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("TravelRepublic.DnsClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("TravelRepublic.DnsClient")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("74571bca-0f31-4ce7-82e8-85e0594f2f0e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: InternalsVisibleTo("TravelRepublic.DnsClient.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("TravelRepublic.DnsClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("TravelRepublic.DnsClient")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("74571bca-0f31-4ce7-82e8-85e0594f2f0e")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
[assembly: InternalsVisibleTo("TravelRepublic.DnsClient.Tests")]
|
bsd-3-clause
|
C#
|
af825511fa6eab81f8a1128e1ae94b4d349b935f
|
Fix more race conditions between tests
|
HeadhunterXamd/VisualStudio,github/VisualStudio,github/VisualStudio,github/VisualStudio,luizbon/VisualStudio
|
src/UnitTests/GitHub.Api/SimpleApiClientFactoryTests.cs
|
src/UnitTests/GitHub.Api/SimpleApiClientFactoryTests.cs
|
using System;
using GitHub.Api;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.VisualStudio;
using NSubstitute;
using Xunit;
public class SimpleApiClientFactoryTests
{
public class TheCreateMethod
{
[Fact]
public void CreatesNewInstanceOfSimpleApiClient()
{
const string url = "https://github.com/github/CreatesNewInstanceOfSimpleApiClient";
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = factory.Create(url);
Assert.Equal(url, client.OriginalUrl);
Assert.Equal(HostAddress.GitHubDotComHostAddress, client.HostAddress);
Assert.Same(client, factory.Create(url)); // Tests caching.
}
}
public class TheClearFromCacheMethod
{
[Fact]
public void RemovesClientFromCache()
{
const string url = "https://github.com/github/RemovesClientFromCache";
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = factory.Create(url);
factory.ClearFromCache(client);
Assert.NotSame(client, factory.Create(url));
}
}
}
|
using System;
using GitHub.Api;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.VisualStudio;
using NSubstitute;
using Xunit;
public class SimpleApiClientFactoryTests
{
public class TheCreateMethod
{
[Fact]
public void CreatesNewInstanceOfSimpleApiClient()
{
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = factory.Create("https://github.com/github/visualstudio");
Assert.Equal("https://github.com/github/visualstudio", client.OriginalUrl);
Assert.Equal(HostAddress.GitHubDotComHostAddress, client.HostAddress);
Assert.Same(client, factory.Create("https://github.com/github/visualstudio")); // Tests caching.
}
}
public class TheClearFromCacheMethod
{
[Fact]
public void RemovesClientFromCache()
{
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = factory.Create("https://github.com/github/visualstudio");
factory.ClearFromCache(client);
Assert.NotSame(client, factory.Create("https://github.com/github/visualstudio"));
}
}
}
|
mit
|
C#
|
00999300f015a38a0a07bab84fd89e7d8cde97a1
|
Fix claim failed bug
|
joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
|
Joinrpg/Views/Shared/_ListOperationsDropdown.cshtml
|
Joinrpg/Views/Shared/_ListOperationsDropdown.cshtml
|
@if (ViewBag.HideOperations == true)
{
return;
}
<div class="btn-group" style="padding: 1em">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Операции <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<a href="?export=xlsx"
title="Экспорт в Excel">
<span class="glyphicon glyphicon-download"></span>
Скачать в Excel
</a>
</li>
@if (ViewBag.ClaimIds != null && ViewBag.ProjectId != null)
{
<li>
@{
var claimIds = "&claimIds=" + string.Join(",", ((int[]) ViewBag.ClaimIds).Select(c => c.ToString()));
}
<a href="@Url.Action("ForClaims", "MassMail", new {ViewBag.ProjectId})@claimIds">
<span class="glyphicon glyphicon-envelope"></span>
Написать всем
</a>
</li>
}
</ul>
</div>
|
@if (ViewBag.HideOperations == true)
{
return;
}
<div class="btn-group" style="padding: 1em">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Операции <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<a href="?export=xlsx"
title="Экспорт в Excel">
<span class="glyphicon glyphicon-download"></span>
Скачать в Excel
</a>
</li>
@if (ViewBag.ClaimIds != null && ViewBag.ProjectId != null)
{
<li>
@{
var claimIds = "&claimIds=" + string.Join(",", ((int?[]) ViewBag.ClaimIds).Select(c => c.ToString()));
}
<a href="@Url.Action("ForClaims", "MassMail", new {ViewBag.ProjectId})@claimIds">
<span class="glyphicon glyphicon-envelope"></span>
Написать всем
</a>
</li>
}
</ul>
</div>
|
mit
|
C#
|
84cebcdc1d49c04c1060fa779b4872b2f208c233
|
Change controller action to debug Kudu issue https://github.com/projectkudu/kudu/issues/1567
|
ShamsulAmry/Malaysia-GST-Checker
|
Amry.Gst.Web/Controllers/HomeController.cs
|
Amry.Gst.Web/Controllers/HomeController.cs
|
using System.Web.Mvc;
using Amry.Gst.Properties;
using WebMarkupMin.Mvc.ActionFilters;
namespace Amry.Gst.Web.Controllers
{
public class HomeController : Controller
{
const int OneYear = 31536000;
[Route, MinifyHtml]
public ActionResult Index()
{
return View();
}
[Route("about"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult About()
{
return View();
}
[Route("api"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult Api()
{
return View();
}
[Route("ver")]
public ActionResult Version()
{
return Content("Version: " + AssemblyInfoConstants.Version, "text/plain");
}
}
}
|
using System.Web.Mvc;
using Amry.Gst.Properties;
using WebMarkupMin.Mvc.ActionFilters;
namespace Amry.Gst.Web.Controllers
{
public class HomeController : Controller
{
const int OneYear = 31536000;
[Route, MinifyHtml]
public ActionResult Index()
{
return View();
}
[Route("about"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult About()
{
return View();
}
[Route("api"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult Api()
{
return View();
}
[Route("ver")]
public ActionResult Version()
{
return Content(AssemblyInfoConstants.Version, "text/plain");
}
}
}
|
mit
|
C#
|
34f19c3b700b2eb058c29c25bce65a629f867c06
|
Update WalletWasabi/Services/Terminate/TerminateService.cs
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Services/Terminate/TerminateService.cs
|
WalletWasabi/Services/Terminate/TerminateService.cs
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private readonly Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateStatusFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning($"Process termination was requested using '{e.SpecialKey}' keyboard shortcut.");
// This must be a blocking call because after this the OS will terminate Wasabi process if it exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Start shutting down the application.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateStatusFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning($"Process termination was requested using '{e.SpecialKey}' keyboard shortcut.");
// This must be a blocking call because after this the OS will terminate Wasabi process if it exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Start shutting down the application.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
|
mit
|
C#
|
4e87c9ae7266a306ae0dac984ad78828ae089c2d
|
Update SeasonConverter for the 2018 season (#522)
|
JanOuborny/RiotSharp,BenFradet/RiotSharp,Oucema90/RiotSharp
|
RiotSharp/Endpoints/MatchEndpoint/Enums/Converters/SeasonConverter.cs
|
RiotSharp/Endpoints/MatchEndpoint/Enums/Converters/SeasonConverter.cs
|
using System;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RiotSharp.Endpoints.MatchEndpoint.Enums.Converters
{
class SeasonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(string).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var token = JToken.Load(reader);
if (token.Value<int>() == 0) return null;
var nbr = token.Value<int>();
switch (nbr)
{
case 0:
return Season.PreSeason3;
case 1:
return Season.Season3;
case 2:
return Season.PreSeason2014;
case 3:
return Season.Season2014;
case 4:
return Season.PreSeason2015;
case 5:
return Season.Season2015;
case 6:
return Season.PreSeason2016;
case 7:
return Season.Season2016;
case 8:
return Season.PreSeason2017;
case 9:
return Season.Season2017;
case 10:
return Season.PreSeason2018;
case 11:
return Season.Season2018;
default:
return null;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((Season)value));
}
}
}
|
using System;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RiotSharp.Endpoints.MatchEndpoint.Enums.Converters
{
class SeasonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(string).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var token = JToken.Load(reader);
if (token.Value<int>() == 0) return null;
var nbr = token.Value<int>();
switch (nbr)
{
case 0:
return Season.PreSeason3;
case 1:
return Season.Season3;
case 2:
return Season.PreSeason2014;
case 3:
return Season.Season2014;
case 4:
return Season.PreSeason2015;
case 5:
return Season.Season2015;
case 6:
return Season.PreSeason2016;
case 7:
return Season.Season2016;
case 8:
return Season.PreSeason2017;
case 9:
return Season.Season2017;
default:
return null;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((Season)value));
}
}
}
|
mit
|
C#
|
113fa59ed5964e6a72989d9859dc7bc391f849cb
|
Update Model
|
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/Standard.cs
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/Standard.cs
|
using System;
using System.Collections.Generic;
namespace SFA.DAS.CommitmentsV2.Models
{
public class Standard
{
public string StandardUId { get; set; }
public int LarsCode { get; set; }
public string IFateReferenceNumber { get; set; }
public string Title { get; set; }
public string Version { get; set; }
public int Level { get; set; }
public int Duration { get; set; }
public int MaxFunding { get; set; }
public DateTime? EffectiveFrom { get; set; }
public DateTime? EffectiveTo { get; set; }
public virtual List<StandardFundingPeriod> FundingPeriods { get; set; }
public bool IsLatestVersion { get; set; }
public int VersionMajor { get; set; }
public int VersionMinor { get; set; }
public string StandardPageUrl { get; set; }
}
public class StandardFundingPeriod : IFundingPeriod
{
public int Id { get; set; }
public DateTime? EffectiveFrom { get; set; }
public DateTime? EffectiveTo { get; set; }
public int FundingCap { get; set; }
public virtual Standard Standard { get ; set ; }
}
}
|
using System;
using System.Collections.Generic;
namespace SFA.DAS.CommitmentsV2.Models
{
public class Standard
{
public string StandardUId { get; set; }
public int LarsCode { get; set; }
public string IFateReferenceNumber { get; set; }
public string Title { get; set; }
public string Version { get; set; }
public int Level { get; set; }
public int Duration { get; set; }
public int MaxFunding { get; set; }
public DateTime? EffectiveFrom { get; set; }
public DateTime? EffectiveTo { get; set; }
public virtual List<StandardFundingPeriod> FundingPeriods { get; set; }
public bool IsLatestVersion { get; set; }
public string StandardPageUrl { get; set; }
}
public class StandardFundingPeriod : IFundingPeriod
{
public int Id { get; set; }
public DateTime? EffectiveFrom { get; set; }
public DateTime? EffectiveTo { get; set; }
public int FundingCap { get; set; }
public virtual Standard Standard { get ; set ; }
}
}
|
mit
|
C#
|
42a6bc1d6dfdde06f17901eb6b5668070b660737
|
switch enum memory space
|
jefking/King.Service
|
King.Service/Data/Enums.cs
|
King.Service/Data/Enums.cs
|
namespace King.Service.Data
{
/// <summary>
/// Queue Priority
/// </summary>
/// <remarks>
/// This shapes
/// - Timing Strategy
/// - Concurrency
/// - Cost
/// - Throughput
/// Default = Low
/// </remarks>
public enum QueuePriority : byte
{
Low = 0,
Medium = 1,
High = 2,
}
}
|
namespace King.Service.Data
{
/// <summary>
/// Queue Priority
/// </summary>
/// <remarks>
/// This shapes
/// - Timing Strategy
/// - Concurrency
/// - Cost
/// - Throughput
/// Default = Low
/// </remarks>
public enum QueuePriority
{
Low = 0,
Medium = 1,
High = 2,
}
}
|
mit
|
C#
|
da8cdf2158244021de3d58a6a65e84bd6fc9f5b3
|
Update package version.
|
mfilippov/DbSeedGenerator
|
DbSeedGenerator/Properties/AssemblyInfo.cs
|
DbSeedGenerator/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DbSeedGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sky@Net")]
[assembly: AssemblyProduct("DbSeedGenerator")]
[assembly: AssemblyCopyright("Copyright © Mikhail Filippov 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("79400718-13dc-44f7-9412-8bdfafc0990f")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DbSeedGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sky@Net")]
[assembly: AssemblyProduct("DbSeedGenerator")]
[assembly: AssemblyCopyright("Copyright © Mikhail Filippov 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("79400718-13dc-44f7-9412-8bdfafc0990f")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
bsd-2-clause
|
C#
|
292851d11d63f53e4c371614a454a12dd465e38d
|
Make the PreviewWorkspace optional for DisposableToolTip
|
KirillOsenkov/roslyn,diryboy/roslyn,abock/roslyn,genlu/roslyn,agocke/roslyn,stephentoub/roslyn,bartdesmet/roslyn,wvdd007/roslyn,aelij/roslyn,eriawan/roslyn,KevinRansom/roslyn,tmat/roslyn,VSadov/roslyn,brettfo/roslyn,heejaechang/roslyn,aelij/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,davkean/roslyn,abock/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,wvdd007/roslyn,eriawan/roslyn,AmadeusW/roslyn,stephentoub/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,DustinCampbell/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,reaction1989/roslyn,davkean/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,jcouv/roslyn,wvdd007/roslyn,abock/roslyn,heejaechang/roslyn,eriawan/roslyn,VSadov/roslyn,gafter/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,nguerrera/roslyn,mavasani/roslyn,diryboy/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,aelij/roslyn,weltkante/roslyn,AmadeusW/roslyn,dotnet/roslyn,MichalStrehovsky/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,mavasani/roslyn,stephentoub/roslyn,genlu/roslyn,KevinRansom/roslyn,agocke/roslyn,tmat/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,physhi/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,panopticoncentral/roslyn,jcouv/roslyn,diryboy/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,brettfo/roslyn,davkean/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,brettfo/roslyn,genlu/roslyn,tmat/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,physhi/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,tannergooding/roslyn,bartdesmet/roslyn,jmarolf/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,reaction1989/roslyn,jcouv/roslyn
|
src/EditorFeatures/Core.Wpf/QuickInfo/DisposableToolTip.cs
|
src/EditorFeatures/Core.Wpf/QuickInfo/DisposableToolTip.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
namespace Microsoft.CodeAnalysis.Editor.QuickInfo
{
internal sealed class DisposableToolTip : IDisposable
{
public readonly ToolTip ToolTip;
private PreviewWorkspace _workspaceOpt;
private bool _disposed;
public DisposableToolTip(ToolTip toolTip, PreviewWorkspace workspaceOpt)
{
ToolTip = toolTip;
_workspaceOpt = workspaceOpt;
}
public void Dispose()
{
Debug.Assert(!_disposed);
_disposed = true;
_workspaceOpt?.Dispose();
_workspaceOpt = null;
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
namespace Microsoft.CodeAnalysis.Editor.QuickInfo
{
internal sealed class DisposableToolTip : IDisposable
{
public readonly ToolTip ToolTip;
private PreviewWorkspace _workspace;
private bool _disposed;
public DisposableToolTip(ToolTip toolTip, PreviewWorkspace workspace)
{
ToolTip = toolTip;
_workspace = workspace;
}
public void Dispose()
{
Debug.Assert(!_disposed);
_disposed = true;
_workspace.Dispose();
_workspace = null;
}
}
}
|
mit
|
C#
|
9910749ee24c0c163c9a5c346ff9951648139c57
|
Replace default script methods with Update & FixedUpdate methods
|
compumike08/Roll-a-Ball
|
Assets/Scripts/PlayerController.cs
|
Assets/Scripts/PlayerController.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
// Update is called before rendering a frame
void Update ()
{
}
// FixedUpdate is called just before performing any physics calculations
void FixedUpdate ()
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
mit
|
C#
|
4d73c5062891460d51f56b2252db1285405fd3ef
|
Edit AdvancingText to use TextMesh Pro
|
NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
|
Assets/Scripts/UI/AdvancingText.cs
|
Assets/Scripts/UI/AdvancingText.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using TMPro;
public class AdvancingText : MonoBehaviour
{
private const string richTextPrefix = "<color=#00000000>";
private const string richTextSuffix = "</color>";
[SerializeField]
private float advanceSpeed;
[SerializeField]
private UnityEvent onComplete;
private TextMeshProUGUI textMeshPro;
private float progress;
private string textString;
void Start ()
{
textMeshPro = GetComponent<TextMeshProUGUI>();
progress = -1f;
resetAdvance();
}
public void resetAdvance()
{
textString = getUnformattedText();
progress = 0f;
enabled = true;
textMeshPro.text = getFittedText(textString, 0);
}
void Update ()
{
if (progress < 0f)
resetAdvance();
if (progress < textString.Length)
updateText();
}
void updateText()
{
textString = getUnformattedText();
progress = Mathf.MoveTowards(progress, textString.Length, Time.deltaTime * advanceSpeed);
textMeshPro.text = getFittedText(textString, (int)Mathf.Floor(progress));
if (progress >= textString.Length)
onComplete.Invoke();
}
public string getFittedText(string textString, int visibleChars)
{
if (visibleChars >= textString.Length)
return textString;
return textString.Substring(0, visibleChars) + richTextPrefix
+ textString.Substring(visibleChars, textString.Length - visibleChars) + richTextSuffix;
}
public string getUnformattedText()
{
return textMeshPro.text.Replace(richTextPrefix, "").Replace(richTextSuffix, "");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class AdvancingText : MonoBehaviour
{
private const string richTextPrefix = "<color=#00000000>";
private const string richTextSuffix = "</color>";
[SerializeField]
private float advanceSpeed;
[SerializeField]
bool dontLocalize;
[SerializeField]
private UnityEvent onComplete;
private Text textComponent;
private LocalizedText localizedText;
private float progress;
private string textString;
void Start ()
{
textComponent = GetComponent<Text>();
localizedText = GetComponent<LocalizedText>();
resetAdvance();
}
public void resetAdvance()
{
if (localizedText != null && !dontLocalize)
{
textComponent.text = TextHelper.getLocalizedText(localizedText.key, textComponent.text);
localizedText.updateText();
}
textString = textComponent.text.Replace(richTextPrefix, "").Replace(richTextSuffix, "");
progress = 0f;
enabled = true;
textComponent.text = getFittedText(textString, 0);
}
void Update ()
{
if (progress < textString.Length)
updateText();
}
void updateText()
{
progress = Mathf.MoveTowards(progress, textString.Length, Time.deltaTime * advanceSpeed);
textComponent.text = getFittedText(textString, (int)Mathf.Floor(progress));
if (progress >= textString.Length)
onComplete.Invoke();
}
public string getFittedText(string textString, int visibleChars)
{
if (visibleChars >= textString.Length)
return textString;
return textString.Substring(0, visibleChars) + richTextPrefix
+ textString.Substring(visibleChars, textString.Length - visibleChars) + richTextSuffix;
}
}
|
mit
|
C#
|
c9f38dfc9a8a26876b9e2b2e989f4ec0cdad89c7
|
Set default result count of a recipe to 1
|
kmclarnon/FactorioModBuilder
|
FactorioModBuilder/Models/ProjectItems/Prototype/Recipe.cs
|
FactorioModBuilder/Models/ProjectItems/Prototype/Recipe.cs
|
using FactorioModBuilder.Models.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactorioModBuilder.Models.ProjectItems.Prototype
{
public class Recipe : TreeItem<Recipe>
{
public bool Enabled { get; set; }
public int EnergyRequired { get; set; }
public string Result { get; set; }
public int ResultCount { get; set; }
public Recipe(string name) : base(name)
{
this.ResultCount = 1;
}
}
}
|
using FactorioModBuilder.Models.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactorioModBuilder.Models.ProjectItems.Prototype
{
public class Recipe : TreeItem<Recipe>
{
public bool Enabled { get; set; }
public int EnergyRequired { get; set; }
public string Result { get; set; }
public int ResultCount { get; set; }
public Recipe(string name) : base(name)
{
}
}
}
|
mit
|
C#
|
1c66cbe9bf24d85480adcf67b357137028d30999
|
Update DriverInfo.cs
|
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
|
src/RasterIO.Gdal/DriverInfo.cs
|
src/RasterIO.Gdal/DriverInfo.cs
|
// Contributors:
// James Domingo, Green Code LLC
using System;
using OSGeo.GDAL;
namespace Landis.SpatialModeling.CoreServices
{
public class DriverInfo
{
private string shortName;
private string longName;
private bool hasCreate;
private bool hasCreateCopy;
public string ShortName { get { return shortName; } }
public string LongName { get { return longName; } }
public bool HasCreate { get { return hasCreate; } }
public bool HasCreateCopy { get { return hasCreateCopy; } }
public DriverInfo(Driver gdalDriver)
{
shortName = gdalDriver.ShortName;
longName = gdalDriver.LongName;
hasCreate = GetMetadataItem(gdalDriver, "DCAP_CREATE") == "YES";
hasCreateCopy = GetMetadataItem(gdalDriver, "DCAP_CREATECOPY") == "YES";
}
private string GetMetadataItem(Driver gdalDriver,
string itemName)
{
string itemValue = gdalDriver.GetMetadataItem(itemName, "");
return itemValue;
}
public static int CompareShortName(DriverInfo x,
DriverInfo y)
{
return x.ShortName.CompareTo(y.ShortName);
}
}
}
|
// Copyright 2010 Green Code LLC
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, Green Code LLC
using System;
using OSGeo.GDAL;
namespace Landis.SpatialModeling.CoreServices
{
public class DriverInfo
{
private string shortName;
private string longName;
private bool hasCreate;
private bool hasCreateCopy;
public string ShortName { get { return shortName; } }
public string LongName { get { return longName; } }
public bool HasCreate { get { return hasCreate; } }
public bool HasCreateCopy { get { return hasCreateCopy; } }
public DriverInfo(Driver gdalDriver)
{
shortName = gdalDriver.ShortName;
longName = gdalDriver.LongName;
hasCreate = GetMetadataItem(gdalDriver, "DCAP_CREATE") == "YES";
hasCreateCopy = GetMetadataItem(gdalDriver, "DCAP_CREATECOPY") == "YES";
}
private string GetMetadataItem(Driver gdalDriver,
string itemName)
{
string itemValue = gdalDriver.GetMetadataItem(itemName, "");
return itemValue;
}
public static int CompareShortName(DriverInfo x,
DriverInfo y)
{
return x.ShortName.CompareTo(y.ShortName);
}
}
}
|
apache-2.0
|
C#
|
5e34014f73ddff8a256e9792c2a452cee7e446f7
|
Update AssemblyInfo.cs
|
Sitefinity-SDK/Sitefinity.Authentication,Sitefinity-SDK/Sitefinity.Authentication,Sitefinity-SDK/Sitefinity.Authentication
|
MVCImplicitFlow/Properties/AssemblyInfo.cs
|
MVCImplicitFlow/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("MVCImplicitFlow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MVCImplicitFlow")]
[assembly: AssemblyCopyright("Copyright © 2005-2019 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved.")]
[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("bb625cc2-5732-44a1-8892-95fcfb232c49")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MVCImplicitFlow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MVCImplicitFlow")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb625cc2-5732-44a1-8892-95fcfb232c49")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
310f2dcefc2f82ba13831e00f1a55410cedaccbc
|
Add constractor to Logger
|
eternnoir/NLogging
|
src/NLogging/Logger.cs
|
src/NLogging/Logger.cs
|
namespace NLogging
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Logger
{
private string loggerName;
public string LoggerName
{
get
{
return this.loggerName;
}
}
public Logger(string loggerName)
{
this.loggerName = loggerName;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NLogging
{
class Logger
{
}
}
|
mit
|
C#
|
4e6d5ccccaf82d0f9f25226e307f59ff57f9b544
|
Update Program.cs #3
|
tvert/GitTest1
|
ConsoleApp1/ConsoleApp1/Program.cs
|
ConsoleApp1/ConsoleApp1/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Code amended in GitHub
// Code amended #2 in GitHub
// Code amended #3 in GitHub
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Code amended in GitHub
// Code amended #2 in GitHub
}
}
}
|
mit
|
C#
|
a47ae74d13d8441a06aa35b36777c545f273c023
|
Update Program.cs
|
miladinoviczeljko/GitTest1
|
ConsoleApp1/ConsoleApp1/Program.cs
|
ConsoleApp1/ConsoleApp1/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Code was edited in GitHub
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Code was added in GitHub
}
}
}
|
mit
|
C#
|
3985661d31a22085dec776317d7f67d706151a34
|
move namespace
|
campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,BreeeZe/NuGetPackageExplorer
|
Core/Utility/PackageIdValidator.cs
|
Core/Utility/PackageIdValidator.cs
|
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using NuGet.Resources;
using NuGetPackageExplorer.Types;
namespace NuGet
{
public static class PackageIdValidator
{
public const int MaxPackageIdLength = 100;
private static readonly Regex _idRegex = new Regex(@"^\w+([_.-]\w+)*$", RegexOptions.IgnoreCase);
public static bool IsValidPackageId(string packageId)
{
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
return (packageId.Length <= MaxPackageIdLength) && _idRegex.IsMatch(packageId) || ReplacementTokens.AllReplacementTokens.Contains(packageId);
}
public static void ValidatePackageId(string packageId)
{
if (packageId.Length > MaxPackageIdLength)
{
throw new ArgumentException(NuGetResources.Manifest_IdMaxLengthExceeded);
}
if (!IsValidPackageId(packageId))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InvalidPackageId,
packageId));
}
}
}
}
|
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using NuGet.Resources;
using NuGet.Utility;
namespace NuGet
{
public static class PackageIdValidator
{
public const int MaxPackageIdLength = 100;
private static readonly Regex _idRegex = new Regex(@"^\w+([_.-]\w+)*$", RegexOptions.IgnoreCase);
public static bool IsValidPackageId(string packageId)
{
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
return (packageId.Length <= MaxPackageIdLength) && _idRegex.IsMatch(packageId) || ReplacementTokens.AllReplacementTokens.Contains(packageId);
}
public static void ValidatePackageId(string packageId)
{
if (packageId.Length > MaxPackageIdLength)
{
throw new ArgumentException(NuGetResources.Manifest_IdMaxLengthExceeded);
}
if (!IsValidPackageId(packageId))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InvalidPackageId,
packageId));
}
}
}
}
|
mit
|
C#
|
21ff2a24618e0cd441c55fd52bc04cad7f2cccea
|
Update AssemblyInfo.cs
|
Seuntjie900/DiceBot
|
DiceBot/Properties/AssemblyInfo.cs
|
DiceBot/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("DiceBot")]
[assembly: AssemblyDescription("Automatic and flexible Betting bot for all the big dice sites")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Botma Software (Pty) Ltd")]
[assembly: AssemblyProduct("DiceBot")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("c30dabf9-82ae-4bf5-91ef-c66e755bff85")]
// 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("3.4.9.0")]
[assembly: AssemblyFileVersion("3.4.9.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DiceBot")]
[assembly: AssemblyDescription("Automatic and flexible Betting bot for all the big dice sites")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Botma Software (Pty) Ltd")]
[assembly: AssemblyProduct("DiceBot")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("c30dabf9-82ae-4bf5-91ef-c66e755bff85")]
// 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("3.4.7.0")]
[assembly: AssemblyFileVersion("3.4.7.0")]
|
mit
|
C#
|
e2fa37dd9c90a8c818a123207efa4a8d08d60dc6
|
Change the assembly file version the same as assembly version, as Gendarme suggested
|
aegif/chemistry-dotcmis,OpenDataSpace/chemistry-dotcmis
|
DotCMIS/Properties/AssemblyInfo.cs
|
DotCMIS/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("DotCMIS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Apache Software Foundation")]
[assembly: AssemblyProduct("DotCMIS")]
[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("ac118463-00ec-4e63-8c93-b45760f9abcf")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DotCMIS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Apache Software Foundation")]
[assembly: AssemblyProduct("DotCMIS")]
[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("ac118463-00ec-4e63-8c93-b45760f9abcf")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
c2d4802dd869754ebda15914d52011000b9437ea
|
Update Assembly properties to version 2.0
|
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Spartan322/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Spartan322/Hacknet-Pathfinder
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("HacknetPathfinder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("2.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("HacknetPathfinder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
mit
|
C#
|
17c0afc3745771ba1b152e48dc580e1ad9d52ba1
|
Bump to 2.8.1
|
dreadnought-friends/support-tool
|
Properties/AssemblyInfo.cs
|
Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dreadnought Community Support Tool")]
[assembly: AssemblyDescription("This community made tool gathers information which the Dreadnought Customer Support might ask of you to assist with issues or bug reports.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("support-tool")]
[assembly: AssemblyCopyright("Copyright Anyone © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.8.1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dreadnought Community Support Tool")]
[assembly: AssemblyDescription("This community made tool gathers information which the Dreadnought Customer Support might ask of you to assist with issues or bug reports.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("support-tool")]
[assembly: AssemblyCopyright("Copyright Anyone © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.8.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
6e2d64de08a44ff2870cb9e258f497d7b7255e61
|
Tweak to keep ReSharper happy
|
taylorjg/FsCheckUtils
|
FsCheckUtils/GenExtensions.cs
|
FsCheckUtils/GenExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using FsCheck;
using FsCheck.Fluent;
namespace FsCheckUtils
{
public static class GenExtensions
{
public static Gen<List<T>> Pick<T>(int n, IReadOnlyCollection<T> l)
{
if (n < 0 || n > l.Count) throw new ArgumentOutOfRangeException("n");
Func<List<T>, List<int>, List<T>> removeItems = (b, idxs) =>
{
foreach (var idx in idxs) b.RemoveAt(idx % b.Count);
return b;
};
var numItemsToRemove = l.Count - n;
return
from idxs in Any.IntBetween(0, l.Count * 10).MakeListOfLength(numItemsToRemove)
select removeItems(new List<T>(l), idxs);
}
public static Gen<List<T>> Pick<T>(int n, params Gen<T>[] gs)
{
var genIdxs = Pick(n, (IReadOnlyCollection<int>) Enumerable.Range(0, gs.Length).ToArray());
return genIdxs.SelectMany(idxs => Any.SequenceOf(idxs.Select(x => gs[x])));
}
public static Gen<List<T>> SomeOf<T>(IReadOnlyCollection<T> l)
{
return Gen.choose(0, l.Count).SelectMany(n => Pick(n, l));
}
public static Gen<List<T>> SomeOf<T>(params Gen<T>[] gs)
{
return Gen.choose(0, gs.Length).SelectMany(n => Pick(n, gs));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using FsCheck;
using FsCheck.Fluent;
namespace FsCheckUtils
{
public static class GenExtensions
{
public static Gen<List<T>> Pick<T>(int n, IReadOnlyCollection<T> l)
{
if (n < 0 || n > l.Count) throw new ArgumentOutOfRangeException("n");
Func<List<T>, List<int>, List<T>> removeItems = (b, idxs) =>
{
foreach (var idx in idxs) b.RemoveAt(idx % b.Count);
return b;
};
var numItemsToRemove = l.Count - n;
return
from idxs in Any.IntBetween(0, l.Count * 10).MakeListOfLength(numItemsToRemove)
select removeItems(new List<T>(l), idxs);
}
public static Gen<List<T>> Pick<T>(int n, params Gen<T>[] gs)
{
var genIdxs = Pick(n, Enumerable.Range(0, gs.Length).ToArray());
return genIdxs.SelectMany(idxs => Any.SequenceOf(idxs.Select(x => gs[x])));
}
public static Gen<List<T>> SomeOf<T>(IReadOnlyCollection<T> l)
{
return Gen.choose(0, l.Count).SelectMany(n => Pick(n, l));
}
public static Gen<List<T>> SomeOf<T>(params Gen<T>[] gs)
{
return Gen.choose(0, gs.Length).SelectMany(n => Pick(n, gs));
}
}
}
|
mit
|
C#
|
210a47145891c88f04409a046309aa63046da488
|
Add Filter(name,value) constructor
|
carbon/Amazon
|
src/Amazon.Ec2/Actions/Filter.cs
|
src/Amazon.Ec2/Actions/Filter.cs
|
using System;
namespace Amazon.Ec2
{
public readonly struct Filter
{
public Filter(string name, string value)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Value = value ?? throw new ArgumentNullException(nameof(value));
}
public Filter(string name, bool value)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Value = value ? "true" : "false";
}
public string Name { get; }
public string Value { get; }
}
}
|
using System;
namespace Amazon.Ec2
{
public readonly struct Filter
{
public Filter(string name, string value)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Value = value ?? throw new ArgumentNullException(nameof(value));
}
public string Name { get; }
public string Value { get; }
}
}
|
mit
|
C#
|
ed397b865dae569b1555acd25f16513885899ae2
|
Update src/SFA.DAS.EAS.Portal.UnitTests/Application/Adapters/CohortAdapterTests.cs
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EAS.Portal.UnitTests/Application/Adapters/CohortAdapterTests.cs
|
src/SFA.DAS.EAS.Portal.UnitTests/Application/Adapters/CohortAdapterTests.cs
|
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Messages.Events;
using SFA.DAS.EAS.Portal.Application.Adapters;
using FluentAssertions;
using System;
using SFA.DAS.EAS.Portal.UnitTests.Builders;
namespace SFA.DAS.EAS.Portal.UnitTests.Application.Adapters
{
[Parallelizable]
[TestFixture]
public class CohortAdapterTests
{
private readonly CohortAdapter _sut;
public CohortAdapterTests()
{
_sut = new CohortAdapter();
}
[Test]
public void WhenConvertCalled_ThenTheEventIsMappedToTheCommand()
{
// arrange
CohortApprovalRequestedByProvider @event = new CohortApprovalRequestedByProviderBuilder();
// act
var result = _sut.Convert(@event);
//assert
result.AccountId.Should().Be(@event.AccountId);
result.ProviderId.Should().Be(@event.ProviderId);
result.CommitmentId.Should().Be(@event.CommitmentId);
}
}
}
|
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Messages.Events;
using SFA.DAS.EAS.Portal.Application.Adapters;
using FluentAssertions;
using System;
using SFA.DAS.EAS.Portal.UnitTests.Builders;
namespace SFA.DAS.EAS.Portal.UnitTests.Application.Adapters
{
[Parallelizable]
[TestFixture]
public class CohortAdapterTests
{
private CohortAdapter _sut;
public CohortAdapterTests()
{
_sut = new CohortAdapter();
}
[Test]
public void WhenConvertCalled_ThenTheEventIsMappedToTheCommand()
{
// arrange
CohortApprovalRequestedByProvider @event = new CohortApprovalRequestedByProviderBuilder();
// act
var result = _sut.Convert(@event);
//assert
result.AccountId.Should().Be(@event.AccountId);
result.ProviderId.Should().Be(@event.ProviderId);
result.CommitmentId.Should().Be(@event.CommitmentId);
}
}
}
|
mit
|
C#
|
f8f9cf3b394d2c0039ed0d69e2c3a9c1e3f905bb
|
Add test trace output to webforms page
|
codevlabs/Glimpse,SusanaL/Glimpse,Glimpse/Glimpse,rho24/Glimpse,sorenhl/Glimpse,flcdrg/Glimpse,elkingtonmcb/Glimpse,gabrielweyer/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,Glimpse/Glimpse,codevlabs/Glimpse,flcdrg/Glimpse,flcdrg/Glimpse,gabrielweyer/Glimpse,dudzon/Glimpse,sorenhl/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,SusanaL/Glimpse,dudzon/Glimpse,dudzon/Glimpse,paynecrl97/Glimpse,codevlabs/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,paynecrl97/Glimpse
|
source/Glimpse.WebForms.WingTip.Sample/Default.aspx.cs
|
source/Glimpse.WebForms.WingTip.Sample/Default.aspx.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WingtipToys
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in Load");
}
protected void Page_Init(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in Init");
}
protected void Page_Render(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in Render");
}
protected void Page_SaveStateComplete(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in SaveStateComplete");
}
protected void Page_SaveState(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in SaveState");
}
protected void Page_PreRender(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in PreRender");
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in PreRenderComplete");
}
protected override void OnInitComplete(EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in InitComplete");
base.OnInitComplete(e);
}
protected override void OnPreInit(EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in PreInit");
base.OnPreInit(e);
}
protected override void OnPreLoad(EventArgs e)
{
HttpContext.Current.Trace.Write("Something that happened in PreLoad");
base.OnPreLoad(e);
}
private void Page_Error(object sender, EventArgs e)
{
// Get last error from the server.
Exception exc = Server.GetLastError();
// Handle specific exception.
if (exc is InvalidOperationException)
{
// Pass the error on to the error page.
Server.Transfer("ErrorPage.aspx?handler=Page_Error%20-%20Default.aspx",
true);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WingtipToys
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void Page_Error(object sender, EventArgs e)
{
// Get last error from the server.
Exception exc = Server.GetLastError();
// Handle specific exception.
if (exc is InvalidOperationException)
{
// Pass the error on to the error page.
Server.Transfer("ErrorPage.aspx?handler=Page_Error%20-%20Default.aspx",
true);
}
}
}
}
|
apache-2.0
|
C#
|
57d35df0b22e64a250a0a8e8f101a641b9723357
|
add comment for Points
|
Zutatensuppe/DiabloInterface,Zutatensuppe/DiabloInterface
|
src/D2Reader/Models/SkillInfo.cs
|
src/D2Reader/Models/SkillInfo.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zutatensuppe.D2Reader.Models
{
public class SkillInfo
{
public uint Id = 0;
// hard points put into the skill (skills from items not included)
public int Points = 0;
public override bool Equals(object obj)
{
SkillInfo other = obj as SkillInfo;
return Id == other.Id
&& Points == other.Points;
}
public override int GetHashCode()
{
int hashCode = -1339893796;
hashCode = hashCode * -1521134295 + Id.GetHashCode();
hashCode = hashCode * -1521134295 + Points.GetHashCode();
return hashCode;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zutatensuppe.D2Reader.Models
{
public class SkillInfo
{
public uint Id = 0;
public int Points = 0; // points invested
public override bool Equals(object obj)
{
SkillInfo other = obj as SkillInfo;
return Id == other.Id
&& Points == other.Points;
}
public override int GetHashCode()
{
int hashCode = -1339893796;
hashCode = hashCode * -1521134295 + Id.GetHashCode();
hashCode = hashCode * -1521134295 + Points.GetHashCode();
return hashCode;
}
}
}
|
mit
|
C#
|
9280a78a61ed60dbba16ac3620d8b4d6e5703df2
|
Update version from 1.0.0.1 to 2.0.0.0
|
open-pay/openpay-dotnet
|
Openpay/Properties/AssemblyInfo.cs
|
Openpay/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("Openpay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Openpay")]
[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("96e67616-0932-45bb-a06e-82c7683abc7c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
|
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("Openpay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Openpay")]
[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("96e67616-0932-45bb-a06e-82c7683abc7c")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
|
apache-2.0
|
C#
|
814998f076cbdc2d81995d527ee655afa8880a78
|
Fix a bug in array extension
|
jbatonnet/shared
|
Utilities/Extensions/Array.cs
|
Utilities/Extensions/Array.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System
{
public static class ArrayExtension
{
public static int IndexOf<T>(this T[] me, T item)
{
for (int i = 0; i < me.Length; i++)
if (me[i]?.Equals(item) == true)
return i;
return -1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System
{
public static class ArrayExtension
{
public static int IndexOf<T>(this T[] me, T item)
{
for (int i = 0; i < me.Length; i++)
if (me[i].Equals(item))
return i;
return -1;
}
}
}
|
mit
|
C#
|
c943c5b87fc0f22b66b4b9172a4e0ef5a5c575f5
|
Simplify usage of the solver
|
bradphelan/SketchSolve.NET,bradphelan/SketchSolve.NET,bradphelan/SketchSolve.NET
|
SketchSolveC#/Parameter.cs
|
SketchSolveC#/Parameter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SketchSolve
{
public class Parameter
{
public double Value = 0;
public double Max = 1000;
public double Min = -1000;
// true if the parameter is free to be adjusted by the
// solver
public bool free;
public Parameter (double v, bool free=true)
{
Value = v;
this.free = free;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SketchSolve
{
public class Parameter
{
public double Value = 0;
// true if the parameter is free to be adjusted by the
// solver
public bool free;
public Parameter (double v, bool free=true)
{
Value = v;
this.free = free;
}
}
}
|
bsd-3-clause
|
C#
|
c6963ff79f173a53a444e040431121656275a9cf
|
Revert "Revert "Adding assembly info attributes back to AssemblyInfo to see if patching will work.""
|
autofac/Autofac.Wcf,caioproiete/Autofac.Wcf
|
src/Autofac.Integration.Wcf/Properties/AssemblyInfo.cs
|
src/Autofac.Integration.Wcf/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: InternalsVisibleTo("Autofac.Integration.Wcf.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyCopyright("Copyright © 2014 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac Inversion of Control container WCF application integration.")]
[assembly: AssemblyVersionAttribute("4.0.0.0")]
[assembly: AssemblyFileVersionAttribute("4.0.0.0")]
[assembly: AssemblyInformationalVersionAttribute("4.0.0.0")]
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Wcf")]
[assembly: InternalsVisibleTo("Autofac.Integration.Wcf.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyCopyright("Copyright © 2014 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac Inversion of Control container WCF application integration.")]
|
mit
|
C#
|
e53308e3c92cd9638f3dab04ceaf616e08271032
|
Implement IEnumerable<PoEStashTab> for PoEStash
|
jcmoyer/Yeena
|
Yeena/PathOfExile/PoEStash.cs
|
Yeena/PathOfExile/PoEStash.cs
|
// Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using System.Collections.Generic;
namespace Yeena.PathOfExile {
class PoEStash : IEnumerable<PoEStashTab> {
private readonly List<PoEStashTab> _tabs;
public PoEStash(IEnumerable<PoEStashTab> tabs) {
_tabs = new List<PoEStashTab>(tabs);
}
public IReadOnlyList<PoEStashTab> Tabs {
get { return _tabs; }
}
public PoEStashTab GetContainingTab(PoEItem item) {
foreach (var tab in _tabs) {
foreach (var tabItem in tab) {
if (item == tabItem) return tab;
}
}
return null;
}
public IEnumerator<PoEStashTab> GetEnumerator() {
return Tabs.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
}
|
// Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
namespace Yeena.PathOfExile {
class PoEStash {
private readonly List<PoEStashTab> _tabs;
public PoEStash(IEnumerable<PoEStashTab> tabs) {
_tabs = new List<PoEStashTab>(tabs);
}
public IReadOnlyList<PoEStashTab> Tabs {
get { return _tabs; }
}
public PoEStashTab GetContainingTab(PoEItem item) {
foreach (var tab in _tabs) {
foreach (var tabItem in tab) {
if (item == tabItem) return tab;
}
}
return null;
}
}
}
|
apache-2.0
|
C#
|
a67f6c2872195aef8326de789c73a37e8b888689
|
Fix test for CI
|
clement911/ShopifySharp,addsb/ShopifySharp,nozzlegear/ShopifySharp
|
ShopifySharp.Tests/Policy_Tests.cs
|
ShopifySharp.Tests/Policy_Tests.cs
|
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using EmptyAssert = ShopifySharp.Tests.Extensions.EmptyExtensions;
namespace ShopifySharp.Tests
{
[Trait("Category", "Policy")]
public class Policy_Tests
{
private PolicyService _Service => new PolicyService(Utils.MyShopifyUrl, Utils.AccessToken);
[Fact]
public async Task Lists_Orders()
{
var list = await _Service.ListAsync();
Assert.NotNull(list);
foreach(var policy in list)
{
EmptyAssert.NotNullOrEmpty(policy.Title);
Assert.NotNull(policy.CreatedAt);
Assert.NotNull(policy.UpdatedAt);
}
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using EmptyAssert = ShopifySharp.Tests.Extensions.EmptyExtensions;
namespace ShopifySharp.Tests
{
[Trait("Category", "Policy")]
public class Policy_Tests
{
private PolicyService _Service => new PolicyService(Utils.MyShopifyUrl, Utils.AccessToken);
[Fact]
public async Task Lists_Orders()
{
var list = await _Service.ListAsync();
Assert.NotNull(list);
Assert.True(list.Count() > 0);
foreach(var policy in list)
{
EmptyAssert.NotNullOrEmpty(policy.Title);
Assert.NotNull(policy.CreatedAt);
Assert.NotNull(policy.UpdatedAt);
}
}
}
}
|
mit
|
C#
|
90bc1f352a5075b047fd66daea1513165a5953e4
|
Fix Back Ground Img
|
BlackthornYugen/SoundScape
|
SoundScape/SoundScape/HighScore.cs
|
SoundScape/SoundScape/HighScore.cs
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace SoundScape
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class HighScore : InfoScene
{
int _score;
public int Score
{
get { return _score; }
set
{
_score = value;
}
}
public HighScore(GameLoop game, Texture2D texture, int score)
: base(game, texture)
{
_score = score;
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
SpriteFont regularFont = Game.Content.Load<SpriteFont>("fonts/regularFont");
string msg = "";
_spritebatch.Begin();
_spritebatch.Draw(Texture, Vector2.Zero, Color.White);
msg = _score.ToString();
_spritebatch.DrawString(regularFont, msg, new Vector2(60, 90), Color.CornflowerBlue, 0,
new Vector2(), 1f, SpriteEffects.None, 0);
_spritebatch.End();
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace SoundScape
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class HighScore : InfoScene
{
int _score;
public int Score
{
get { return _score; }
set
{
_score = value;
}
}
public HighScore(GameLoop game, Texture2D texture, int score)
: base(game, texture)
{
_score = score;
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
SpriteFont regularFont = Game.Content.Load<SpriteFont>("fonts/regularFont");
string msg = "";
_spritebatch.Begin();
_spritebatch.Draw(Texture, Vector2.Zero, Color.White);
msg = _score.ToString();
_spritebatch.DrawString(regularFont, msg, new Vector2(60, 90), Color.CornflowerBlue, 0,
new Vector2(), 1f, SpriteEffects.None, 0);
_spritebatch.End();
}
}
}
|
apache-2.0
|
C#
|
09f65f227d7fbb7948a28648e8865d7a726f8a39
|
use the new
|
kusl/Tree
|
VisualTree/TreeLibrary/BinarySearchTree.cs
|
VisualTree/TreeLibrary/BinarySearchTree.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TreeLibrary
{
public sealed class BinarySearchTree
{
public BinarySearchTreeNode Root { get; set; }
public int Count { get; private set; }
public BinarySearchTree()
{
Root = null;
}
public bool IsEmpty()
{
return Root == null;
}
public void Add(int value)
{
if (IsEmpty())
{
Root = new BinarySearchTreeNode(value);
}
Count++;
}
public void Remove(int value)
{
if (Root != null && Root.Value == value)
{
if (Root.LeftChild == null && Root.RightChild == null)
{
Root = null;
}
}
}
private BinarySearchTreeNode Search_Recursively(int value, BinarySearchTreeNode node)
{
if (node == null || node.Value == value)
{
return node;
}
else if (value < node.Value)
{
return Search_Recursively(value, node.LeftChild);
}
else
{
return Search_Recursively(value, node.RightChild);
}
}
public bool Contains(int value)
{
if(Root == null)
{
return false;
}
if (Root.Value == value)
{
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TreeLibrary
{
public sealed class BinarySearchTree
{
public BinarySearchTreeNode Root { get; set; }
public BinarySearchTree()
{
Root = null;
}
public bool IsEmpty()
{
return Root == null;
}
public void Add(int value)
{
if (Root == null)
{
Root = new BinarySearchTreeNode(value);
}
}
public void Remove(int value)
{
if (Root != null && Root.Value == value)
{
if (Root.LeftChild == null && Root.RightChild == null)
{
Root = null;
}
}
}
private BinarySearchTreeNode Search_Recursively(int value, BinarySearchTreeNode node)
{
if (node == null || node.Value == value)
{
return node;
}
else if (value < node.Value)
{
return Search_Recursively(value, node.LeftChild);
}
else
{
return Search_Recursively(value, node.RightChild);
}
}
public bool Contains(int value)
{
if(Root == null)
{
return false;
}
if (Root.Value == value)
{
return true;
}
return false;
}
}
}
|
agpl-3.0
|
C#
|
e8696d62bc1d475a40db45725e2003894ff9881e
|
Fix wrong Vector3 to SerializablePosition convertion
|
Trojaner25/Rocket-Safezone,Trojaner25/Rocket-Regions
|
Model/SerializablePosition.cs
|
Model/SerializablePosition.cs
|
using System;
using System.Xml.Serialization;
using UnityEngine;
namespace Safezone.Model
{
[Serializable]
[XmlType(TypeName = "Position")]
public class SerializablePosition
{
public SerializablePosition()
{
X = 0;
Y = 0;
}
public SerializablePosition(Vector2 vec)
{
X = vec.x;
Y = vec.y;
}
public SerializablePosition(Vector3 vec)
{
X = vec.x;
Y = vec.z;
}
[XmlAttribute("x")]
public float X;
[XmlAttribute("y")]
public float Y;
}
}
|
using System;
using System.Xml.Serialization;
using UnityEngine;
namespace Safezone.Model
{
[Serializable]
[XmlType(TypeName = "Position")]
public class SerializablePosition
{
public SerializablePosition()
{
X = 0;
Y = 0;
}
public SerializablePosition(Vector3 vec)
{
X = vec.x;
Y = vec.y;
}
[XmlAttribute("x")]
public float X;
[XmlAttribute("y")]
public float Y;
}
}
|
agpl-3.0
|
C#
|
056d204866b9d6366e51ef1e5ee00b4895ef71ea
|
Add missing Attachment attributes.
|
Jaykul/SlackAPI,vampireneo/SlackAPI,Inumedia/SlackAPI
|
Attachment.cs
|
Attachment.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
//See: https://api.slack.com/docs/attachments
public class Attachment
{
public string fallback;
public string color;
public string pretext;
public string author_name;
public string author_link;
public string author_icon;
public string title;
public string title_link;
public string text;
public Field[] fields;
public string image_url;
public string thumb_url;
}
public class Field{
public string title;
public string value;
public string @short;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
public class Attachment
{
public string Pretext;
public string text;
public string fallback;
public string color;
public Field[] fields;
public string image_url;
public string thumb_url;
///I have absolutely no idea what goes on in here.
}
public class Field{
public string title;
public string value;
public string @short;
}
}
|
mit
|
C#
|
b9a03df88b3d9795fda55090417601df392dcfd0
|
Put in placeholders instead of a real username and password.
|
LeisureLink/Property-Feed-Samples
|
C#/Program.cs
|
C#/Program.cs
|
using System.Xml;
using PropertyFeedSampleApp.PropertyFeed;
namespace PropertyFeedSampleApp
{
class Program
{
static void Main(string[] args)
{
//You should have been provided values for the following
const string userName = "YOUR_USER_NAME";
const string password = "YOUR_PASSWORD";
using (var client = new DataReceiverServiceSoapClient())
{
var supplierIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, string.Empty, true);
foreach (var supplierId in supplierIds)
{
var rentalUnitIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, supplierId.ToString(), false);
foreach (var rentalUnitId in rentalUnitIds)
{
//Some properties will return a lot of data.
//Be sure to increase the MaxReceivedMessageSize property on the appropriate binding element in your config.
//We suggest maxReceivedMessageSize="6553600"
string dataExtract = client.DataExtract(new AuthHeader { UserName = userName, Password = password }, "STANDARD", string.Empty, string.Empty, rentalUnitId.ToString());
var propertyDoc = new XmlDocument();
propertyDoc.LoadXml(dataExtract);
if (propertyDoc.DocumentElement.ChildNodes.Count == 0)
{
//The property is inactive, make it inactive in your system
}
else
{
//The property is active, cache the data in your system
goto EndOfExample;
}
}
}
EndOfExample:;
}
}
}
}
|
using System.Xml;
using PropertyFeedSampleApp.PropertyFeed;
namespace PropertyFeedSampleApp
{
class Program
{
static void Main(string[] args)
{
const string userName = "VACATION11";
const string password = "f33der1!";
using (var client = new DataReceiverServiceSoapClient())
{
var supplierIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, string.Empty, true);
foreach (var supplierId in supplierIds)
{
var rentalUnitIds = client.GetValidRentalUnitIdsForExtract(new AuthHeader { UserName = userName, Password = password }, string.Empty, supplierId.ToString(), false);
foreach (var rentalUnitId in rentalUnitIds)
{
//Some properties will return a lot of data.
//Be sure to increase the MaxReceivedMessageSize property on the appropriate binding element in your config.
//We suggest maxReceivedMessageSize="6553600"
string dataExtract = client.DataExtract(new AuthHeader { UserName = userName, Password = password }, "STANDARD", string.Empty, string.Empty, rentalUnitId.ToString());
var propertyDoc = new XmlDocument();
propertyDoc.LoadXml(dataExtract);
if (propertyDoc.DocumentElement.ChildNodes.Count == 0)
{
//The property is inactive, make it inactive in your system
}
else
{
//The property is active, cache the data in your system
goto EndOfExample;
}
}
}
EndOfExample:;
}
}
}
}
|
mit
|
C#
|
203b8b22b90216a26a02ae69294d52a41a248711
|
Adjust tests
|
ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu
|
osu.Game.Rulesets.Mania.Tests/ManiaDifficultyCalculatorTest.cs
|
osu.Game.Rulesets.Mania.Tests/ManiaDifficultyCalculatorTest.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.
#nullable disable
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3493769750220914d, 242, "diffcalc-test")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(2.797245912537965d, 242, "diffcalc-test")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new ManiaModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
|
// 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.
#nullable disable
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3449735700206298d, 242, "diffcalc-test")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(2.7879104989252959d, 242, "diffcalc-test")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new ManiaModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
|
mit
|
C#
|
356f5dceef8e898dc592b8630b82b1bfda3eecfa
|
Add more test case
|
peppy/osu,smoogipooo/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu
|
osu.Game.Tests/Localisation/BeatmapMetadataRomanisationTest.cs
|
osu.Game.Tests/Localisation/BeatmapMetadataRomanisationTest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
namespace osu.Game.Tests.Localisation
{
[TestFixture]
public class BeatmapMetadataRomanisationTest
{
[Test]
public void TestRomanisation()
{
var metadata = new BeatmapMetadata
{
Artist = "Romanised Artist",
ArtistUnicode = "Unicode Artist",
Title = "Romanised title",
TitleUnicode = "Unicode Title"
};
var romanisableString = metadata.ToRomanisableString();
Assert.AreEqual(metadata.ToString(), romanisableString.Romanised);
Assert.AreEqual($"{metadata.ArtistUnicode} - {metadata.TitleUnicode}", romanisableString.Original);
}
[Test]
public void TestRomanisationNoUnicode()
{
var metadata = new BeatmapMetadata
{
Artist = "Romanised Artist",
Title = "Romanised title"
};
var romanisableString = metadata.ToRomanisableString();
Assert.AreEqual(romanisableString.Romanised, romanisableString.Original);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
namespace osu.Game.Tests.Localisation
{
[TestFixture]
public class BeatmapMetadataRomanisationTest
{
[Test]
public void TestNoUnicode()
{
var beatmap = new Beatmap
{
BeatmapInfo = new BeatmapInfo
{
Metadata = new BeatmapMetadata
{
Artist = "Artist",
Title = "Romanised title"
}
}
};
var romanisableString = beatmap.Metadata.ToRomanisableString();
Assert.AreEqual(romanisableString.Romanised, romanisableString.Original);
}
}
}
|
mit
|
C#
|
9175a7bc72a3a0155a4138d9bf02689a15b525c2
|
fix for GA
|
autumn009/TanoCSharpSamples
|
Chap37/LambdaImprovements/LambdaImprovements/Program.cs
|
Chap37/LambdaImprovements/LambdaImprovements/Program.cs
|
using System;
var lambda1 = () => new B();
var lambda2 = A () => new B();
Console.WriteLine(lambda1.GetType().FullName);
Console.WriteLine(lambda2.GetType().FullName);
class A { }
class B : A { }
|
var lambda1 = () => new B();
var lambda2 = A () => new B();
Console.WriteLine(lambda1.GetType().FullName);
Console.WriteLine(lambda2.GetType().FullName);
class A { }
class B : A { }
|
mit
|
C#
|
b591a5d18e451998443da90bd8bb6a2071b2da7c
|
fix cors config
|
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
|
Demo/NakedObjects.Rest.App.Demo/App_Start/CorsConfig.cs
|
Demo/NakedObjects.Rest.App.Demo/App_Start/CorsConfig.cs
|
using System.Web.Http;
using Thinktecture.IdentityModel.Http.Cors.WebApi;
public class CorsConfig {
public static void RegisterCors(HttpConfiguration httpConfig) {
var corsConfig = new WebApiCorsConfiguration();
// this adds the CorsMessageHandler to the HttpConfiguration’s
// MessageHandlers collection
corsConfig.RegisterGlobal(httpConfig);
// this allow all CORS requests to the Products controller
// from the http://foo.com origin.
corsConfig.ForResources("RestfulObjects").
ForOrigins("http://localhost:49998",
"http://localhost:8080",
"http://nakedobjectstest.azurewebsites.net",
"http://nakedobjectstest2.azurewebsites.net",
"http://localhost").
AllowAll().
AllowResponseHeaders("Warning", "Set-Cookie", "ETag").
AllowCookies();
}
}
|
using System.Web.Http;
using Thinktecture.IdentityModel.Http.Cors.WebApi;
public class CorsConfig {
public static void RegisterCors(HttpConfiguration httpConfig) {
var corsConfig = new WebApiCorsConfiguration();
// this adds the CorsMessageHandler to the HttpConfiguration’s
// MessageHandlers collection
corsConfig.RegisterGlobal(httpConfig);
// this allow all CORS requests to the Products controller
// from the http://foo.com origin.
corsConfig.ForResources("RestfulObjects").
ForOrigins("http://localhost:49998", "http://localhost:8080", "http://nakedobjectstest.azurewebsites.net", "http://localhost").
AllowAll().
AllowResponseHeaders("Warning", "Set-Cookie", "ETag").
AllowCookies();
}
}
|
apache-2.0
|
C#
|
0f85cec02864600353699cdcd672df3ac416a09f
|
add Benchmark attribute to Callback.FakeItEasy()
|
stevedesmond-ca/BenchmarkMockNet
|
Callback.cs
|
Callback.cs
|
using BenchmarkDotNet.Attributes;
using FakeItEasy;
using Moq;
using NSubstitute;
namespace BenchmarkMockNet
{
public class Callback : IMockingBenchmark
{
[Benchmark(Baseline = true)]
public void Stub()
{
var stub = new ThingStub();
stub.Do();
}
[Benchmark]
public void Moq()
{
var mock = new Mock<IThingy>();
mock.Setup(m => m.Do()).Callback(() => mock.Object.Called = true);
mock.Object.Do();
}
[Benchmark]
public void NSubstitute()
{
var sub = Substitute.For<IThingy>();
sub.When(s => s.Do()).Do(c => sub.Called = true);
sub.Do();
}
[Benchmark]
public void FakeItEasy()
{
var fake = A.Fake<IThingy>();
A.CallTo(() => fake.Do()).Invokes(() => fake.Called = true);
fake.Do();
}
}
}
|
using BenchmarkDotNet.Attributes;
using FakeItEasy;
using Moq;
using NSubstitute;
namespace BenchmarkMockNet
{
public class Callback : IMockingBenchmark
{
[Benchmark(Baseline = true)]
public void Stub()
{
var stub = new ThingStub();
stub.Do();
}
[Benchmark]
public void Moq()
{
var mock = new Mock<IThingy>();
mock.Setup(m => m.Do()).Callback(() => mock.Object.Called = true);
mock.Object.Do();
}
[Benchmark]
public void NSubstitute()
{
var sub = Substitute.For<IThingy>();
sub.When(s => s.Do()).Do(c => sub.Called = true);
sub.Do();
}
public void FakeItEasy()
{
var fake = A.Fake<IThingy>();
A.CallTo(() => fake.Do()).Invokes(() => fake.Called = true);
fake.Do();
}
}
}
|
mit
|
C#
|
cdcd4b634fbbd2bbcd96f0b1f89ece5b5d148663
|
Fix Dev15 build
|
MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS
|
src/Package/Impl/ProjectSystem/Commands/CopyItemPathCommand.cs
|
src/Package/Impl/ProjectSystem/Commands/CopyItemPathCommand.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.Common.Core;
using Microsoft.R.Components.Extensions;
using Microsoft.R.Components.InteractiveWorkflow;
using Microsoft.R.Host.Client.Session;
using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.Shell;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Designers;
using Microsoft.VisualStudio.ProjectSystem.Utilities;
#else
using Microsoft.VisualStudio.ProjectSystem;
#endif
namespace Microsoft.VisualStudio.R.Package.ProjectSystem.Commands {
[ExportCommandGroup("AD87578C-B324-44DC-A12A-B01A6ED5C6E3")]
[AppliesTo(ProjectConstants.RtvsProjectCapability)]
internal sealed class CopyItemPathCommand : IAsyncCommandGroupHandler {
private readonly IRInteractiveWorkflowProvider _interactiveWorkflowProvider;
[ImportingConstructor]
public CopyItemPathCommand(IRInteractiveWorkflowProvider interactiveWorkflowProvider) {
_interactiveWorkflowProvider = interactiveWorkflowProvider;
}
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) {
if (commandId == RPackageCommandId.icmdCopyItemPath && nodes.IsSingleNodePath()) {
return Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported));
}
return Task.FromResult(CommandStatusResult.Unhandled);
}
public async Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut) {
VsAppShell.Current.AssertIsOnMainThread();
if (commandId != RPackageCommandId.icmdCopyItemPath) {
return false;
}
var path = nodes.GetSingleNodePath();
var directory = await _interactiveWorkflowProvider.GetOrCreate().RSession.MakeRelativeToRUserDirectoryAsync(path);
if (!string.IsNullOrEmpty(directory)) {
directory.CopyToClipboard();
}
return true;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.Common.Core;
using Microsoft.R.Components.Extensions;
using Microsoft.R.Components.InteractiveWorkflow;
using Microsoft.R.Host.Client.Session;
using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.Shell;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Designers;
using Microsoft.VisualStudio.ProjectSystem.Utilities;
#else
using Microsoft.VisualStudio.ProjectSystem
#endif
namespace Microsoft.VisualStudio.R.Package.ProjectSystem.Commands {
[ExportCommandGroup("AD87578C-B324-44DC-A12A-B01A6ED5C6E3")]
[AppliesTo(ProjectConstants.RtvsProjectCapability)]
internal sealed class CopyItemPathCommand : IAsyncCommandGroupHandler {
private readonly IRInteractiveWorkflowProvider _interactiveWorkflowProvider;
[ImportingConstructor]
public CopyItemPathCommand(IRInteractiveWorkflowProvider interactiveWorkflowProvider) {
_interactiveWorkflowProvider = interactiveWorkflowProvider;
}
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) {
if (commandId == RPackageCommandId.icmdCopyItemPath && nodes.IsSingleNodePath()) {
return Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported));
}
return Task.FromResult(CommandStatusResult.Unhandled);
}
public async Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut) {
VsAppShell.Current.AssertIsOnMainThread();
if (commandId != RPackageCommandId.icmdCopyItemPath) {
return false;
}
var path = nodes.GetSingleNodePath();
var directory = await _interactiveWorkflowProvider.GetOrCreate().RSession.MakeRelativeToRUserDirectoryAsync(path);
if (!string.IsNullOrEmpty(directory)) {
directory.CopyToClipboard();
}
return true;
}
}
}
|
mit
|
C#
|
9b4268ea0316e697a3c5b8aae93770ea5219982b
|
Add error handling for auth response
|
dylanplecki/BasicOidcAuthentication,dylanplecki/KeycloakOwinAuthentication,joelnet/KeycloakOwinAuthentication
|
src/Owin.Security.Keycloak/Models/AuthorizationResponse.cs
|
src/Owin.Security.Keycloak/Models/AuthorizationResponse.cs
|
using System;
using System.Collections.Specialized;
using System.Web;
using Microsoft.IdentityModel.Protocols;
namespace Owin.Security.Keycloak.Models
{
internal class AuthorizationResponse : OidcBaseResponse
{
public string Code { get; private set; }
public string State { get; private set; }
public AuthorizationResponse(string query)
{
Init(HttpUtility.ParseQueryString(query));
if (!Validate())
{
throw new ArgumentException("Invalid query string used to instantiate an AuthorizationResponse");
}
}
public AuthorizationResponse(NameValueCollection authResult)
{
Init(authResult);
}
protected new void Init(NameValueCollection authResult)
{
base.Init(authResult);
Code = authResult.Get(OpenIdConnectParameterNames.Code);
State = authResult.Get(OpenIdConnectParameterNames.State);
}
public bool Validate()
{
return !string.IsNullOrWhiteSpace(Code) && !string.IsNullOrWhiteSpace(State);
}
}
}
|
using System.Collections.Specialized;
using System.Web;
using Microsoft.IdentityModel.Protocols;
namespace Owin.Security.Keycloak.Models
{
internal class AuthorizationResponse : OidcBaseResponse
{
public string Code { get; private set; }
public string State { get; private set; }
public AuthorizationResponse(string query)
{
Init(HttpUtility.ParseQueryString(query));
}
public AuthorizationResponse(NameValueCollection authResult)
{
Init(authResult);
}
protected new void Init(NameValueCollection authResult)
{
base.Init(authResult);
Code = authResult.Get(OpenIdConnectParameterNames.Code);
State = authResult.Get(OpenIdConnectParameterNames.State);
}
}
}
|
mit
|
C#
|
fc78413fecbf35524c29a971e19400ea63a2568a
|
Hide .sln file from project tree
|
AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS
|
src/Package/Impl/ProjectSystem/RMsBuildFileSystemFilter.cs
|
src/Package/Impl/ProjectSystem/RMsBuildFileSystemFilter.cs
|
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO;
namespace Microsoft.VisualStudio.R.Package.ProjectSystem
{
internal sealed class RMsBuildFileSystemFilter : IMsBuildFileSystemFilter
{
public bool IsFileAllowed(string relativePath, FileAttributes attributes)
{
return !attributes.HasFlag(FileAttributes.Hidden)
&& !HasExtension(relativePath, ".user", ".rxproj", ".sln");
}
public bool IsDirectoryAllowed(string relativePath, FileAttributes attributes)
{
return !attributes.HasFlag(FileAttributes.Hidden);
}
public void Seal()
{
}
private static bool HasExtension(string filePath, params string[] possibleExtensions)
{
var extension = Path.GetExtension(filePath);
return !string.IsNullOrEmpty(extension) && possibleExtensions.Any(pe => extension.Equals(pe, StringComparison.OrdinalIgnoreCase));
}
}
}
|
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.IO;
namespace Microsoft.VisualStudio.R.Package.ProjectSystem
{
internal sealed class RMsBuildFileSystemFilter : IMsBuildFileSystemFilter
{
public bool IsFileAllowed(string relativePath, FileAttributes attributes)
{
return !attributes.HasFlag(FileAttributes.Hidden)
&& !HasExtension(relativePath, ".user", ".rxproj");
}
public bool IsDirectoryAllowed(string relativePath, FileAttributes attributes)
{
return !attributes.HasFlag(FileAttributes.Hidden);
}
public void Seal()
{
}
private static bool HasExtension(string filePath, params string[] possibleExtensions)
{
var extension = Path.GetExtension(filePath);
return !string.IsNullOrEmpty(extension) && possibleExtensions.Any(pe => extension.Equals(pe, StringComparison.OrdinalIgnoreCase));
}
}
}
|
mit
|
C#
|
ee6f3527993d497e50b3136d80b9d5707358a12e
|
Fix infinite loop when retrying a failing build number
|
Abc-Arbitrage/zerio
|
build/scripts/utilities.cake
|
build/scripts/utilities.cake
|
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
// if(!AppVeyor.IsRunningOnAppVeyor)
// {
// Information("Not running under AppVeyor");
// return;
// }
Information("Running under AppVeyor");
Information("Updating AppVeyor build version to " + VersionContext.BuildVersion);
var increment = 0;
while(increment < 10)
{
try
{
var version = VersionContext.BuildVersion;
if(increment > 0)
version += "-" + increment;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
}
}
}
|
#tool "nuget:?package=GitVersion.CommandLine"
#addin "Cake.Yaml"
public class ContextInfo
{
public string NugetVersion { get; set; }
public string AssemblyVersion { get; set; }
public GitVersion Git { get; set; }
public string BuildVersion
{
get { return NugetVersion + "-" + Git.Sha; }
}
}
ContextInfo _versionContext = null;
public ContextInfo VersionContext
{
get
{
if(_versionContext == null)
throw new Exception("The current context has not been read yet. Call ReadContext(FilePath) before accessing the property.");
return _versionContext;
}
}
public ContextInfo ReadContext(FilePath filepath)
{
_versionContext = DeserializeYamlFromFile<ContextInfo>(filepath);
_versionContext.Git = GitVersion();
return _versionContext;
}
public void UpdateAppVeyorBuildVersionNumber()
{
if(!AppVeyor.IsRunningOnAppVeyor)
{
Information("Not running under AppVeyor");
return;
}
Information("Running under AppVeyor");
Information("Updating AppVeyor build version to " + VersionContext.BuildVersion);
while(true)
{
int? increment = null;
try
{
var version = VersionContext.BuildVersion;
if(increment.HasValue)
version += "-" + increment.Value;
AppVeyor.UpdateBuildVersion(version);
break;
}
catch
{
increment++;
if(increment <= 10)
continue;
}
}
}
|
mit
|
C#
|
e96efa927d9bedb0c93d3366c37bc1848e3ed75f
|
Implement a few dependency properties for AppView
|
jamesqo/Sirloin
|
src/Sirloin/AppView.xaml.cs
|
src/Sirloin/AppView.xaml.cs
|
using Sirloin.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Sirloin
{
public sealed partial class AppView : UserControl
{
public static AppView Current { get; private set; }
// Expose the GUI elements via properties
public Frame Frame => this.frame;
public SplitView SplitView => this.splitView;
public ListView TopView => this.topView;
public ListView BottomView => this.bottomView;
// Begin dependency property cruft
// BottomViewSource:
public object BottomViewSource
{
get { return this.GetValue<object>(BottomViewSourceProperty); }
set { this.SetValue(BottomViewSourceProperty, value); }
}
public static DependencyProperty BottomViewSourceProperty { get; } =
Dependency.Register<object, AppView>(nameof(BottomViewSource), BottomViewSourcePropertyChanged);
private static void BottomViewSourcePropertyChanged(AppView o, IPropertyChangedArgs<object> args)
{
o.bottomView.ItemsSource = args.NewValue;
}
// IsPaneOpen:
public bool IsPaneOpen
{
get { return this.GetValue<bool>(IsPaneOpenProperty); }
set { this.SetValue(IsPaneOpenProperty, value); }
}
public static DependencyProperty IsPaneOpenProperty { get; } =
Dependency.Register<bool, AppView>(nameof(IsPaneOpen), IsPaneOpenPropertyChanged);
private static void IsPaneOpenPropertyChanged(AppView o, IPropertyChangedArgs<bool> args)
{
o.splitView.IsPaneOpen = args.NewValue;
}
// TopViewSource:
public object TopViewSource
{
get { return this.GetValue<object>(TopViewSourceProperty); }
set { this.SetValue(TopViewSourceProperty, value); }
}
public static DependencyProperty TopViewSourceProperty { get; } =
Dependency.Register<object, AppView>(nameof(TopViewSource), TopViewSourcePropertyChanged);
private static void TopViewSourcePropertyChanged(AppView o, IPropertyChangedArgs<object> args)
{
o.topView.ItemsSource = args.NewValue;
}
// End dependency property cruft
public AppView()
{
this.InitializeComponent();
this.Loaded += (o, e) => Current = this;
}
private void OnHamburgerClicked(object sender, RoutedEventArgs e)
{
var splitView = this.splitView; // save a field access
splitView.IsPaneOpen = !splitView.IsPaneOpen;
}
}
}
|
using Sirloin.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Sirloin
{
public sealed partial class AppView : UserControl
{
public static AppView Current { get; private set; }
// Expose the GUI elements via properties
public Frame Frame => this.frame;
public SplitView SplitView => this.splitView;
public ListView TopView => this.topView;
public ListView BottomView => this.bottomView;
public AppView()
{
this.InitializeComponent();
this.Loaded += (o, e) => Current = this;
}
private void OnHamburgerClicked(object sender, RoutedEventArgs e)
{
var splitView = this.splitView; // save a field access
splitView.IsPaneOpen = !splitView.IsPaneOpen;
}
}
}
|
bsd-2-clause
|
C#
|
101b4ea5f9872c046d2b12198102a0b892f9e66d
|
Update SqlDbSafeManager.cs
|
dbsafe/dbsafe
|
SqlDbSafe/SqlDbSafeManager.cs
|
SqlDbSafe/SqlDbSafeManager.cs
|
using DbSafe;
using System;
using System.Configuration;
namespace SqlDbSafe
{
public class SqlDbSafeManager : DbSafeManager<SqlDatabaseClient>
{
private readonly SqlDatabaseClient _databaseClient = new SqlDatabaseClient();
public static SqlDbSafeManager Initialize(DbSafeManagerConfig config, params string[] filenames)
{
var result = new SqlDbSafeManager(config);
foreach (var filename in filenames)
{
result.Load(filename);
}
result.BeginTest();
return result;
}
public static SqlDbSafeManager Initialize(params string[] filenames)
{
return Initialize(DbSafeManagerConfig.GlobalConfig, filenames);
}
private SqlDbSafeManager(DbSafeManagerConfig config)
: base(config)
{
DatabaseClient = _databaseClient;
}
public SqlDbSafeManager SetConnectionString(string connectionStringName)
{
var connectionStringDetail = ConfigurationManager.ConnectionStrings[connectionStringName];
if (connectionStringDetail == null)
{
string message = $"Connection String '{connectionStringName}' not found";
throw new Exception(message);
}
_databaseClient.ConnectionString = connectionStringDetail.ConnectionString;
return this;
}
public SqlDbSafeManager PassConnectionString(string connectionString)
{
_databaseClient.ConnectionString = connectionString;
return this;
}
protected override void ValidateDependencies(bool allowTestWithoutInputFile = false)
{
base.ValidateDependencies(allowTestWithoutInputFile);
if (string.IsNullOrWhiteSpace(_databaseClient.ConnectionString))
{
throw new InvalidOperationException("ConnectionString not specified");
}
}
}
}
|
using DbSafe;
using System;
using System.Configuration;
namespace SqlDbSafe
{
public class SqlDbSafeManager : DbSafeManager<SqlDatabaseClient>
{
private readonly SqlDatabaseClient _databaseClient = new SqlDatabaseClient();
public static SqlDbSafeManager Initialize(DbSafeManagerConfig config, params string[] filenames)
{
var result = new SqlDbSafeManager(config);
foreach (var filename in filenames)
{
result.Load(filename);
}
result.BeginTest();
return result;
}
public static SqlDbSafeManager Initialize(params string[] filenames)
{
return Initialize(DbSafeManagerConfig.GlobalConfig, filenames);
}
private SqlDbSafeManager(DbSafeManagerConfig config)
: base(config)
{
DatabaseClient = _databaseClient;
}
public SqlDbSafeManager SetConnectionString(string connectionStringName)
{
var connectionStringDetail = ConfigurationManager.ConnectionStrings[connectionStringName];
if (connectionStringDetail == null)
{
string message = $"Connection String '{connectionStringName}' not found";
throw new Exception(message);
}
_databaseClient.ConnectionString = connectionStringDetail.ConnectionString;
return this;
}
protected override void ValidateDependencies(bool allowTestWithoutInputFile = false)
{
base.ValidateDependencies(allowTestWithoutInputFile);
if (string.IsNullOrWhiteSpace(_databaseClient.ConnectionString))
{
throw new InvalidOperationException("ConnectionString not specified");
}
}
}
}
|
mit
|
C#
|
06a78d9729a17f119c18f455b9a1a3e30342e8e8
|
fix taiko tests
|
ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu
|
osu.Game.Rulesets.Taiko.Tests/TaikoDifficultyCalculatorTest.cs
|
osu.Game.Rulesets.Taiko.Tests/TaikoDifficultyCalculatorTest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(2.2420075288523802d, "diffcalc-test")]
[TestCase(2.2420075288523802d, "diffcalc-test-strong")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(3.134084469440479d, "diffcalc-test")]
[TestCase(3.134084469440479d, "diffcalc-test-strong")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new TaikoModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Taiko.Tests
{
public class TaikoDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(2.2593624565103561d, "diffcalc-test")]
[TestCase(2.2593624565103561d, "diffcalc-test-strong")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(3.1518486708786382d, "diffcalc-test")]
[TestCase(3.1518486708786382d, "diffcalc-test-strong")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new TaikoModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new TaikoDifficultyCalculator(new TaikoRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new TaikoRuleset();
}
}
|
mit
|
C#
|
2c19197bd4dd6381022c699c256374e093c37f15
|
remove Pipe's Close() method
|
lontivero/Open.HttpProxy
|
Open.HttpProxy/Pipe.cs
|
Open.HttpProxy/Pipe.cs
|
using System.IO;
using System.Threading.Tasks;
namespace Open.HttpProxy
{
internal class Pipe
{
public Stream Stream { get; }
public HttpStreamReader Reader { get; }
public HttpStreamWriter Writer { get; }
public Pipe(Stream stream)
{
stream.ReadTimeout = 10 * 1000;
stream.WriteTimeout = 10 * 1000;
Stream = stream;
Reader = new HttpStreamReader(Stream);
Writer = new HttpStreamWriter(Stream);
}
}
}
|
using System.IO;
using System.Threading.Tasks;
namespace Open.HttpProxy
{
internal class Pipe
{
public Stream Stream { get; }
public HttpStreamReader Reader { get; }
public HttpStreamWriter Writer { get; }
public Pipe(Stream stream)
{
Stream = stream;
Reader = new HttpStreamReader(new BufferedStream(Stream));
Writer = new HttpStreamWriter(new BufferedStream(Stream));
}
public void Close()
{
Reader.Close();
Writer.Close();
Stream.Close();
}
}
}
|
mit
|
C#
|
58d934af2a9e13ade955adb3fa2cb4cc3d3c0048
|
Fix improper container configuration for service locator
|
LeCantaloop/OctoHook,kzu/OctoHook
|
Web/ContainerConfiguration.cs
|
Web/ContainerConfiguration.cs
|
namespace OctoHook
{
using Autofac;
using Autofac.Extras.CommonServiceLocator;
using Autofac.Integration.WebApi;
using Microsoft.Practices.ServiceLocation;
using OctoHook.CommonComposition;
using Octokit;
using Octokit.Internal;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.Web.Http;
public static class ContainerConfiguration
{
public static IContainer Configure(IWorkQueue queue)
{
IContainer container = null;
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterComponents(Assembly.GetExecutingAssembly())
.InstancePerRequest();
builder.Register<IGitHubClient>(c =>
new GitHubClient(
new ProductHeaderValue("OctoHook"),
new InMemoryCredentialStore(
new Credentials(ConfigurationManager.AppSettings["GitHubToken"]))));
builder.Register<IServiceLocator>(c => new AutofacServiceLocator(c))
.InstancePerRequest();
builder.RegisterInstance(queue).SingleInstance();
container = builder.Build();
return container;
}
}
}
|
namespace OctoHook
{
using Autofac;
using Autofac.Extras.CommonServiceLocator;
using Autofac.Integration.WebApi;
using Microsoft.Practices.ServiceLocation;
using OctoHook.CommonComposition;
using Octokit;
using Octokit.Internal;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.Web.Http;
public static class ContainerConfiguration
{
public static IContainer Configure(IWorkQueue queue)
{
IContainer container = null;
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterComponents(Assembly.GetExecutingAssembly())
.InstancePerRequest();
builder.Register<IGitHubClient>(c =>
new GitHubClient(
new ProductHeaderValue("OctoHook"),
new InMemoryCredentialStore(
new Credentials(ConfigurationManager.AppSettings["GitHubToken"]))));
builder.Register<IServiceLocator>(c => new AutofacServiceLocator(container));
builder.RegisterInstance(queue).SingleInstance();
container = builder.Build();
return container;
}
}
}
|
apache-2.0
|
C#
|
b1721c4d6e551d77e37478b056c5ec07481044e5
|
Add seed
|
toshetoo/TaskManagerMVC,toshetoo/TaskManagerMVC,toshetoo/TaskManagerMVC,toshetoo/TaskManagerMVC
|
TaskManagerMVC/TaskManagerMVC.Data/Migrations/Configuration.cs
|
TaskManagerMVC/TaskManagerMVC.Data/Migrations/Configuration.cs
|
namespace TaskManagerMVC.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<TaskManagerMVC.Data.TaskManagerContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(TaskManagerMVC.Data.TaskManagerContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
context.Users.AddOrUpdate(
p => p.Username,
new Models.User { Username = "Andrew Peters" },
new Models.User { Username = "Brice Lambson" },
new Models.User { Username = "Rowan Miller" }
);
}
}
}
|
namespace TaskManagerMVC.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<TaskManagerMVC.Data.TaskManagerContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(TaskManagerMVC.Data.TaskManagerContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
|
mit
|
C#
|
99f486e42b19b853db2989eb2e98229d58eec0de
|
Fix exception in inital mapping if event subject or summary is null
|
aluxnimm/outlookcaldavsynchronizer,DoCode/Outlook-CalDav-Synchronizer
|
CalDavSynchronizer/Implementation/OutlookCalDavInitialEntityMatcher.cs
|
CalDavSynchronizer/Implementation/OutlookCalDavInitialEntityMatcher.cs
|
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using CalDavSynchronizer.Generic.InitialEntityMatching;
using CalDavSynchronizer.Implementation.ComWrappers;
using DDay.iCal;
using Microsoft.Office.Interop.Outlook;
namespace CalDavSynchronizer.Implementation
{
internal class OutlookCalDavInitialEntityMatcher : InitialEntityMatcherByPropertyGrouping<AppointmentItemWrapper, string, DateTime, string, IICalendar, Uri, string, string>
{
protected override bool AreEqual (AppointmentItemWrapper atypeEntity, IICalendar btypeEntity)
{
var evt = btypeEntity.Events[0];
return
evt.Summary == atypeEntity.Inner.Subject &&
(evt.IsAllDay && atypeEntity.Inner.AllDayEvent ||
evt.Start.UTC == atypeEntity.Inner.StartUTC.ToUniversalTime() &&
evt.DTEnd.UTC == atypeEntity.Inner.EndUTC.ToUniversalTime());
}
protected override string GetAtypePropertyValue (AppointmentItemWrapper atypeEntity)
{
return (atypeEntity.Inner.Subject!=null?atypeEntity.Inner.Subject.ToLower():string.Empty);
}
protected override string GetBtypePropertyValue (IICalendar btypeEntity)
{
return (btypeEntity.Events[0].Summary!=null?btypeEntity.Events[0].Summary.ToLower():string.Empty);
}
protected override string MapAtypePropertyValue (string value)
{
return value;
}
}
}
|
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using CalDavSynchronizer.Generic.InitialEntityMatching;
using CalDavSynchronizer.Implementation.ComWrappers;
using DDay.iCal;
using Microsoft.Office.Interop.Outlook;
namespace CalDavSynchronizer.Implementation
{
internal class OutlookCalDavInitialEntityMatcher : InitialEntityMatcherByPropertyGrouping<AppointmentItemWrapper, string, DateTime, string, IICalendar, Uri, string, string>
{
protected override bool AreEqual (AppointmentItemWrapper atypeEntity, IICalendar btypeEntity)
{
var evt = btypeEntity.Events[0];
return
evt.Summary == atypeEntity.Inner.Subject &&
(evt.IsAllDay && atypeEntity.Inner.AllDayEvent ||
evt.Start.UTC == atypeEntity.Inner.StartUTC.ToUniversalTime() &&
evt.DTEnd.UTC == atypeEntity.Inner.EndUTC.ToUniversalTime());
}
protected override string GetAtypePropertyValue (AppointmentItemWrapper atypeEntity)
{
return atypeEntity.Inner.Subject.ToLower();
}
protected override string GetBtypePropertyValue (IICalendar btypeEntity)
{
return btypeEntity.Events[0].Summary.ToLower();
}
protected override string MapAtypePropertyValue (string value)
{
return value;
}
}
}
|
agpl-3.0
|
C#
|
636137bd5e38acaaa79d55eda028d509eb78c2f3
|
add some code
|
Maskln/CSharp-Part-1
|
5.Conditional-Statements/09.PlayWithIntDoubleAndString/Program.cs
|
5.Conditional-Statements/09.PlayWithIntDoubleAndString/Program.cs
|
/*Problem 9. Play with Int, Double and String
Write a program that, depending on the user’s choice, inputs an int, double or string variable.
If the variable is int or double, the program increases it by one.
If the variable is a string, the program appends * at the end.
Print the result at the console. Use switch statement.
*/
using System;
class PlayWithIntDoubleAndString
{
static void Main()
{
Console.Write("Please choose a type:\n1 --> int\n2 --> double\n3 --> string\nPlease make your choise: ");
int programType = int.Parse(Console.ReadLine());
switch (programType)
{
case 1:
Console.Write("Please enter an Integer: ");
int integer = int.Parse(Console.ReadLine());
int sum = integer + 1;
Console.WriteLine("Result: {0}", sum);
break;
case 2:
Console.Write("Please enter a Double: ");
double valueDouble = double.Parse(Console.ReadLine());
double sumDouble = valueDouble + 1;
Console.WriteLine("Result: {0}", sumDouble);
break;
case 3:
Console.Write("Please enter a String: ");
string nameString = Console.ReadLine();
Console.WriteLine("Result: {0}", nameString +"*");
break;
default:
Console.WriteLine("Incorrect Choise!");
break;
}
}
}
|
/*Problem 9. Play with Int, Double and String
Write a program that, depending on the user’s choice, inputs an int, double or string variable.
If the variable is int or double, the program increases it by one.
If the variable is a string, the program appends * at the end.
Print the result at the console. Use switch statement.
*/
using System;
class PlayWithIntDoubleAndString
{
static void Main()
{
Console.Write("Please choose a type:\n1 --> int\n2 --> double\n3 --> string\nPlease make your choise: ");
int programType = int.Parse(Console.ReadLine());
switch (programType)
{
case 1:
Console.Write("Please enter an Integer: ");
int integer = int.Parse(Console.ReadLine());
int sum = integer + 1;
Console.WriteLine("Result: {0}", sum);
break;
case 2:
Console.Write("Please enter a Double: ");
double valueDouble = double.Parse(Console.ReadLine());
double sumDouble = valueDouble + 1;
Console.WriteLine("Result: {0}", sumDouble);
break;
case 3:
Console.Write("Please enter a String: ");
string nameString = Console.ReadLine();
Console.WriteLine("Result: {0}", nameString +"*");
break;
default:
break;
}
}
}
|
mit
|
C#
|
df770a3b77eae957b582fb0f8a259769bfb246a4
|
Update ResourceRef.cs
|
paulhayes/UnityResourceReference
|
Scripts/ResourceRef.cs
|
Scripts/ResourceRef.cs
|
using UnityEngine;
using System.Collections;
[System.Serializable]
public class ResourceRef : ScriptableObject
{
public string path;
public string GUID;
private Object cache;
public T Get<T>() where T : Object
{
//Debug.Log("Runtime -> Loading Path:"+path+" GUID:"+GUID);
if (cache == null)
{
Load<T>();
}
return cache as T;
}
public ResourceRequest GetAsync<T>()
{
return Resources.LoadAsync(path,typeof(T));
}
public void Unload()
{
if (cache != null)
{
Resources.UnloadAsset(cache);
}
}
public void Load<T>() where T : Object
{
cache = (T)Resources.Load(path, typeof(T));
}
public virtual System.Type ResourceType()
{
return typeof(Object);
}
public void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
}
}
/*
[System.Serializable]
public class GameObjectResource : ResourceRef
{
public GameObject Get()
{
return Get<GameObject>();
}
public override System.Type ResourceType()
{
return typeof(GameObject);
}
}
*/
/*
[System.Serializable]
public class TextAssetResource : ResourceRef
{
public TextAsset Get()
{
return Get<TextAsset>();
}
public override System.Type ResourceType()
{
return typeof(TextAsset);
}
}
[System.Serializable]
public class AudioClipResource : ResourceRef
{
public AudioClip Get()
{
return Get<AudioClip>();
}
public override System.Type ResourceType()
{
return typeof(AudioClip);
}
}
[System.Serializable]
public class TextureResource : ResourceRef
{
public Texture Get()
{
return Get<Texture>();
}
public override System.Type ResourceType()
{
return typeof(Texture);
}
}
*/
|
using UnityEngine;
using System.Collections;
[System.Serializable]
public class ResourceRef : ScriptableObject
{
public string path;
public string GUID;
public T Get<T>() where T : Object
{
//Debug.Log("Runtime -> Loading Path:"+path+" GUID:"+GUID);
return (T)Resources.Load(path,typeof(T));
}
public ResourceRequest GetAsync<T>()
{
return Resources.LoadAsync(path,typeof(T));
}
public void Unload()
{
Resources.UnloadAsset( Resources.Load(path) );
}
public virtual System.Type ResourceType()
{
return typeof(Object);
}
public void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
}
}
/*
[System.Serializable]
public class GameObjectResource : ResourceRef
{
public GameObject Get()
{
return Get<GameObject>();
}
public override System.Type ResourceType()
{
return typeof(GameObject);
}
}
*/
/*
[System.Serializable]
public class TextAssetResource : ResourceRef
{
public TextAsset Get()
{
return Get<TextAsset>();
}
public override System.Type ResourceType()
{
return typeof(TextAsset);
}
}
[System.Serializable]
public class AudioClipResource : ResourceRef
{
public AudioClip Get()
{
return Get<AudioClip>();
}
public override System.Type ResourceType()
{
return typeof(AudioClip);
}
}
[System.Serializable]
public class TextureResource : ResourceRef
{
public Texture Get()
{
return Get<Texture>();
}
public override System.Type ResourceType()
{
return typeof(Texture);
}
}
*/
|
mit
|
C#
|
1f3caf0aacfce3f72c3dc06550a773c9401f0178
|
update quotations
|
AccountGo/accountgo,AccountGo/accountgo,AccountGo/accountgo,AccountGo/accountgo
|
src/AccountGoWeb/Views/Quotations/Quotations.cshtml
|
src/AccountGoWeb/Views/Quotations/Quotations.cshtml
|
@model string
<div>
<a href="~/quotations/addsalesquotation" class="btn">
<i class="fa fa-plus"></i>
New Quotation
</a>
<a href="~/quotations/salesquotationpdo" id="linkViewQuotation" class="btn inactiveLink">
<i class="fa fa-edit"></i>
View
</a>
<a href="" id="linkNewOrder" class="btn inactiveLink">
<i class="fa fa-plus"></i>
New Order
</a>
</div>
<div>
<div id="quotations" class="ag-fresh"></div>
</div>
<script>
var columnDefs = [
{headerName: "No", field: "no", width: 50},
{headerName: "Customer Name", field: "customerName", width: 350},
{headerName: "Date", field: "quotationDate", width: 100},
{headerName: "Amount", field: "amount", width: 100},
{headerName: "Ref no", field: "referenceNo", width: 100},
{headerName: "Status" , field: "salesQuoteStatus", width : 100}
];
var gridOptions = {
columnDefs: columnDefs,
rowData: @Html.Raw(Model),
enableSorting: true,
// PROPERTIES - simple boolean / string / number properties
rowSelection: 'single',
onSelectionChanged: onSelectionChanged,
};
function onSelectionChanged() {
var selectedRows = gridOptions.api.getSelectedRows();
selectedRow = selectedRows[0];
document.getElementById('linkViewQuotation').setAttribute('href', 'quotation?id=' + selectedRow.id);
document.getElementById('linkViewQuotation').setAttribute('class', 'btn');
if(selectedRow.status == 3)
{
document.getElementById('linkNewOrder').setAttribute('class', 'btn inactiveLink');
}
else if (selectedRow.status == 1){
document.getElementById('linkNewOrder').setAttribute('href', '/sales/salesorder?quotationId=' + selectedRow.id);
document.getElementById('linkNewOrder').setAttribute('class', 'btn');
}
if (true) {
}
}
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
var eGridDiv = document.querySelector('#quotations');
new agGrid.Grid(eGridDiv, gridOptions);
});
</script>
|
@model string
<div>
<a href="~/quotations/addsalesquotation" class="btn">
<i class="fa fa-plus"></i>
New Quotation
</a>
<a href="~/quotations/salesquotationpdo" id="linkViewQuotation" class="btn inactiveLink">
<i class="fa fa-edit"></i>
View
</a>
<a href="" id="linkNewOrder" class="btn inactiveLink">
<i class="fa fa-plus"></i>
New Order
</a>
</div>
<div>
<div id="quotations" class="ag-fresh"></div>
</div>
<script>
var columnDefs = [
{headerName: "No", field: "no", width: 50},
{headerName: "Customer Name", field: "customerName", width: 350},
{headerName: "Date", field: "quotationDate", width: 100},
{headerName: "Amount", field: "amount", width: 100},
{headerName: "Ref no", field: "referenceNo", width: 100},
{headerName: "Status" , field: "salesQuoteStatus", width : 100}
];
var gridOptions = {
columnDefs: columnDefs,
rowData: @Html.Raw(Model),
enableSorting: true,
// PROPERTIES - simple boolean / string / number properties
rowSelection: 'single',
onSelectionChanged: onSelectionChanged,
};
function onSelectionChanged() {
var selectedRows = gridOptions.api.getSelectedRows();
selectedRow = selectedRows[0];
document.getElementById('linkViewQuotation').setAttribute('href', 'quotation?id=' + selectedRow.id);
document.getElementById('linkViewQuotation').setAttribute('class', 'btn');
document.getElementById('linkNewOrder').setAttribute('href', '/sales/salesorder?quotationId=' + selectedRow.id);
document.getElementById('linkNewOrder').setAttribute('class', 'btn');
}
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function() {
var eGridDiv = document.querySelector('#quotations');
new agGrid.Grid(eGridDiv, gridOptions);
});
</script>
|
mit
|
C#
|
4ba125c396881fb16f0ed85e6035fac7ac0c6466
|
Verify exception message when application is not configured
|
appharbor/appharbor-cli
|
src/AppHarbor.Tests/ApplicationConfigurationTest.cs
|
src/AppHarbor.Tests/ApplicationConfigurationTest.cs
|
using System.IO;
using System.Text;
using Moq;
using Xunit;
namespace AppHarbor.Tests
{
public class ApplicationConfigurationTest
{
public static string ConfigurationFile = Path.GetFullPath(".appharbor");
[Fact]
public void ShouldReturnApplicationIdIfConfigurationFileExists()
{
var fileSystem = new Mock<IFileSystem>();
var applicationName = "bar";
var configurationFile = ConfigurationFile;
var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName));
fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream);
var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object);
Assert.Equal(applicationName, applicationConfiguration.GetApplicationId());
}
[Fact]
public void ShouldThrowIfApplicationFileDoesNotExist()
{
var fileSystem = new InMemoryFileSystem();
var applicationConfiguration = new ApplicationConfiguration(fileSystem);
var exception = Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId());
Assert.Equal("Application is not configured", exception.Message);
}
}
}
|
using System.IO;
using System.Text;
using Moq;
using Xunit;
namespace AppHarbor.Tests
{
public class ApplicationConfigurationTest
{
public static string ConfigurationFile = Path.GetFullPath(".appharbor");
[Fact]
public void ShouldReturnApplicationIdIfConfigurationFileExists()
{
var fileSystem = new Mock<IFileSystem>();
var applicationName = "bar";
var configurationFile = ConfigurationFile;
var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName));
fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream);
var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object);
Assert.Equal(applicationName, applicationConfiguration.GetApplicationId());
}
[Fact]
public void ShouldThrowIfApplicationFileDoesNotExist()
{
var fileSystem = new InMemoryFileSystem();
var applicationConfiguration = new ApplicationConfiguration(fileSystem);
Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId());
}
}
}
|
mit
|
C#
|
db16f0020e96bde153ce802cbdf99cd9df0f86f7
|
Make ctor internal
|
meziantou/Meziantou.Framework,meziantou/Meziantou.Framework,meziantou/Meziantou.Framework,meziantou/Meziantou.Framework
|
src/Meziantou.Framework.WPF/DispatcherExtensions.cs
|
src/Meziantou.Framework.WPF/DispatcherExtensions.cs
|
using System.Runtime.CompilerServices;
using System.Windows.Threading;
namespace Meziantou.Framework.WPF;
public static class DispatcherExtensions
{
// https://medium.com/@kevingosse/switching-back-to-the-ui-thread-in-wpf-uwp-in-modern-c-5dc1cc8efa5e
public static SwitchToUiAwaitable SwitchToDispatcherThread(this Dispatcher dispatcher)
{
return new SwitchToUiAwaitable(dispatcher);
}
public readonly struct SwitchToUiAwaitable : INotifyCompletion
{
private readonly Dispatcher _dispatcher;
internal SwitchToUiAwaitable(Dispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public SwitchToUiAwaitable GetAwaiter()
{
return this;
}
public void GetResult()
{
}
public bool IsCompleted => _dispatcher.CheckAccess();
public void OnCompleted(Action continuation)
{
_dispatcher.BeginInvoke(continuation);
}
}
}
|
using System.Runtime.CompilerServices;
using System.Windows.Threading;
namespace Meziantou.Framework.WPF;
public static class DispatcherExtensions
{
// https://medium.com/@kevingosse/switching-back-to-the-ui-thread-in-wpf-uwp-in-modern-c-5dc1cc8efa5e
public static SwitchToUiAwaitable SwitchToDispatcherThread(this Dispatcher dispatcher)
{
return new SwitchToUiAwaitable(dispatcher);
}
public readonly struct SwitchToUiAwaitable : INotifyCompletion
{
private readonly Dispatcher _dispatcher;
public SwitchToUiAwaitable(Dispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public SwitchToUiAwaitable GetAwaiter()
{
return this;
}
public void GetResult()
{
}
public bool IsCompleted => _dispatcher.CheckAccess();
public void OnCompleted(Action continuation)
{
_dispatcher.BeginInvoke(continuation);
}
}
}
|
mit
|
C#
|
d73a3cba495d40dbf57d826d32d9086a583ae411
|
Modify AssemblyFileVersion to allow build system to increment.
|
conniey/icu-dotnet,sillsdev/icu-dotnet,ermshiperete/icu-dotnet,sillsdev/icu-dotnet,ermshiperete/icu-dotnet,conniey/icu-dotnet
|
source/icu.net/Properties/AssemblyInfo.cs
|
source/icu.net/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("icu.net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL International")]
[assembly: AssemblyProduct("icu.net")]
[assembly: AssemblyCopyright("Copyright © SIL International 2007")]
[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("3439151b-347b-4321-9f2f-d5fa28b46477")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.2.1.0")]
[assembly: AssemblyFileVersion("4.2.1.*")]
//Location of the public/private key pair for strong naming this assembly --TA 7 Oct 2008
[assembly: AssemblyKeyFile("icu.net.snk")]
|
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("icu.net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SIL International")]
[assembly: AssemblyProduct("icu.net")]
[assembly: AssemblyCopyright("Copyright © SIL International 2007")]
[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("3439151b-347b-4321-9f2f-d5fa28b46477")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.2.1.0")]
[assembly: AssemblyFileVersion("4.2.1.0")]
//Location of the public/private key pair for strong naming this assembly --TA 7 Oct 2008
[assembly: AssemblyKeyFile("icu.net.snk")]
|
mit
|
C#
|
eb66d160d2b4e08a7af9e6088f02a8098e6ea9e7
|
Fix System.Tests.Perf_String.Contains (#21575)
|
billwert/corefx,DnlHarvey/corefx,wtgodbe/corefx,shimingsg/corefx,MaggieTsang/corefx,mazong1123/corefx,mmitche/corefx,zhenlan/corefx,wtgodbe/corefx,fgreinacher/corefx,fgreinacher/corefx,billwert/corefx,billwert/corefx,shimingsg/corefx,seanshpark/corefx,wtgodbe/corefx,ptoonen/corefx,seanshpark/corefx,axelheer/corefx,parjong/corefx,cydhaselton/corefx,mazong1123/corefx,ViktorHofer/corefx,mmitche/corefx,nchikanov/corefx,zhenlan/corefx,mazong1123/corefx,JosephTremoulet/corefx,zhenlan/corefx,parjong/corefx,ptoonen/corefx,twsouthwick/corefx,Ermiar/corefx,seanshpark/corefx,nchikanov/corefx,jlin177/corefx,mazong1123/corefx,cydhaselton/corefx,nchikanov/corefx,seanshpark/corefx,tijoytom/corefx,rubo/corefx,nchikanov/corefx,ptoonen/corefx,mazong1123/corefx,twsouthwick/corefx,Jiayili1/corefx,ravimeda/corefx,jlin177/corefx,JosephTremoulet/corefx,cydhaselton/corefx,JosephTremoulet/corefx,nbarbettini/corefx,wtgodbe/corefx,wtgodbe/corefx,twsouthwick/corefx,BrennanConroy/corefx,ViktorHofer/corefx,nchikanov/corefx,krk/corefx,fgreinacher/corefx,the-dwyer/corefx,ViktorHofer/corefx,JosephTremoulet/corefx,ptoonen/corefx,Jiayili1/corefx,ptoonen/corefx,shimingsg/corefx,DnlHarvey/corefx,ericstj/corefx,Jiayili1/corefx,nchikanov/corefx,BrennanConroy/corefx,DnlHarvey/corefx,krk/corefx,rubo/corefx,billwert/corefx,the-dwyer/corefx,tijoytom/corefx,cydhaselton/corefx,stone-li/corefx,tijoytom/corefx,Jiayili1/corefx,parjong/corefx,rubo/corefx,jlin177/corefx,richlander/corefx,ericstj/corefx,krk/corefx,ericstj/corefx,DnlHarvey/corefx,tijoytom/corefx,jlin177/corefx,seanshpark/corefx,nbarbettini/corefx,nbarbettini/corefx,richlander/corefx,ravimeda/corefx,richlander/corefx,MaggieTsang/corefx,ericstj/corefx,seanshpark/corefx,ViktorHofer/corefx,stone-li/corefx,krk/corefx,MaggieTsang/corefx,mmitche/corefx,krk/corefx,Jiayili1/corefx,Ermiar/corefx,DnlHarvey/corefx,tijoytom/corefx,nbarbettini/corefx,billwert/corefx,stone-li/corefx,twsouthwick/corefx,mmitche/corefx,stone-li/corefx,zhenlan/corefx,billwert/corefx,shimingsg/corefx,rubo/corefx,zhenlan/corefx,cydhaselton/corefx,stone-li/corefx,ravimeda/corefx,mazong1123/corefx,ericstj/corefx,nchikanov/corefx,stone-li/corefx,parjong/corefx,ericstj/corefx,Jiayili1/corefx,the-dwyer/corefx,yizhang82/corefx,Ermiar/corefx,shimingsg/corefx,billwert/corefx,Ermiar/corefx,Jiayili1/corefx,shimingsg/corefx,JosephTremoulet/corefx,stone-li/corefx,axelheer/corefx,yizhang82/corefx,jlin177/corefx,JosephTremoulet/corefx,Ermiar/corefx,seanshpark/corefx,ravimeda/corefx,jlin177/corefx,parjong/corefx,axelheer/corefx,twsouthwick/corefx,nbarbettini/corefx,axelheer/corefx,ViktorHofer/corefx,ericstj/corefx,JosephTremoulet/corefx,mmitche/corefx,yizhang82/corefx,ptoonen/corefx,richlander/corefx,MaggieTsang/corefx,rubo/corefx,yizhang82/corefx,zhenlan/corefx,DnlHarvey/corefx,DnlHarvey/corefx,mmitche/corefx,richlander/corefx,ravimeda/corefx,yizhang82/corefx,tijoytom/corefx,richlander/corefx,tijoytom/corefx,mazong1123/corefx,Ermiar/corefx,krk/corefx,axelheer/corefx,the-dwyer/corefx,wtgodbe/corefx,nbarbettini/corefx,yizhang82/corefx,the-dwyer/corefx,ptoonen/corefx,shimingsg/corefx,cydhaselton/corefx,parjong/corefx,parjong/corefx,BrennanConroy/corefx,MaggieTsang/corefx,twsouthwick/corefx,yizhang82/corefx,twsouthwick/corefx,zhenlan/corefx,axelheer/corefx,Ermiar/corefx,ravimeda/corefx,krk/corefx,ravimeda/corefx,fgreinacher/corefx,ViktorHofer/corefx,nbarbettini/corefx,the-dwyer/corefx,ViktorHofer/corefx,mmitche/corefx,MaggieTsang/corefx,cydhaselton/corefx,richlander/corefx,MaggieTsang/corefx,jlin177/corefx,the-dwyer/corefx,wtgodbe/corefx
|
src/System.Runtime/tests/Performance/Perf.String.netcoreapp.cs
|
src/System.Runtime/tests/Performance/Perf.String.netcoreapp.cs
|
using System.Collections.Generic;
using Microsoft.Xunit.Performance;
using Xunit;
namespace System.Tests
{
public partial class Perf_String
{
private static readonly object[] s_testStringSizes = new object[]
{
10, 100, 1000
};
public static IEnumerable<object[]> ContainsStringComparisonArgs => Permutations(s_compareOptions, s_testStringSizes);
[Benchmark]
[MemberData(nameof(ContainsStringComparisonArgs))]
public void Contains(StringComparison comparisonType, int size)
{
PerfUtils utils = new PerfUtils();
string testString = utils.CreateString(size);
string subString = testString.Substring(testString.Length / 2, testString.Length / 4);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
testString.Contains(subString, comparisonType);
}
}
}
|
using System.Collections.Generic;
using Microsoft.Xunit.Performance;
using Xunit;
namespace System.Tests
{
public partial class Perf_String
{
public static IEnumerable<object[]> ContainsStringComparisonArgs => Permutations(s_compareOptions, TestStringSizes());
[Benchmark]
[MemberData(nameof(ContainsStringComparisonArgs))]
public void Contains(StringComparison comparisonType, int size)
{
PerfUtils utils = new PerfUtils();
string testString = utils.CreateString(size);
string subString = testString.Substring(testString.Length / 2, testString.Length / 4);
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 10000; i++)
testString.Contains(subString, comparisonType);
}
}
}
|
mit
|
C#
|
3cb2fee274cd72aa17c959f6e63d30934af5e805
|
Add missing license header
|
out-of-pixel/HoloToolkit-Unity,paseb/HoloToolkit-Unity,dbastienMS/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity,willcong/HoloToolkit-Unity,ForrestTrepte/HoloToolkit-Unity,NeerajW/HoloToolkit-Unity
|
Assets/HoloToolkit-Tests/Utilities/Editor/EditorUtils.cs
|
Assets/HoloToolkit-Tests/Utilities/Editor/EditorUtils.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class EditorUtils
{
/// <summary>
/// Deletes all objects in the scene
/// </summary>
public static void ClearScene()
{
foreach (var gameObject in Object.FindObjectsOfType<GameObject>())
{
//only destroy root objects
if (gameObject.transform.parent == null)
{
Object.DestroyImmediate(gameObject);
}
}
}
}
}
|
using UnityEngine;
namespace HoloToolkit.Unity
{
public static class EditorUtils
{
/// <summary>
/// Deletes all objects in the scene
/// </summary>
public static void ClearScene()
{
foreach (var gameObject in Object.FindObjectsOfType<GameObject>())
{
//only destroy root objects
if (gameObject.transform.parent == null)
{
Object.DestroyImmediate(gameObject);
}
}
}
}
}
|
mit
|
C#
|
c83a2943ba4ccc63ffe7d9820ffcf470cd41881b
|
Add CommentModerator role
|
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
|
src/AtomicChessPuzzles/Models/UserRole.cs
|
src/AtomicChessPuzzles/Models/UserRole.cs
|
using System;
namespace AtomicChessPuzzles.Models
{
[Flags]
public enum UserRole
{
None = 0,
PuzzleReviewer = 1,
PuzzleEditor = 2,
CommentModerator = 4,
UserModerator = 8,
Admin = 16
}
}
|
using System;
namespace AtomicChessPuzzles.Models
{
[Flags]
public enum UserRole
{
None = 0,
PuzzleReviewer = 1,
PuzzleEditor = 2,
UserModerator = 4,
Admin = 8
}
}
|
agpl-3.0
|
C#
|
6fdf44d03bd622fb12d9301767aeb0791235a190
|
Add synthesis scaling coefficient to iSTFT
|
protyposis/Aurio,protyposis/Aurio
|
Aurio/Aurio/Features/InverseSTFT.cs
|
Aurio/Aurio/Features/InverseSTFT.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aurio.Streams;
namespace Aurio.Features {
/// <summary>
/// Inverse Short-Time Fourier Tranformation.
/// Takes a number of raw FFT frames and converts them to a continuous audio stream by using the overlap-add method.
/// </summary>
public class InverseSTFT : OLA {
private float[] frameBuffer;
private PFFFT.PFFFT fft;
private WindowFunction synthesisWindow;
public InverseSTFT(IAudioWriterStream stream, int windowSize, int hopSize, int fftSize, WindowType windowType, float windowNormalizationFactor)
: base(stream, windowSize, hopSize) {
if (fftSize < windowSize) {
throw new ArgumentOutOfRangeException("fftSize must be >= windowSize");
}
frameBuffer = new float[fftSize];
fft = new PFFFT.PFFFT(fftSize, PFFFT.Transform.Real);
synthesisWindow = WindowUtil.GetFunction(windowType, windowSize, windowNormalizationFactor);
}
public InverseSTFT(IAudioWriterStream stream, int windowSize, int hopSize, WindowType windowType)
: this(stream, windowSize, hopSize, windowSize, windowType, 1.0f) {
}
/// <summary>
/// Writes a raw FFT result frame into the output audio stream.
/// </summary>
/// <param name="fftResult">raw FFT frame as output by STFT in OutputFormat.Raw mode</param>
public override void WriteFrame(float[] fftResult) {
if (fftResult.Length != fft.Size) {
throw new ArgumentException("the provided FFT result array has an invalid size");
}
OnFrameWrittenInverseSTFT(fftResult);
// do inverse fourier transform
fft.Backward(fftResult, frameBuffer);
// Apply synthesis window
synthesisWindow.Apply(frameBuffer);
base.WriteFrame(frameBuffer);
}
/// <summary>
/// Flushes remaining buffered data to the output audio stream.
/// </summary>
public override void Flush() {
base.Flush();
}
protected virtual void OnFrameWrittenInverseSTFT(float[] frame) {
// to be overridden
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aurio.Streams;
namespace Aurio.Features {
/// <summary>
/// Inverse Short-Time Fourier Tranformation.
/// Takes a number of raw FFT frames and converts them to a continuous audio stream by using the overlap-add method.
/// </summary>
public class InverseSTFT : OLA {
private float[] frameBuffer;
private PFFFT.PFFFT fft;
private WindowFunction synthesisWindow;
public InverseSTFT(IAudioWriterStream stream, int windowSize, int hopSize, int fftSize, WindowType windowType)
: base(stream, windowSize, hopSize) {
if (fftSize < windowSize) {
throw new ArgumentOutOfRangeException("fftSize must be >= windowSize");
}
frameBuffer = new float[fftSize];
fft = new PFFFT.PFFFT(fftSize, PFFFT.Transform.Real);
synthesisWindow = WindowUtil.GetFunction(windowType, windowSize);
}
public InverseSTFT(IAudioWriterStream stream, int windowSize, int hopSize, WindowType windowType)
: this(stream, windowSize, hopSize, windowSize, windowType) {
}
/// <summary>
/// Writes a raw FFT result frame into the output audio stream.
/// </summary>
/// <param name="fftResult">raw FFT frame as output by STFT in OutputFormat.Raw mode</param>
public override void WriteFrame(float[] fftResult) {
if (fftResult.Length != fft.Size) {
throw new ArgumentException("the provided FFT result array has an invalid size");
}
OnFrameWrittenInverseSTFT(fftResult);
// do inverse fourier transform
fft.Backward(fftResult, frameBuffer);
// Apply synthesis window
synthesisWindow.Apply(frameBuffer);
base.WriteFrame(frameBuffer);
}
/// <summary>
/// Flushes remaining buffered data to the output audio stream.
/// </summary>
public override void Flush() {
base.Flush();
}
protected virtual void OnFrameWrittenInverseSTFT(float[] frame) {
// to be overridden
}
}
}
|
agpl-3.0
|
C#
|
2c82b15f668a62550131c462fcf6fa68e2010acf
|
Move method down.
|
alastairs/BobTheBuilder,fffej/BobTheBuilder
|
BobTheBuilder/DynamicBuilderBase.cs
|
BobTheBuilder/DynamicBuilderBase.cs
|
using System;
using System.Dynamic;
namespace BobTheBuilder
{
public abstract class DynamicBuilderBase<T> : DynamicObject, IDynamicBuilder<T> where T : class
{
protected internal readonly IArgumentStore argumentStore;
protected DynamicBuilderBase(IArgumentStore argumentStore)
{
if (argumentStore == null)
{
throw new ArgumentNullException("argumentStore");
}
this.argumentStore = argumentStore;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
return InvokeBuilderMethod(binder, args, out result);
}
public abstract bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result);
public T Build()
{
var instance = CreateInstanceOfType();
PopulatePublicSettableProperties(instance);
return instance;
}
private void PopulatePublicSettableProperties(T instance)
{
var knownMembers = argumentStore.GetAllStoredMembers();
foreach (var member in knownMembers)
{
var property = typeof (T).GetProperty(member.Name);
property.SetValue(instance, member.Value);
}
}
private static T CreateInstanceOfType()
{
var instance = Activator.CreateInstance<T>();
return instance;
}
public static implicit operator T(DynamicBuilderBase<T> builder)
{
return builder.Build();
}
}
}
|
using System;
using System.Dynamic;
namespace BobTheBuilder
{
public abstract class DynamicBuilderBase<T> : DynamicObject, IDynamicBuilder<T> where T : class
{
protected internal readonly IArgumentStore argumentStore;
protected DynamicBuilderBase(IArgumentStore argumentStore)
{
if (argumentStore == null)
{
throw new ArgumentNullException("argumentStore");
}
this.argumentStore = argumentStore;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
return InvokeBuilderMethod(binder, args, out result);
}
public abstract bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result);
public static implicit operator T(DynamicBuilderBase<T> builder)
{
return builder.Build();
}
public T Build()
{
var instance = CreateInstanceOfType();
PopulatePublicSettableProperties(instance);
return instance;
}
private void PopulatePublicSettableProperties(T instance)
{
var knownMembers = argumentStore.GetAllStoredMembers();
foreach (var member in knownMembers)
{
var property = typeof (T).GetProperty(member.Name);
property.SetValue(instance, member.Value);
}
}
private static T CreateInstanceOfType()
{
var instance = Activator.CreateInstance<T>();
return instance;
}
}
}
|
apache-2.0
|
C#
|
a2a83745049de4bd9adb9ca9e94fc3559d8ab1ad
|
Update EditableItem.axaml.cs
|
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Controls/EditableItem.axaml.cs
|
src/Core2D/Controls/EditableItem.axaml.cs
|
#nullable enable
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
namespace Core2D.Controls;
public class EditableItem : TemplatedControl
{
public static readonly StyledProperty<ContextMenu?> TextContextMenuProperty =
AvaloniaProperty.Register<EditableItem, ContextMenu?>(nameof(TextContextMenu));
public static readonly StyledProperty<IBinding?> TextBindingProperty =
AvaloniaProperty.Register<EditableItem, IBinding?>(nameof(TextBinding));
public static readonly StyledProperty<object?> IconContentProperty =
AvaloniaProperty.Register<EditableItem, object?>(nameof(IconContent));
public ContextMenu? TextContextMenu
{
get => GetValue(TextContextMenuProperty);
set => SetValue(TextContextMenuProperty, value);
}
[AssignBinding]
public IBinding? TextBinding
{
get => GetValue(TextBindingProperty);
set => SetValue(TextBindingProperty, value);
}
public object? IconContent
{
get => GetValue(IconContentProperty);
set => SetValue(IconContentProperty, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
var textBox = e.NameScope.Find<TextBox>("PART_TextBox");
var textBlock = e.NameScope.Find<TextBlock>("PART_TextBlock");
if (textBox is { } && TextBinding is { })
{
textBox.Bind(TextBox.TextProperty, TextBinding);
}
if (textBlock is { } && TextBinding is { })
{
textBlock.Bind(TextBlock.TextProperty, TextBinding);
}
}
}
|
#nullable enable
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
namespace Core2D.Controls;
public class EditableItem : TemplatedControl
{
public static readonly StyledProperty<ContextMenu?> TextContextMenuProperty =
AvaloniaProperty.Register<EditableItem, ContextMenu?>(nameof(TextContextMenu));
public static readonly StyledProperty<IBinding?> TextBindingProperty =
AvaloniaProperty.Register<EditableItem, IBinding?>(nameof(TextBinding));
public static readonly StyledProperty<object?> IconContentProperty =
AvaloniaProperty.Register<EditableItem, object?>(nameof(IconContent));
public ContextMenu? TextContextMenu
{
get => GetValue(TextContextMenuProperty);
set => SetValue(TextContextMenuProperty, value);
}
[AssignBinding]
public IBinding? TextBinding
{
get => GetValue(TextBindingProperty);
set => SetValue(TextBindingProperty, value);
}
public object? IconContent
{
get => GetValue(IconContentProperty);
set => SetValue(IconContentProperty, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
var textBox = e.NameScope.Find<TextBox>("PART_TextBox");
var textBlock = e.NameScope.Find<TextBlock>("PART_TextBlock");
if (textBox is { })
{
textBox.Bind(TextBox.TextProperty, TextBinding);
}
if (textBlock is { })
{
textBlock.Bind(TextBlock.TextProperty, TextBinding);
}
}
}
|
mit
|
C#
|
e9ca43098c3dbdaa45e5f4171e20162379366d62
|
Update WpfBrushCache.cs
|
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
|
src/Draw2D.Wpf/Renderers/WpfBrushCache.cs
|
src/Draw2D.Wpf/Renderers/WpfBrushCache.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Windows.Media;
using Draw2D.Core.Style;
namespace Draw2D.Wpf.Renderers
{
public struct WpfBrushCache : IDisposable
{
public readonly Brush Stroke;
public readonly Pen StrokePen;
public readonly Brush Fill;
public WpfBrushCache(Brush stroke, Pen strokePen, Brush fill)
{
this.Stroke = stroke;
this.StrokePen = strokePen;
this.Fill = fill;
}
public void Dispose()
{
}
public static Color FromDrawColor(DrawColor color)
{
return Color.FromArgb(color.A, color.R, color.G, color.B);
}
public static WpfBrushCache FromDrawStyle(DrawStyle style)
{
Brush stroke = null;
Pen strokePen = null;
Brush fill = null;
if (style.Stroke != null)
{
stroke = new SolidColorBrush(FromDrawColor(style.Stroke));
strokePen = new Pen(stroke, style.Thickness);
stroke.Freeze();
strokePen.Freeze();
}
if (style.Fill != null)
{
fill = new SolidColorBrush(FromDrawColor(style.Fill));
fill.Freeze();
}
return new WpfBrushCache(stroke, strokePen, fill);
}
}
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Windows.Media;
using Draw2D.Core.Style;
namespace Draw2D.Wpf.Renderers
{
public struct WpfBrushCache : IDisposable
{
public readonly Brush Stroke;
public readonly Pen StrokePen;
public readonly Brush Fill;
public WpfBrushCache(Brush stroke, Pen strokePen, Brush fill)
{
this.Stroke = stroke;
this.StrokePen = strokePen;
this.Fill = fill;
}
public void Dispose()
{
}
public static Color FromDrawColor(DrawColor color)
{
return Color.FromArgb(color.A, color.R, color.G, color.B);
}
public static WpfBrushCache FromDrawStyle(DrawStyle style)
{
Brush stroke = null;
Pen strokePen = null;
Brush fill = null;
if (style.Stroke != null)
{
stroke = new SolidColorBrush(FromDrawColor(style.Stroke));
strokePen = new Pen(stroke, style.Thickness);
stroke.Freeze();
strokePen.Freeze();
}
if (style.Fill != null)
{
fill = new SolidColorBrush(FromDrawColor(style.Fill));
fill.Freeze();
}
return new WpfBrushCache(stroke, strokePen, fill);
}
}
}
|
mit
|
C#
|
f202e8b47a3a8930c6fbbc4a2ea33732e3362a9c
|
Update BuildValuesForDirective
|
GaProgMan/OwaspHeaders.Core
|
src/Extensions/StringBuilderExtentions.cs
|
src/Extensions/StringBuilderExtentions.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OwaspHeaders.Core.Extensions
{
public static class StringBuilderExtentions
{
/// <summary>
/// Used to build the concatenated string value for the given values
/// </summary>
/// <param name="stringBuilder">The <see cref="StringBuilder" /> to use</param>
/// <param name="directiveName">The name of the CSP directive</param>
/// <param name="directiveValues">A list of strings representing the directive values</param>
/// <returns>The updated <see cref="StringBuilder" /> instance</returns>
public static StringBuilder BuildValuesForDirective(this StringBuilder @stringBuilder,
string directiveName, List<string> directiveValues)
{
if (!directiveValues.Any()) return stringBuilder;
@stringBuilder.Append(directiveName);
@stringBuilder.Append(" ");
@stringBuilder.Append(string.Join(' ', directiveValues));
@stringBuilder.Append(";");
return stringBuilder;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OwaspHeaders.Core.Extensions
{
public static class StringBuilderExtentions
{
/// <summary>
/// Used to build the concatenated string value for the given values
/// </summary>
/// <param name="stringBuilder">The <see cref="StringBuilder" /> to use</param>
/// <param name="directiveName">The name of the CSP directive</param>
/// <param name="directiveValues">A list of strings representing the directive values</param>
/// <returns>The updated <see cref="StringBuilder" /> instance</returns>
public static StringBuilder BuildValuesForDirective(this StringBuilder @stringBuilder,
string directiveName, List<string> directiveValues)
{
if (!directiveValues.Any()) return stringBuilder;
@stringBuilder.Append(directiveName);
directiveValues.Select(s => @stringBuilder.Append($"'{s}' "));
@stringBuilder.Append(";");
return stringBuilder;
}
}
}
|
mit
|
C#
|
83cccf3c4396789c1420c4eb82474b34f88e4501
|
Allow PublishingModelTests to run on dev machines (just not on TeamCity)
|
sillsdev/hearthis,sillsdev/hearthis,sillsdev/hearthis
|
src/HearThisTests/PublishingModelTests.cs
|
src/HearThisTests/PublishingModelTests.cs
|
using System;
using System.IO;
using HearThis.Publishing;
using NUnit.Framework;
using Palaso.Progress;
namespace HearThisTests
{
[TestFixture]
public class PublishingModelTests
{
[Test]
// At one point this test was ignored because it failed on the (TeamCity) server.
// I (JohnT) changed it to this category so it can be used on developer machines.
// We don't recall how or why it fails on TeamCity, or even know for sure that it still does.
// It MIGHT be something to do with whether Paratext is installed, or whether a progress dialog can be shown.
[Category("SkipOnTeamCity")]
public void Publish_PublishRootPathHasOneNewDirectory_DirectoryCreated()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
var newRandomPart = Guid.NewGuid().ToString();
m.PublishRootPath = Path.Combine(Path.GetTempPath(), newRandomPart);
var progress = new Palaso.Progress.StringBuilderProgress();
m.Publish(progress);
Assert.IsFalse(progress.ErrorEncountered);
Assert.IsTrue(Directory.Exists(m.PublishRootPath));
}
[Test]
// At one point this test was ignored because it failed on the (TeamCity) server.
// I (JohnT) changed it to this category so it can be used on developer machines.
// We don't recall how or why it fails on TeamCity, or even know for sure that it still does.
// It MIGHT be something to do with whether Paratext is installed, or whether a progress dialog can be shown.
[Category("SkipOnTeamCity")]
public void Publish_PublishRootPathHasMoreThanOneNewDirectory_DirectoryCreated()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
m.PublishRootPath = "c:/1/2/3";
m.Publish(new NullProgress());
Assert.IsTrue(Directory.Exists(m.PublishRootPath));
}
[Test]
// At one point this test was ignored because it failed on the (TeamCity) server.
// I (JohnT) changed it to this category so it can be used on developer machines.
// We don't recall how or why it fails on TeamCity, or even know for sure that it still does.
// It MIGHT be something to do with whether Paratext is installed, or whether a progress dialog can be shown.
[Category("SkipOnTeamCity")]
public void Publish_PublishRootPathIsNull_PublishRootPathIsAtSomeDefaultPlace()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
m.PublishRootPath = null;
m.Publish(new NullProgress());
Assert.IsFalse(string.IsNullOrEmpty(m.PublishRootPath));
Assert.IsTrue(Directory.Exists(m.PublishRootPath));
}
[Test]
// At one point this test was ignored because it was thought that it might fail on the (TeamCity) server.
// I (JohnT) changed it to this category so it can be used on developer machines.
// We don't recall how or why it might fail on TeamCity, or even know for sure that it ever did.
// It MIGHT be something to do with whether Paratext is installed, or whether a progress dialog can be shown.
[Category("SkipOnTeamCity")]
public void Publish_PublishRootPathIsNull_PublishThisProjectPathUnderneathMyDocuments()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
m.PublishRootPath = null;
m.Publish(new NullProgress());
Assert.IsTrue(m.PublishThisProjectPath.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), m.PublishThisProjectPath);
Assert.IsTrue(m.PublishThisProjectPath.EndsWith("HearThis-foo"), m.PublishThisProjectPath);
}
}
}
|
using System;
using System.IO;
using HearThis.Publishing;
using NUnit.Framework;
using Palaso.Progress;
namespace HearThisTests
{
[TestFixture]
public class PublishingModelTests
{
[Test, Ignore("Failing on server")]
public void Publish_PublishRootPathHasOneNewDirectory_DirectoryCreated()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
var newRandomPart = Guid.NewGuid().ToString();
m.PublishRootPath = Path.Combine(Path.GetTempPath(), newRandomPart);
var progress = new Palaso.Progress.StringBuilderProgress();
m.Publish(progress);
Assert.IsFalse(progress.ErrorEncountered);
Assert.IsTrue(Directory.Exists(m.PublishRootPath));
}
[Test, Ignore("Failing on server")]
public void Publish_PublishRootPathHasMoreThanOneNewDirectory_DirectoryCreated()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
m.PublishRootPath = "c:/1/2/3";
m.Publish(new NullProgress());
Assert.IsTrue(Directory.Exists(m.PublishRootPath));
}
[Test, Ignore("Failing on server")]
public void Publish_PublishRootPathIsNull_PublishRootPathIsAtSomeDefaultPlace()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
m.PublishRootPath = null;
m.Publish(new NullProgress());
Assert.IsFalse(string.IsNullOrEmpty(m.PublishRootPath));
Assert.IsTrue(Directory.Exists(m.PublishRootPath));
}
[Test, Ignore("might be Failing on server")]
public void Publish_PublishRootPathIsNull_PublishThisProjectPathUnderneathMyDocuments()
{
LineRecordingRepository library = new LineRecordingRepository();
var m = new PublishingModel(library, "foo");
m.PublishRootPath = null;
m.Publish(new NullProgress());
Assert.IsTrue(m.PublishThisProjectPath.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), m.PublishThisProjectPath);
Assert.IsTrue(m.PublishThisProjectPath.EndsWith("HearThis-foo"), m.PublishThisProjectPath);
}
}
}
|
mit
|
C#
|
a2a2f0007ca3a6b74bb8b6af1832c6ec6abc47af
|
Initialise list
|
FireCube-/HarvesterBot
|
TexasHoldEm/Trainer.cs
|
TexasHoldEm/Trainer.cs
|
using System;
using System.Collections.Generic;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Trainer {
private int popSize;
private List<Gene<double>> pop;
private int currentGene = 0;
private int generation = 1;
private const double crossoverSplit = 0.5;
public Trainer(int popSize = 10) {
this.popSize = popSize;
pop = new List<Gene<double>>();
for (int i = 0; i < popSize; i++) {
pop.Add(new Gene<double>(10));
}
}
public bool nextGene() {
if(++currentGene < popSize)
return true;
currentGene = 0;
return false;
}
public Gene<double> getCurrentGene() {
return this.pop[currentGene];
}
public void nextGeneration() {
generation++;
pop.Sort(geneSort); // Sorting
List<Gene<double>> fittest = getFittest();
}
private static int geneSort(Gene<double> geneA, Gene<double> geneB) {
double diff = geneA.getFitness() - geneB.getFitness();
if (diff > 0)
return 1;
if (diff < 0)
return -1;
return 0;
}
private List<Gene<double>> getFittest() {
return new List<Gene<double>>();
}
private Gene<double> crossover(Gene<double> geneA, Gene<double> geneB) {
List<double> left = geneA.getLeft(crossoverSplit);
List<double> right = geneB.getRight(1 - crossoverSplit);
left.AddRange(right);
return new Gene<double>(left);
}
}
|
using System;
using System.Collections.Generic;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Trainer {
private int popSize;
private List<Gene<double>> pop;
private int currentGene = 0;
private int generation = 1;
private const double crossoverSplit = 0.5;
public Trainer(int popSize = 10) {
this.popSize = popSize;
for (int i = 0; i < popSize; i++) {
pop[i] = new Gene<double>(10);
}
}
public bool nextGene() {
if(++currentGene < popSize)
return true;
currentGene = 0;
return false;
}
public Gene<double> getCurrentGene() {
return this.pop[currentGene];
}
public void nextGeneration() {
generation++;
pop.Sort(geneSort); // Sorting
List<Gene<double>> fittest = getFittest();
}
private static int geneSort(Gene<double> geneA, Gene<double> geneB) {
double diff = geneA.getFitness() - geneB.getFitness();
if (diff > 0)
return 1;
if (diff < 0)
return -1;
return 0;
}
private List<Gene<double>> getFittest() {
return new List<Gene<double>>();
}
private Gene<double> crossover(Gene<double> geneA, Gene<double> geneB) {
List<double> left = geneA.getLeft(crossoverSplit);
List<double> right = geneB.getRight(1 - crossoverSplit);
left.AddRange(right);
return new Gene<double>(left);
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.